 
 
/*********************************************\
*   ABSSOLUTE Oracle Objects                  *
*                                             *
*   Objects:           VIEWS                  *
*   Database version:  09.02.00               *
*   Date:              12-MAY-2018            *
\*********************************************/
 
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_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_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_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_WORKORDERLINE
 (WORKORDERLINE_ID, WORKORDER_ID, PRODNR, PRODDESCRIPTION, PRODLONGDESCRIPTION, FINMETHCODE, SIZECODE, UNIQUEYN, QUALITYGRADE, QUANTITYORDERED, QUANTITYCANCELLED, QORDER, QDONE, QOPEN, MODIFICATIONGROUPCODE, MODIFICATIONCODE, MODIFICATIONDESC, INSTRUCTIONS, LANGUAGECODE, SALESEMPLOYEE1NUMBER, SALESEMPLOYEE1NAME, SALESEMPLOYEE2NUMBER, SALESEMPLOYEE2NAME, QUALITYGRADE_CODE, REASONCODE_ID, RENTALQTYADJUSTMENT_ID, EXECUTEDBY)
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,
       e.employeenumber salesemployee1number,
       e.NAME salesemployee1name,
       ee.employeenumber salesemployee2number,
       ee.NAME salesemployee2name,
       qualitygrade.code qualitygrade_code,
       wokli.reasoncode_id, wokli.rentalqtyadjustment_id, wokli.executedby
FROM   workorderline wokli
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_link prdlk ON wokli.product_link_id = prdlk.product_link_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 employee e ON wokli.salesemployee1_id = e.employee_id
LEFT   OUTER JOIN employee ee ON wokli.salesemployee2_id = e.employee_id
 , languages

/
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_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_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_ORDERFORM_AUX_BUB
 (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, COLOUR)
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
, (select cod.description from color_desc cod where cod.color_id = g.color_id and cod.language_id = a.language_id) Colour
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
, (select cod.description from color_desc cod where cod.color_id = g.color_id and cod.language_id = a.language_id) Colour
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_ORDERFORM_AUX_CBD
 (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, PRODUCTGROUP_CODE, CUSTDELIVDAYS
, SERVICEEMPLOYEE_ID, PLANT_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(60)) 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     Stand 06.07.2017
   where dh.deliverydate >= RP.DATE_VALUE1- (select value from systemsetting where groupname = 'General'
                                            and name = 'DELIVERIESFORAVGDELVAR'
                                            and plant_id = (select bu.plant_id from businessunit bu where
                                            a.defaultbusinessunit_id = bu.businessunit_id))*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- (select value from systemsetting where groupname = 'General'
                                            and name = 'DELIVERIESFORAVGDELVAR'
                                            and plant_id = (select bu.plant_id from businessunit bu where
                                            a.defaultbusinessunit_id = bu.businessunit_id))*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
  , (select pg.code from productgroup pg where g.productgroup_id = pg.productgroup_id) productgroup_code
  ,  case  when (select max(cast(lpad(replace(pcv.version, '.', ''), 3) as numeric)) from product_component_version pcv) >= 112
  then (CAST((select listagg(dd.code, ', ') within group( order by dd.day_id) from customerdeliveryday cdd, day_desc dd
        where cdd.customer_id = a.customer_id and cdd.day_id = dd.day_id and cdd.typeofmerchadise = 1
        and dd.language_id = a.language_id and not exists
               (select 1
                        from deliveryday dyd
                       where dyd.department_id = B.department_id
                         and dyd.day_id = cdd.day_id)) AS VARCHAR2(60)) )
  else ('Only for Oracle version 11.b' )
  end CustDelivDays,
    A.SERVICEEMPLOYEE_ID SERVICEEMPLOYEE_ID,
    (select bu.plant_id  from businessunit bu where a.defaultbusinessunit_id = bu.businessunit_id) PLANT_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(60)) 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
  , (select pg.code from productgroup pg where g.productgroup_id = pg.productgroup_id) productgroup_code
  ,  case  when (select max(cast(lpad(replace(pcv.version, '.', ''), 3) as numeric)) from product_component_version pcv) >= 112
  then (CAST((select listagg(dd.code, ', ') within group( order by dd.day_id) from customerdeliveryday cdd, day_desc dd
        where cdd.customer_id = a.customer_id and cdd.day_id = dd.day_id and cdd.typeofmerchadise = 1
        and dd.language_id = a.language_id and not exists
               (select 1
                        from deliveryday dyd
                       where dyd.department_id = B.department_id
                         and dyd.day_id = cdd.day_id)) AS VARCHAR2(60)) )
  else ('Only for Oracle version 11.b' )
  end CustDelivDays,
    A.SERVICEEMPLOYEE_ID SERVICEEMPLOYEE_ID,
   (select bu.plant_id  from businessunit bu where a.defaultbusinessunit_id = bu.businessunit_id) PLANT_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_ORDERFORM_AUX_ECL
 (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, LEGACYCUSTOMERNUMBER, COLORDESC
)
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, a.legacycustomernumber
  , (select cd.description from color_desc cd where cd.color_id = g.color_id and cd.language_id = a.language_id) colordesc
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, a.legacycustomernumber
  , (select cd.description from color_desc cd where cd.color_id = g.color_id and cd.language_id = a.language_id) colordesc
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_ORDERFORM_AUX_RRA
 (REPORTPARAM_ID, COPY_NUMBER, CUSTOMERNUMBER, CUSTOMERNAME, ADDRESS, ZIPCODE, CITY, DEPARTMENTNUMBER, DEPARTMENTNAME, DEPACTIVE, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTNUMBERNAME, DISTRIBACTIVE, SIZEDEFINITIONCODE, SIZEDEFINITIONDESC, FINISHINGMETHODCODE, FINISHINGMETHODDESC, PRODUCTCODE, PRODUCTDESC, CUSTOMCODE, CUSTOMDESCRIPTION, CUSTOMER_ID, AMOUNT, DELIVERIES, ORDERINGMETHOD, ROUTELISTINSTRUCTIONS, ROUTENUMBER)
as SELECT distinct RP.REPORTPARAM_ID, rp.copy_number, A.CUSTOMERNUMBER--, A.LEGALNAME CUSTOMERNAME
, A.NAME CUSTOMERNAME
, 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, (dbms_lob.substr( rs.routelistinstructions)) routelistinstructions, r.routenumber
FROM CUSTOMER A, DEPARTMENT B, DISTRIBUTIONPOINT C, DELIVERYPOINT DP,
  PRODUCTLISTPERDISTRIBPOINT D, PRODUCTLISTPERCUSTOMER E, ADDRESS F, PRODUCT G,
  SIZEDEFINITION H, FINISHINGMETHOD I, STANDARDDELIVERYLINE J,
  REPORTPARAM RP
    left outer join (routestop rs
      left join route r on r.route_id = rs.route_id)
    on rs.routestop_id = rp.number_value1
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
union all
SELECT distinct RP.REPORTPARAM_ID, rp.copy_number, A.CUSTOMERNUMBER--, A.LEGALNAME CUSTOMERNAME
, A.NAME CUSTOMERNAME
, 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,(dbms_lob.substr(  rs.routelistinstructions)) routelistinstructions, r.routenumber
FROM CUSTOMER A, DEPARTMENT B, DISTRIBUTIONPOINT C, DELIVERYPOINT DP,
  PRODUCTLISTPERDISTRIBPOINT D, PRODUCTLISTPERCUSTOMER E, ADDRESS F, PRODUCT G,
  SIZEDEFINITION H, FINISHINGMETHOD I, STANDARDDELIVERYLINE J,
  REPORTPARAM RP
    left outer join (routestop rs
      left join route r on r.route_id = rs.route_id)
    on rs.routestop_id = rp.number_value1
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

/
create or replace view V_ORDERFORM_AUX_STK
 (REPORTPARAM_ID, COPY_NUMBER, CUSTOMERNUMBER, CUSTOMERNAME, SICCODE, ADDRESS, ZIPCODE, CITY, DEPARTMENTNUMBER, DEPARTMENTNAME, DEPACTIVE, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTNUMBERNAME, DISTRIBACTIVE, SIZEDEFINITIONCODE, SIZEDEFINITIONDESC, FINISHINGMETHODCODE, FINISHINGMETHODDESC, PRODUCTCODE, PRODUCTDESC, CUSTOMCODE, CUSTOMDESCRIPTION, CUSTOMER_ID, AMOUNT, DELIVERIES, ORDERINGMETHOD, SEQUENCENUMBER, PACKINGSEQUENCE)
as SELECT distinct RP.REPORTPARAM_ID, rp.copy_number, A.CUSTOMERNUMBER--, A.LEGALNAME CUSTOMERNAME
, A.NAME CUSTOMERNAME, a.siccode  --, NHI for STK 29-07-2010
, 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
FROM CUSTOMER A, 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
union all
SELECT distinct RP.REPORTPARAM_ID, rp.copy_number, A.CUSTOMERNUMBER--, A.LEGALNAME CUSTOMERNAME
, A.NAME CUSTOMERNAME, a.siccode --, NHI for STK 29-07-2010
, 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
FROM CUSTOMER A, 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

/
create or replace view V_SALESMONITORPERCUSTOMER_AUX
 (INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, INVOICENUMBER, ISCONSOLIDATEINV, YEAR, WEEK, FREQUENCY, 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 A.INVOICEHEADER_ID, A.PARENTINVOICEHEADER_ID, A.INVOICENUMBER,
  (CASE WHEN a.invoiceheader_id = a.parentinvoiceheader_id THEN 1 else 0 end) isconsolidateinv,
  a.invoiceyear year, a.invoiceweek week, M.FREQUENCY,
  il.processingbusinessunit_id,
  procbu.code procbucode, procbu.description procbudesc,
  f.code plant, f.name plantname,e.businessunit_id invoicingBU_id,
  e.code businessunit, e.description businessunitdesc,
  a.invoicedate,
  k.code depot, k.description depotdesc,
  j.routenumber, j.description routedesc,
  g.state state,
  h.code marketsegment,
    (SELECT description FROM marketsegment_DESC m WHERE h.marketsegment_id = m.marketsegment_id
     AND m.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) marketsegmentdesc,
  d.siccode, d.masteraccount masteraccountcust,
  o.customernumber masteraccountnumber, o.masteraccount masteraccount,
  i.code chain, i.name chainname,
  d.customernumber, d.name customername, LANGUAGES.CODE LANGUAGECODE
from invoiceheader a
    left outer join (route j left outer join depot k on j.depot_id = k.depot_id)
      on a.route_id = j.route_id, MAX_DELIVERYFREQUENCY M,
  customer d
    left outer join chain i on (d.chain_id = i.chain_id),
  address g, businessunit e, plant f, marketsegment h, status n, customer o,invoiceline il,businessunit procbu ,languages
where a.documenttype = 1
  AND A.DELTOCUSTOMER_LINK_ID = d.CUSTOMER_ID
  and d.customer_id = m.customer_id
  and a.invoicebusinessunit_id = e.businessunit_id
  and procbu.plant_id = f.plant_id
  and d.marketsegment_id = h.marketsegment_id
  and a.status_id = n.status_id
  and n.statustype = 'IN'
  and n.code = '2'
  and d.masteraccount_id = o.customer_id
  and d.visitaddress_id = g.address_id
  and il.invoiceheader_id=a.invoiceheader_id
  and il.processingbusinessunit_id=procbu.businessunit_id

/
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_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, 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)
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
, cu.customernumber, cu.name, cu.customermarkinggarment
, address.street, address.zipcode, address.city, address.state custState
, null wcustomernumber, '' wname, '' wcustomermarkinggarment
, '' wstreet, '' wzipcode, '' 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, department.description Department
, department.departmentnumber
, w.emblemname NameOnLabel, distributionpoint.description ConsPoint--, wearerfunction.description FunctionX
, (select wf.description from wearerfunction wf where we.wearerfunction_id = wf.wearerfunction_id) FunctionX
, w.remark WearerRemark, route.routenumber, route.description RouteDescription
, wok.customerowned NotLaundryOwned, status.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
, plant.code plant_code, plant.name plant_name, plant.phoneno plant_phoneno, plant.faxno plant_faxno
, plant.email plant_email, plant.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
, (select ss.value from systemsetting ss where ss.plant_id = plant.plant_id and ss.name = 'PRINTBARCODEONWORKORDER') Print_Barcode
, lan.code Language_code
, (select sy.value from systemsetting sy where sy.plant_id = plant.plant_id and sy.name = 'PRINTREPLACEMENTSONWO') 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
, bu.code bucode
from workorder wok   --left outer
            join weareremployment we  on wok.weareremployment_link_id = we.weareremployment_id --left outer join wearerfunction on we.wearerfunction_id = wearerfunction.wearerfunction_id
                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
                left outer join deliverypointopeninghour dpoh on de.deliverypoint_id=dpoh.deliverypoint_id and dpoh.day_id = getabsdaynumber(wok.neededdate)
                left outer join address adr on de.deliveryaddress_id=adr.address_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
                        join address on cu.visitaddress_id = address.address_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 employee emp on su.employee_id=emp.employee_id
 left outer join woreferencenumber worefnr on wok.woreferencenumber_id = worefnr.woreferencenumber_id
, status, businessunit bu, plant, address paddr--, SYSTEMSETTING SS
, languages lan
where wok.status_id = status.status_id
    and wok.businessunit_id = bu.businessunit_id
    and bu.plant_id = plant.plant_id
    and plant.address_id = paddr.address_id    --and ss.plant_id=plant.plant_id and ss.name='PRINTBARCODEONWORKORDER'
UNION
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
, cu.customernumber, cu.name, cu.customermarkinggarment
, address.street, address.zipcode, address.city, address.state custState
, cus.customernumber wcustomernumber, cus.name wname, cus.customermarkinggarment wcustomermarkinggarment
, addr.street wstreet, addr.zipcode wzipcode, addr.city wcity
, null WearerNr
, null WearerName, null wearersearchname, null WearerFIRSTNAME
, null Admin, null EmplNr, null CupBoard, null
, null GarmentDispenser, (select de.code from deliverypoint de where de.deliverypoint_id = distributionpoint.deliverypoint_id) DeliveryPoint, department.description Department
, department.departmentnumber
, null NameOnLabel, distributionpoint.description ConsPoint--, wearerfunction.description FunctionX
, null FunctionX
, null WearerRemark, route.routenumber, route.description RouteDescription
, wok.customerowned NotLaundryOwned, status.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
, plant.code plant_code, plant.name plant_name, plant.phoneno plant_phoneno, plant.faxno plant_faxno
, plant.email plant_email, plant.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
, (select ss.value from systemsetting ss where ss.plant_id = plant.plant_id and ss.name = 'PRINTBARCODEONWORKORDER') Print_Barcode
, lan.code Language_code
, (select sy.value from systemsetting sy where sy.plant_id = plant.plant_id and sy.name = 'PRINTREPLACEMENTSONWO') 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
, null
, null
, null
, null
, null
, null
, null
, null
, null
, null
, wok.replacement
, wok.woreferencenumber_id
, worefnr.referencenumber woreferencenr
, worefnr.description worefnr_desc
, bu.code bucode
from workorder wok
   left outer join distributionpoint
        inner join department
             inner join customer cu
                  inner join address on cu.visitaddress_id=address.address_id
             on cu.customer_id = department.customer_id
        on distributionpoint.department_id = department.department_id
   on distributionpoint.distributionpoint_id = wok.distributionpoint_link_id
   left outer join route on wok.route_id = route.route_id
   left outer join customer cus
                  inner join address  addr on cus.visitaddress_id = addr.address_id
    on cus.customer_id = wok.customer_link_id
 left outer join Systemuser su on wok.creationuser_id=su.systemuser_id
 left outer join employee emp on su.employee_id=emp.employee_id
 left outer join woreferencenumber worefnr on wok.woreferencenumber_id = worefnr.woreferencenumber_id
, status, businessunit bu, plant, address paddr--, SYSTEMSETTING SS
, languages lan
where wok.status_id = status.status_id
    and wok.businessunit_id = bu.businessunit_id
    and plant.address_id = paddr.address_id
    and bu.plant_id = plant.plant_id    --and ss.plant_id=plant.plant_id and ss.name='PRINTBARCODEONWORKORDER'
    and wok.weareremployment_link_id is null

/
create or replace view VR_SALESJOURNALAMOUNT
 (BUSINESSUNIT_ID, PROCESSBUSINESSUNIT_ID, ROUTE_ID, TURNOVERGROUP_ID, SALESJOURNALGROUP_ID, ARTRANSACTIONDATE, CASHAMOUNT, CHARGEAMOUNT, CURRENCYCODE)
as select c.businessunit_id, c.processbusinessunit_id, c.route_id, a.turnovergroup_id, a.salesjournalgroup_id,
 c.artransactiondate,
 (CASE WHEN c.paymenttype = 0 then b.amount ELSE 0 END)
 cashamount,
 (CASE WHEN c.paymenttype = 1 then b.amount ELSE 0 END)
 chargeamount,
 currency.code currencyCode
from turnovergroup a, artransactiondetail b, artransaction c, artransactiontype d, currency, invoiceheader ih
where a.turnovergroup_id = b.turnovergroup_id
 and b.artransaction_id = c.artransaction_id
 and c.artransactiontype_id = d.artransactiontype_id
 and d.typenumber in (1,3) --todo 4653
 and d.debitcredit = 'D'
 and c.debitcredit = 'D'
 and c.currency_id = currency.currency_id
 and c.invoiceheader_id = ih.invoiceheader_id
-- and (ih.parentinvoiceheader_id is null or ih.parentinvoiceheader_id = ih.invoiceheader_id) --commented for TODO3048

/
create or replace view VR_SALESJOURNALAMOUNT_AUS
 (BUSINESSUNIT_ID, PROCESSBUSINESSUNIT_ID, ROUTE_ID, TURNOVERGROUP_ID, SALESJOURNALGROUP_ID, ARTRANSACTIONDATE, CASHAMOUNT, CHARGEAMOUNT, CURRENCYCODE, INVOICEDATE)
as select c.businessunit_id, c.processbusinessunit_id, c.route_id, a.turnovergroup_id, a.salesjournalgroup_id,
 c.artransactiondate,
 (CASE WHEN c.paymenttype = 0 then b.amount ELSE 0 END)
 cashamount,
 (CASE WHEN c.paymenttype = 1 then b.amount ELSE 0 END)
 chargeamount,
 currency.code currencyCode
 ,ih.invoicedate
from turnovergroup a, artransactiondetail b, artransaction c, artransactiontype d, currency, invoiceheader ih
where a.turnovergroup_id = b.turnovergroup_id
 and b.artransaction_id = c.artransaction_id
 and c.artransactiontype_id = d.artransactiontype_id
 and d.typenumber in (1,3) --todo 4653
 and d.debitcredit = 'D'
 and c.debitcredit = 'D'
 and c.currency_id = currency.currency_id
 and c.invoiceheader_id = ih.invoiceheader_id
-- and (ih.parentinvoiceheader_id is null or ih.parentinvoiceheader_id = ih.invoiceheader_id) --commented for TODO3048

/
create or replace view VR_SALESJOURNALAMOUNT_SMG
 (BUSINESSUNIT_ID, PROCESSBUSINESSUNIT_ID, ROUTE_ID, TURNOVERGROUP_ID, SALESJOURNALGROUP_ID, ARTRANSACTIONDATE, CASHAMOUNT, CHARGEAMOUNT, CURRENCYCODE)
as select c.businessunit_id, c.processbusinessunit_id, c.route_id, a.turnovergroup_id, a.salesjournalgroup_id,
 c.artransactiondate,
 currency.exchangerate * (CASE WHEN c.paymenttype = 0 then b.amount ELSE 0 END) cashamount,
 currency.exchangerate * (CASE WHEN c.paymenttype = 1 then b.amount ELSE 0 END) chargeamount,
 currency.code currencyCode
from turnovergroup a, artransactiondetail b, artransaction c, artransactiontype d, currency, invoiceheader ih
where a.turnovergroup_id = b.turnovergroup_id
 and b.artransaction_id = c.artransaction_id
 and c.artransactiontype_id = d.artransactiontype_id
 and d.typenumber in (1,3) --todo 4653
 and d.debitcredit = 'D'
 and c.debitcredit = 'D'
 and currency.currency_id = coalesce(c.plantcountrycurrency_id, c.currency_id)
 and c.invoiceheader_id = ih.invoiceheader_id
-- and (ih.parentinvoiceheader_id is null or ih.parentinvoiceheader_id = ih.invoiceheader_id) --commented for TODO3048

/
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_AGEANALYSIS_ROUTE
 (CUSTOMER_ID, EXPDATE, ROUTE_ID, REPORTPARAM_ID)
as select c.customer_id,
  (select max(cp.dateinactive) from contractspercustomer cp where
     c.customer_id = cp.customer_id) expdate,
  --max(cp.dateinactive) expdate,
  GET_ROUTEANDFILTER(rp.reportparam_id, c.customer_id) ROUTE_ID,
  rp.reportparam_id
from customer c, reportparam rp--contractspercustomer cp
--where c.customer_id = cp.customer_id
--group by c.customer_id, rp.reportparam_id

/
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_BILLTOCOMPANY_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.address_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.address_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.address_id = a.address_id
where poh.billtocompany = 2

/
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' )
        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' )
        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'
            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'
            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_OUTSCANNEDIDS_LTS
 (PRIMARYID, UNIQUERESIDENTIALITEM_ID, CLIENTDELIVERYNOTE_ID, LANGUAGECODE, PRODDESC, PRODCODE, FM_DESC)
as select uri.primaryid, uri.uniqueresidentialitem_id, cdn.clientdeliverynote_id, lan.code languagecode,
       (select pd.description from product_desc pd where cdnl.product_link_id = pd.product_id and pd.language_id = lan.language_id) proddesc,
       (select p.code from product p where p.product_id = cdnl.product_link_id) prodcode,
       (select fd.description from finishingmethod_desc fd where fd.finishingmethod_id = cdnl.finishingmethod_id and fd.language_id = lan.language_id) fm_desc
from clientdeliverynote cdn, clientdeliverynoteline cdnl, uniqueresidentialitem uri,
     clientdelnotelinescan cds, languages lan
where cdn.clientdeliverynote_id = cdnl.clientdeliverinote_id
      and cds.outscanclientdelnoteline_id = cdnl.clientdeliverynoteline_id
      and uri.uniqueresidentialitem_id = cds.uniqueresidentialitem_link_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.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
, 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
, 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_CIRCINV_BDM
 (INVOICEHEADER_ID, INVOICELINE_ID, CHANGESPERWEEK, NUMBEREMPLOYMENTSCHARGE, MAXINV, CIRCINV, SIZECODE, COSTCENTER_ID)
as select h.invoiceheader_id, l.invoiceline_id, sqt.changesperweek, sqt.numberemploymentscharge, sqt.maxinv, sqt.totalcircinv circinv, (select sd.code from sizedefinition sd where sd.sizedefinition_id= sqt.sizedefinition_link_id) sizecode, cc.costcenter_id
from   invoiceheader h inner join invoiceline l on  h.invoiceheader_id = l.invoiceheader_id
 left outer join invoicelineproduct lp on lp.invoiceline_id = l.invoiceline_id,
 statusquoheader sq join sqsetincirculation sqt on sq.statusquoheader_id=sqt.statusquoheader_id
join distributionpoint dp on sqt.distributionpoint_link_id = dp.distributionpoint_id
join costcenter cc on cc.costcenter_id=dp.costcenter_id
 where sqt.customer_link_id = h.deltocustomer_link_id
         and sq.statusquotype = 2
         and sq.year = year(h.enddate)
         and  sq.week in (select cri.week from costreportinfo cri where cri.invoiceline_id=l.invoiceline_id)
         and sqt.totalcircinv > 0
         and sqt.product_link_id =  lp.product_link_id
          and (sqt.sizedefinition_link_id=lp.sizedefinition_link_id or lp.sizedefinition_link_id=(select sd.sizedefinition_id from sizedefinition sd where sd.code='*'))
         and cc.code= h.splitupcode
 and h.splitupcode is not null
 and lp.invoiceqtycolumn=sqt.changesperweek
 union all
 select h.invoiceheader_id,l.invoiceline_id, sqt.changesperweek,sqt.numberemploymentscharge, sqt.maxinv, sqt.totalcircinv circinv, (select sd.code from sizedefinition sd where sd.sizedefinition_id= sqt.sizedefinition_link_id) sizecode, cc.costcenter_id
from   invoiceheader h inner join invoiceline l on  h.invoiceheader_id = l.invoiceheader_id
 left outer join invoicelineproduct lp on lp.invoiceline_id = l.invoiceline_id,
 statusquoheader sq join sqsetincirculation sqt on sq.statusquoheader_id=sqt.statusquoheader_id
join distributionpoint dp on sqt.distributionpoint_link_id = dp.distributionpoint_id
join costcenter cc on cc.costcenter_id=dp.costcenter_id
 where sqt.customer_link_id = h.deltocustomer_link_id
         and sq.statusquotype = 2
         and sq.year = year(h.enddate)
         and sq.week  in (select cri.week from costreportinfo cri where cri.invoiceline_id=l.invoiceline_id)
         and sqt.totalcircinv > 0
         and sqt.product_link_id =  lp.product_link_id
          and (sqt.sizedefinition_link_id=lp.sizedefinition_link_id or lp.sizedefinition_link_id=(select sd.sizedefinition_id from sizedefinition sd where sd.code='*'))
 and h.splitupcode is null
and lp.invoiceqtycolumn=sqt.changesperweek

/
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_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_CLIENTDELIVERYNOTE_FLAG
 (PRINTIDCODE, UNIQUERESIDENTIALITEM_LINK_ID, SCANTIMESTAMP, LANGUAGE_CODE, FLAGCODE, FLAGDESC)
as select 'Y' printidcode, ris.uniqueresidentialitem_link_id, GETDATEONLY(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 GETDATEONLY(cds.outscantimestamp) = GETDATEONLY(ris.scantimestamp)
--union all select 'N' printidcode, null, null, null, null, null from dual

/
create or replace view V_CLIENTDEPARTMENT
 (CUSTOMER_ID, CLIENT_ID, CLIENTNUMBER, CLIENT_SEARCHNAME, CLIENT_NAME, DEPARTMENT_ID, DEPARTMENTNUMBER, DEP_DESC, ROOMNUMBER)
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
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_COMMON_CUST_ID_AMM
 (DEBTOR_ID, CUSTOMER_ID, COMMONCUSTOMER_ID, COMMON_ID)
as select c.debtor_id, c.customer_id, c.commoncustomer_id,
Case When statementpercustomer in ('N', 'Y') then c.debtor_id
     else
     Case When statementpercustomer is null and c.commoncustomer_id is null then
          Case When Exists  (select c.customer_id from customer x, customerbillinginfo xcb
                  where x.debtor_id = xcb.customer_id AND x.customer_id = c.debtor_id and xcb.statementpercustomer = 'Y')
               Then (select max(c.customer_id) from customer x, customerbillinginfo xcb
                  where x.debtor_id = xcb.customer_id AND x.customer_id = c.debtor_id and xcb.statementpercustomer = 'Y')
               When Exists (select debtor_id from customer x, customerbillinginfo xcb
                  where x.debtor_id = xcb.customer_id AND x.customer_id = c.debtor_id and xcb.statementpercustomer = 'N')
               Then (select max(debtor_id) from customer x, customerbillinginfo xcb
                  where x.debtor_id = xcb.customer_id AND x.customer_id = c.debtor_id and xcb.statementpercustomer = 'N')
               else c.commoncustomer_id
          End
     else c.commoncustomer_id
     End
End as common_id
from customer c left outer join customerbillinginfo cb
       on c.debtor_id = cb.customer_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_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_CONSIGNOTE_PROD_EDE
 (PRODUCT_ID, PACKINGNOTELINE_ID, PROD_CODE, LANGUAGE_ID, DELIVEREDAMOUNT, PACKINGNOTE_ID, SIZECODE, DESCRIPTION)
as select p.product_id
  , l.packingnoteline_id
  , p.code Prod_code, lan.language_id, l.deliveredamount, l.packingnote_id,
  (select sd.code from sizedefinition sd where sd.sizedefinition_id=l.sizedefinition_id) sizecode,
  (select pd.description from product_desc pd where pd.product_id=p.product_id and pd.language_id=lan.language_id) description
from packingnoteline l, packingnotelinecontent lc, product p, languages lan
where l.packingnoteline_id = lc.packingnoteline_id and lc.product_id= p.product_id --and p.packtype <> 0
union all
select p.product_id
  ,    l.packingnoteline_id
  ,    p.code Prod_code, lan.language_id, l.deliveredamount, l.packingnote_id,
  (select sd.code from sizedefinition sd where sd.sizedefinition_id=l.sizedefinition_id) sizecode,
    (select pd.description from product_desc pd where pd.product_id=p.product_id and pd.language_id=lan.language_id) description
from packingnoteline l, product p, languages lan
where l.product_id= p.product_id

/
create or replace view V_CONSIG_CNT_ECL
 (PACKINGNOTE_ID, TAREWEIGHT, GROSSWEIGHT, CONTAINER_PRIMARYID, CONTAINERTYPE_CODE, WEIGHINGCATEGORYDESC, CONTAINERTYPE_DESC, LANGUAGECODE)
as select  pnc.packingnote_id, pnc.tareweight, pnc.grossweight,
       (select c.primaryid
       from container c
       where c.container_id = pnc.container_id) CONTAINER_PRIMARYID,
       ct.code CONTAINERTYPE_CODE,
       (select wd.description from weighingcategory_desc wd
        where wd.weighingcategory_id = w.weighingcategory_id and wd.language_id = LANGUAGES.LANGUAGE_ID) weighingcategorydesc,
       (select CTD.DESCRIPTION from CONTAINERTYPE_DESC CTD
        where CTD.CONTAINERTYPE_ID = CT.CONTAINERTYPE_ID and CTD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) CONTAINERTYPE_DESC,
       LANGUAGES.Code LANGUAGECODE
from PACKINGNOTECONTAINER pnc
        left outer join CONTAINERTYPE CT on CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
        left outer join WEIGHINGCATEGORY W on W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID,
     LANGUAGES

/
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_CONTRACTEXPIRATION_RC_HUE
 (CUSTOMER_ID, CUSTOMERNUMBER, NAME, DEFAULTBUSINESSUNIT_ID, MAILADDRESS_ID, PHONENO, ACTIVE, ROUTENUMBER, DRIVINGDAY_ID)
as select distinct cu.customer_id, cu.customernumber, cu.name,
  cu.defaultbusinessunit_id, cu.mailaddress_id, cu.phoneno, cu.active,
  r.routenumber, MIN(r.drivingday_id) drivingday_id
from route r, routestop rs, customer cu
where r.route_id = rs.route_id
  and rs.customer_id = cu.customer_id
GROUP BY cu.customer_id, cu.customernumber, cu.name, cu.defaultbusinessunit_id, cu.mailaddress_id, cu.phoneno, cu.active, r.routenumber

/
create or replace view V_COSTCENTERINVOICELINE
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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 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.adjustmentpermited, 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,
       cc.code costcenter_code, cc.description costcenter_description,
       nvl(ccil.quantity, a.billedqty) costcenterinvoiceline_quantity, nvl(ccil.amount, a.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,
       nvl((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), 0) totalamountexclvat
, (select ilstd.description from invoicelinesubtype ilst, invoicelinesubtype_desc ilstd where ilst.invoicelinetype_id = a.invoicelinetype_id
            and ilst.subtype=a.invoicelinesubtype and ilstd.invoicelinesubtype_id = ilst.invoicelinesubtype_id and ilstd.language_id = languages.language_id) subtype_desc
, (select coc.ponumber from costcenter coc where coc.costcenter_id = ccil.costcenter_link_id) costcenter_ponumber
from invoiceheader f, invoiceline a
       left outer join costcenterinvoiceline ccil
           inner join costcenter_link cc on (ccil.costcenter_link_id = cc.costcenter_link_id)
       on ccil.invoiceline_id = a.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), languages
where  a.invoiceheader_id = f.invoiceheader_id
and    f.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 GETCURRENTDATE() 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 GETCURRENTDATE() 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 GETCURRENTDATE() 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 GETCURRENTDATE() 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 GETCURRENTDATE() 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_DET
 (BILLTOCUSTOMER_LINK_ID, AMOUNT, INVOICENUMBER, INVOICEDATE, ARTRANSACTIONDATE, DUEDATE, REPORTPARAM_ID, DATE_VALUE1)
as SELECT coalesce(Y.Deltocustomer_Link_Id, y.billtocustomer_link_id) BILLTOCUSTOMER_LINK_ID
, (Y.AMOUNT-Y.Totalappliedamount) AMOUNT, Y.INVOICENUMBER, Y.ARTRANSACTIONDATE INVOICEDATE, Y.ARTRANSACTIONDATE
, (select max(i.paymenttermsduedate) from invoiceheaderextrainfo i where y.invoiceheader_id = i.invoiceheader_id) duedate
, rp.reportparam_id, rp.date_value1
FROM ARTRANSACTION Y, reportparam rp, artransactiontype Z
WHERE y.artransactiontype_ID = z.artransactiontype_ID --Y.CLOSINGTRANSACTION_ID IS NULL
  AND Y.DEBITCREDIT = 'D' and Y.Isopen_Yn = 'Y' and z.typenumber <> 2
  AND (Y.PARENTARTRANSACTION_ID IS NULL OR Y.PARENTARTRANSACTION_ID=Y.ARTRANSACTION_ID)

/
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_DELIVERYNOTEAPPENDIX_AUX
 (WEIGHINGCATEGORYCODE, WEIGHINGCATEGORYDESC, WEIGHTQTY, NOTENUMBER, PACKINGNOTE_ID, SHOWONINVOICEAPPENDIX, ORIGIN, CUSTOMERNUMBER, WEIGHTPRICE, WEIGHTDISCOUNT, LANGUAGECODE)
as select
  wgh.code weighingcategoryCode
, ( select weighingcategory_desc.description from weighingcategory_desc where weighingcategory_desc.weighingcategory_id = wgh.weighingcategory_id
  and weighingcategory_desc.language_id = languages.language_id ) weighingcategoryDesc
, (pnc.grossweight - pnc.tareweight) WeightQty
, pn.notenumber, pnc.packingnote_id
, pn.showoninvoiceappendix,pn.origin --todo6892
, CU.CUSTOMERNUMBER
, pack_price.Weight_Price(cu.customer_id, wgh.weighingcategory_id, case when whgcu.invoicemethod = 4 then 'Y'
else 'N' end, GETCURRENTDATE()) WeightPrice
, coalesce(pack_price.Weight_Discount(cu.customer_id, wgh.weighingcategory_id,  'N', GETCURRENTDATE()), 0) WeightDiscount
, languages.code languageCode
from
  customer cu
, weighingcategpercustomer whgcu, weighingcategory wgh, packingnotecontainer pnc, packingnote pn
, languages
where
    cu.customer_id = whgcu.customer_id and
    ((whgcu.weightclean = 'Y' and whgcu.invoicemethod = 3) --> todo4062
    or
    (whgcu.weightclean = 'N' and whgcu.invoicemethod = 4)) --<
and GETCURRENTDATETIME() between whgcu.dateactive and whgcu.dateinactive
    and whgcu.weighingcategory_id = wgh.weighingcategory_id
        and wgh.weighingcategory_id = pnc.weighingcategory_id
            and pnc.packingnote_id = pn.packingnote_id

/
create or replace view V_DELIVERYNOTE_KNT
 (PACKINGNOTE_ID, SEQUENCENUMBER, TAREWEIGHT, GROSSWEIGHT, SOILPORTION, WEIGHTDECIMALS, WEIGHINGSEQUENCENR, WEIGHINGTIMESTAMP, CONTAINER_PRIMARYID, CONTAINERTYPE_CODE, CONTAINERTYPE_DEFAULTTARAW, CONTAINERTYPE_ACTIVE, DISINFECTBEFOREDELIVERY, WEIGHCAT_CODE, WEIGHCAT_LEGACYCODE, WEIGHINGCATEGORYDESC, CONTAINERTYPE_DESC, PRICE, AMOUNT, TAXGROUPCODE, WEIGHINGUSE, EXTRAINPUT, SPREGUNIT, REGUNITDECIMALS, SPECIALQUANTITY, SPECIALLENGTH, SPECIALWIDTH, LANGUAGECODE)
as select --+index(pnc XAK1PACKINGNOTECONTAINER) index(CT XPKCONTAINERTYPE)
       pnc.packingnote_id, pnc.sequencenumber, pnc.tareweight, pnc.grossweight,
       pnc.soilportion, pnc.weightdecimals, pnc.weighingsequencenr, pnc.weighingtimestamp,
       (select c.primaryid
       from container c
       where c.container_id = pnc.container_id) CONTAINER_PRIMARYID,
       ct.code CONTAINERTYPE_CODE, ct.defaulttaraweight CONTAINERTYPE_DEFAULTTARAW,
       ct.active CONTAINERTYPE_ACTIVE, ct.disinfectbeforedelivery,
       w.code WEIGHCAT_CODE, w.legacyweighingcategorycode WEIGHCAT_LEGACYCODE,
       (select wd.description from weighingcategory_desc wd
        where wd.weighingcategory_id = w.weighingcategory_id and wd.language_id = LANGUAGES.LANGUAGE_ID) weighingcategorydesc,
       (select CTD.DESCRIPTION from CONTAINERTYPE_DESC CTD
        where CTD.CONTAINERTYPE_ID = CT.CONTAINERTYPE_ID and CTD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) CONTAINERTYPE_DESC,
       pnc.price, pnc.amount, pnc.taxgroupcode,
       coalesce(w.weighinguse,0) weighinguse,w.extrainput,
        (select rg.code from  registrationunit rg where rg.registrationunit_id= w.registrationunit_id) spregunit,
        (select rg.decimals from  registrationunit rg where rg.registrationunit_id= w.registrationunit_id) regunitdecimals,
        pnc.specialquantity, pnc.speciallength, pnc.specialwidth,
       LANGUAGES.Code LANGUAGECODE
from PACKINGNOTECONTAINER pnc
      --  left outer join CONTAINER C on C.CONTAINER_ID = PNC.CONTAINER_ID
        left outer join CONTAINERTYPE CT on CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
        left outer join WEIGHINGCATEGORY W on W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID,
     LANGUAGES

/
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)
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 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
  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)
                  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 and
       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 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
  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)
                  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, 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
       ui_link.uniqueitem_link_id = ds.uniqueitem_link_id and
       ui.uniqueitem_id = ui_link.uniqueitem_id and
       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 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
  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)
                  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, wearer w
 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 and
       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 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
  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)
                  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, wearer w
 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_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 io.orderdate from internetorder IO, internetorderline iol
  where iol.deliveryvariations_id = dv.deliveryvariations_id and io.internetorder_id = iol.internetorder_id)
                   , GETDATEONLY(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_DELIVERYVARIATIONS_FIS
 (CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDESCRIPTION, FINISHINGMETHODCODE, FINISHINGMETHODDESCRIPTION, PACKINGNOTENUMBER, PROCESSBUSINESSUNIT_ID, DELIVERYDATE, ORIGIN, AMOUNT, FIXEDAMOUNT, REFERENCE, PROCESSED, CAUSENOTENUMBER, CAUSENOTEDELIVERYDATE, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE, UPDATERENTQTY, SOILCOUNTSUBTYPE)
as SELECT
       CUSTOMER.CUSTOMERNUMBER
,      CUSTOMER.NAME CUSTOMERNAME
,      DEPARTMENT.DEPARTMENTNUMBER
,      DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION
,      DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER
,      DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION
,      PRODUCT.CODE PRODUCTCODE
,      ( SELECT DESCRIPTION
         FROM   PRODUCT_DESC P
         WHERE  P.PRODUCT_ID = DELIVERYVARIATIONS.PRODUCT_ID
            AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) PRODUCTDESCRIPTION
,      ( SELECT DESCRIPTION
         FROM   SIZEDEFINITION_DESC S
         WHERE  S.SIZEDEFINITION_ID = DELIVERYVARIATIONS.SIZEDEFINITION_ID
            AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) SIZEDESCRIPTION
,      FINISHINGMETHOD.CODE FINISHINGMETHODCODE
,      ( SELECT DESCRIPTION
         FROM   FINISHINGMETHOD_DESC F
         WHERE  F.FINISHINGMETHOD_ID = DELIVERYVARIATIONS.FINISHINGMETHOD_ID
            AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) FINISHINGMETHODDESCRIPTION
,      PACKINGNOTE.NOTENUMBER PACKINGNOTENUMBER
,      PACKINGNOTE.PROCESSBUSINESSUNIT_ID
,      DELIVERYVARIATIONS.DELIVERYDATE
,      DELIVERYVARIATIONS.ORIGIN
,      DELIVERYVARIATIONS.AMOUNT
,      DELIVERYVARIATIONS.FIXEDAMOUNT
,      DELIVERYVARIATIONS.REFERENCE
,      DELIVERYVARIATIONS.PROCESSED
,      CAUSENOTE.NOTENUMBER CAUSENOTENUMBER
,      CAUSENOTE.DELIVERYDATE CAUSENOTEDELIVERYDATE
,      DELIVERYVARIATIONS.SYSTEMUSER_ID
,      GETDATEONLY(DELIVERYVARIATIONS.TIMESTAMP) TIMESTAMP
,      LANGUAGES.CODE LANGUAGECODE
,      DELIVERYVARIATIONS.UPDATERENTQTY
,      DELIVERYVARIATIONS.SOILCOUNTSUBTYPE
FROM   CUSTOMER
,      DEPARTMENT
,      DISTRIBUTIONPOINT
,      PRODUCT
,      FINISHINGMETHOD
,      LANGUAGES
,      DELIVERYVARIATIONS
         LEFT OUTER JOIN PACKINGNOTE
           ON (DELIVERYVARIATIONS.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID)
         LEFT OUTER JOIN PACKINGNOTE CAUSENOTE
           ON (DELIVERYVARIATIONS.CAUSENOTE_ID = CAUSENOTE.PACKINGNOTE_ID)
WHERE  DELIVERYVARIATIONS.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
   AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
   AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
   AND DELIVERYVARIATIONS.PRODUCT_ID = PRODUCT.PRODUCT_ID
   AND DELIVERYVARIATIONS.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
   AND DEPARTMENT.ACTIVE = 'Y'

/
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, CITY, DEPARTMENTNUMBER, DEPARTMENTDESC, 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
  cu.customernumber, cu.name customerName, address.city, dep.departmentnumber, dep.description departmentDesc
, we.wearernumber, we.fullname wearerName, wey.sequencenumber, cu.active, cu.dateactive, cu.dateinactive
, wef.code functionCode
, prd.code productCode, sz.code sizeCode
, ( select product_desc.description from product_desc where product_desc.product_id = weinv.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = weinv.sizedefinition_id
  and sdd.language_id = languages.language_id ) sizeDesc
, sum(weinv.maxinventory) maxinventory, sum(weinv.circinventory) circinventory
, sum(weinv.qtytobereturnedreplacement) qtytobereturnedreplacement
, sum(weinv.qtytobereturneddecreasemax) qtytobereturneddecreasemax
, coalesce((select count(*)
    from uniqueitemnonpool uinp, uniqueitemflag uif, automaticflag afl, uniqueitem ui
    where uinp.uniqueitem_id=uif.uniqueitem_id and uif.flag_id=afl.flag_id
       and uinp.uniqueitem_id = ui.uniqueitem_id
       and 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(*)
    from nonuniqueitem nui, automaticflag afl
    where nui.flag_id = afl.flag_id
       and 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
, pa.processbusinessunit_id
, pa.internalprocessingbu_id
, languages.Code languageCode
from
  wearerinventory weinv
, weareremployment wey
         left outer join wearerfunction wef on wey.wearerfunction_id = wef.wearerfunction_id
, wearer we, distributionpoint dip, department dep, customer cu, address
, product prd, sizedefinition sz
, languages
, (select p.product_id, ca.customer_id, ca.processbusinessunit_id, ca.internalprocessingbu_id
  from customeractivities ca, productgroup pg, product p
  where pg.activity_id = ca.activity_id
  and p.productgroup_id = pg.productgroup_id) pa
where
    weinv.weareremployment_id = wey.weareremployment_id
and wey.wearer_id = we.wearer_id
and wey.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 weinv.product_id = prd.product_id
and weinv.sizedefinition_id = sz.sizedefinition_id
and pa.customer_id = cu.customer_id
and pa.product_id = weinv.product_id
GROUP BY
  cu.customernumber, cu.name , address.city, dep.departmentnumber, dep.description
, we.wearernumber, we.fullname, we.dateinactive , weinv.dateinactive
, wey.sequencenumber, wef.code
, prd.code, sz.code
, wey.weareremployment_id, weinv.product_id, weinv.sizedefinition_id
, cu.defaultbusinessunit_id
, pa.processbusinessunit_id
, pa.internalprocessingbu_id
, languages.language_id, languages.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
  sum( wokli.quantityordered - wokli.quantityfilled - wokli.quantitycancelled ) OutStandingQty
, wok.weareremployment_link_id, wokli.product_link_id, wokli.sizedefinition_link_id
from
  workorder wok, status, workorderline wokli, reasoncode
where
    wok.status_id = status.status_id
and status.statustype = 'WO' -- work order
    and status.code <> '40' and status.code <> '30' -- completed and cancelled
and wok.workorder_id = wokli.workorder_id
    and wokli.reasoncode_id = reasoncode.reasoncode_id
        and reasoncode.inventorytrigger <> 5 -- do not trigger free of charge
group by
 wok.weareremployment_link_id, wokli.product_link_id, wokli.sizedefinition_link_id

/
create or replace view V_DEVIATEDCIRCINV_NIX
 (ROUTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CITY, DEPARTMENTNUMBER, DEPARTMENTDESC, WEARERNUMBER, WEARERNAME, SEQUENCENUMBER, FUNCTIONCODE, SEARCHNAME, PRODUCTCODE, SIZECODE, PRODUCTDESC, MAXINVENTORY, CIRCINVENTORY, QTYTOBERETURNEDREPLACEMENT, QTYTOBERETURNEDDECREASEMAX, QTYTOBERETURNED, WEAREREMPLOYMENT_ID, PRODUCT_ID, SIZEDEFINITION_ID, WEARERDATEINACTIVE, WEARERINVENTORYDATEINACTIVE, DEFAULTBUSINESSUNIT_ID, WEARERINVENTORY_ID, LANGUAGECODE)
as select (select max(ro.routenumber) from routestop rs, route ro where rs.customer_id = cu.customer_id and rs.route_id = ro.route_id) routenumber,
  cu.customernumber, cu.name customerName, address.city, dep.departmentnumber, dep.description departmentDesc
, we.wearernumber, we.fullname wearerName, wey.sequencenumber
, wef.code functionCode, cu.searchname
, prd.code productCode, sz.code sizeCode
, ( select product_desc.description from product_desc where product_desc.product_id = weinv.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, sum(weinv.maxinventory) maxinventory, sum(weinv.circinventory) circinventory
, sum(weinv.qtytobereturnedreplacement) qtytobereturnedreplacement
, sum(weinv.qtytobereturneddecreasemax) qtytobereturneddecreasemax
, sum(weinv.qtytobereturnedreplacement + weinv.qtytobereturneddecreasemax) qtyToBeReturned
, wey.weareremployment_id, weinv.product_id, weinv.sizedefinition_id
, we.dateinactive wearerdateinactive, weinv.dateinactive wearerINVENTORYdateinactive
, cu.defaultbusinessunit_id, weinv.wearerinventory_id
, languages.Code languageCode
from
  wearerinventory weinv
, weareremployment wey
         left outer join wearerfunction wef on wey.wearerfunction_id = wef.wearerfunction_id
, wearer we, distributionpoint dip, department dep, customer cu, address
, product prd, sizedefinition sz
, languages
where
    weinv.weareremployment_id = wey.weareremployment_id
and wey.wearer_id = we.wearer_id
and wey.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 weinv.product_id = prd.product_id
and weinv.sizedefinition_id = sz.sizedefinition_id
GROUP BY
  cu.customer_id, cu.customernumber, cu.name , address.city, dep.departmentnumber, dep.description
, we.wearernumber, we.fullname, we.dateinactive , weinv.dateinactive
, wey.sequencenumber, wef.code, cu.searchname
, prd.code, sz.code
, wey.weareremployment_id, weinv.product_id, weinv.sizedefinition_id
, cu.defaultbusinessunit_id
, languages.language_id, languages.Code
, weinv.wearerinventory_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_DVREFERENCE
 (CONSIGNMENTNOTE_ID, REFERENCE)
as select distinct pn.consignmentnote_id, dv.reference
from deliveryvariations dv join packingnote pn on dv.packingnote_id=pn.packingnote_id

/
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_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_INVOICEADDITION_AUX_BNL
 (INVOICELINE_ID, WEAREREMPLOYMENT_LINK_ID, SEQUENCENUMBER, YEAR, WEEK, MINYEARWEEK, QUANTITY, NO_OF_WEEKS)
as select ia.invoiceline_id, ia.weareremployment_link_id, ia.sequencenumber,
	MIN(ia.year) YEAR, MIN(ia.week) WEEK, MIN(ia.year*100+ia.week) minyearweek,
       MIN(ia.quantity) QUANTITY, COUNT(distinct (IA.YEAR*100+IA.WEEK)) NO_OF_WEEKS
from invoicelineaddition ia
group by ia.invoiceline_id, ia.weareremployment_link_id, ia.sequencenumber

/
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_INVOICEDAMNTCOMPAR_PLPC_LLG
 (CUSTOMER_ID, MINIMUMTURNAROUND, TOTALINCIRC, RENT_PRICE)
as select plpc.customer_id,
plpc.minimumturnaround,
(select sum(rqa.quantity) from rentalqtyadjustment rqa
   where rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
   and rqa.adjustmentdate <= sysdate
   and rqa.origin <> 2
   and rqa.sampleitem = 'N'
   and plpd.product_id = plpc.product_id
   and plpd.sizedefinition_id = plpc.sizedefinition_id
   and plpd.finishingmethod_id = plpc.finishingmethod_id) totalincirc,
   pack_price.Rent_Price(plpc.customer_id,plpc.product_id,plpc.sizedefinition_id,plpc.finishingmethod_id,sysdate) rent_price
from
productlistpercustomer plpc, department d, distributionpoint dp,
productlistperdistribpoint plpd
where d.department_id = dp.department_id
and d.customer_id = plpc.customer_id
and plpd.distributionpoint_id = dp.distributionpoint_id

/
create or replace view V_INVOICEHEADER_HUE_2
 (INVOICEHEADER_ID, DEP_CODE, DEP_DESC, DEP_PHONE, DEP_FAXNO, DEP_STREET, DEP_STREET2, DEP_ZIPCODE, DEP_CITY, DEP_STATE, DEP_COUNTY)
as select a.invoiceheader_id, DEP.CODE DEP_CODE, DEP.DESCRIPTION DEP_DESC, DEP.PHONENO DEP_PHONE, DEP.FAXNO DEP_FAXNO,
       Y.STREET DEP_STREET, Y.STREET2 DEP_STREET2, Y.ZIPCODE DEP_ZIPCODE, Y.CITY DEP_CITY, Y.STATE DEP_STATE
       , Y.COUNTY DEP_COUNTY
from  invoiceheader a, route rr,
      --businessunit e,
      depot dep,
      address Y
where --a.invoicebusinessunit_id = e.businessunit_id
      a.route_id = rr.route_id
      --and e.plant_id = dep.plant_id
      --and dep.code = a.depotcode
      and dep.depot_id = rr.depot_id
      and DEP.ADDRESS_ID = Y.ADDRESS_ID

/
create or replace view V_INVOICELINE
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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 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.adjustmentpermited,
       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
         where pilt.plant_id =bu.plant_id
           and pilt.invoicelinetype_id = a.invoicelinetype_id) InvoiceLine_SequenceNumber,
case (SELECT pilt.suppressprinting
         from plantinvoicelinetype pilt
         where bu.plant_id = pilt.plant_id
               and pilt.invoicelinetype_id = a.invoicelinetype_id)
  when 0 then 0
  when 1 then 1
  when 2 then 2
  else e.supressprinting
end supressprinting, --502161
       b.adjustmentdeliveredqty,
       b.pricefactor
  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, businessunit bu,
 LANGUAGES
 where a.invoicelinetype_id = e.invoicelinetype_id
   and a.invoiceheader_id = f.invoiceheader_id
   and f.invoicebusinessunit_id = bu.businessunit_id
   and f.documenttype in (1, 8)

/
create or replace view V_INVOICELINE1_SMG
 (INVOICEHEADER_ID, INVOICELINE_ID, ITEM, CODE, QTY, PRICE, AMOUNT, DISCOUNTPERCENTAGE, PRODUCTGR_CODE, SIZECODE, FINISHINGMETHODCODE, FMPRICEFACTOR, YEAR, WEEK, QUANTITY, MAXILAWEEK, STARTWEEK, ENDWEEK, ENDWEEKDATE, STARTDATE, ENDDATE, WEEKSINYEAR, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, PRICEDECIMALS, INVOICEDECIMALS, CURRENCYCODE, DSFREQUENCY)
as select  h.invoiceheader_id,l.invoiceline_id,
       l.description item,l.code, l.billedqty qty,
       l.price, l.amount amount, l.discountpercentage,
       (select pg.code from product pr, productgroup pg where lp.product_link_id = pr.product_id and pr.productgroup_id=pg.productgroup_id)   productgr_code,
       ( select  sd.code from sizedefinition sd where sd.sizedefinition_id=lp.sizedefinition_link_id) sizecode,
       (select fm.code from finishingmethod fm where lp.finishingmethod_id = fm.finishingmethod_id) finishingmethodcode,
       coalesce((select fm.pricefactor from finishingmethod fm where lp.finishingmethod_id = fm.finishingmethod_id),1) fmpricefactor,
        cri.year,cri.week,
      coalesce((select sum(a.standardquantity) from costreportextrainfo a, invoiceline il
       where a.invoiceline_id=il.invoiceline_id and  il.invoiceheader_id=h.invoiceheader_id
       and il.invoiceline_id=l.invoiceline_id
       and a.year=cri.year and a.week=cri.week
       and il.invoicelinetype_id=1  group by h.invoiceheader_id ,a.invoiceline_id, cri.year,cri.week), 0)
          quantity,
        cast(( select to_char(max(ild.year*100+ild.week)) from costreportinfo ild, invoiceline il
          where ild.invoiceline_id=il.invoiceline_id
          and il.invoiceheader_id=h.invoiceheader_id
          and il.invoicelinetype_id = 1)as varchar2(6)) maxilaweek,
      h.startweek, h.endweek, to_number(getweeknumber(h.enddate)) endweekdate,h.startdate,h.enddate,
      (case  when h.startyear <> 0 then getweeksinyear(h.startyear)
          else getweeksinyear(to_number(getyearasvarchar(h.invoicedate))) end) weeksinyear,
      h.startmonth, h.endmonth, h.startyear, h.endyear,
      (select c.decimals from currency c where h.currency_id=c.currency_id) pricedecimals,
      (select c.invoiceamountdecimals from currency c where h.currency_id=c.currency_id) invoicedecimals,
      (select c.code from currency c where h.currency_id=c.currency_id) currencycode,
      (select ds.frequency from deliveryscheme ds where ds.code=lp.deliveryschemecode) dsfrequency
from   invoiceheader h,invoicelineproduct lp, invoiceline l, costreportextrainfo cri
where  h.invoiceheader_id = l.invoiceheader_id
       and lp.invoiceline_id = l.invoiceline_id
       and l.invoiceline_id=cri.invoiceline_id
and l.invoicelinetype_id=1 and l.invoicelinesubtype = 6  --  only rent underuse lines
group  by h.invoiceheader_id,h.invoicedate,l.invoiceline_id,l.code,l.billedqty ,l.amount, lp.product_link_id, lp.sizedefinition_link_id,
          lp.finishingmethod_id,lp.weighingcategory_link_id, h.billtocustomer_link_id, h.invoicebusinessunit_id,
          l.description, l.price,l.discountpercentage,cri.year, cri.week, h.startyear, h.endyear, h.startweek,
           h.endweek,h.startmonth, h.endmonth,h.enddate,h.startdate,h.startyear,h.currency_id,lp.deliveryschemecode
union
select  h.invoiceheader_id,l.invoiceline_id,
       l.description item,l.code, l.billedqty qty,
       l.price, l.amount amount, l.discountpercentage,
       (select pg.code from product pr, productgroup pg where lp.product_link_id = pr.product_id and pr.productgroup_id=pg.productgroup_id)   productgr_code,
       ( select  sd.code from sizedefinition sd where sd.sizedefinition_id=lp.sizedefinition_link_id) sizecode,
       (select fm.code from finishingmethod fm where lp.finishingmethod_id = fm.finishingmethod_id) finishingmethodcode,
       coalesce((select fm.pricefactor from finishingmethod fm where lp.finishingmethod_id = fm.finishingmethod_id),1) fmpricefactor,
       cri.year,cri.week,
      coalesce(( select sum(a.quantity) from costreportinfo a, invoiceline il
       where a.invoiceline_id=il.invoiceline_id and  il.invoiceheader_id=h.invoiceheader_id
       and il.invoiceline_id=l.invoiceline_id
       and a.year=cri.year and a.week=cri.week
       and il.invoicelinetype_id=1  group by h.invoiceheader_id ,a.invoiceline_id, a.year,a.week), 0)
          quantity,
        cast(( select to_char(max(ild.year*100+ild.week)) from costreportinfo ild, invoiceline il
          where ild.invoiceline_id=il.invoiceline_id
          and il.invoiceheader_id=h.invoiceheader_id
          and il.invoicelinetype_id = 1)as varchar2(6)) maxilaweek,
      h.startweek, h.endweek, to_number(getweeknumber(h.enddate)) endweekdate,h.startdate,h.enddate,
      (case  when h.startyear <> 0 then getweeksinyear(h.startyear)
          else getweeksinyear(to_number(getyearasvarchar(h.invoicedate))) end) weeksinyear,
      h.startmonth, h.endmonth, h.startyear, h.endyear,
      (select c.decimals from currency c where h.currency_id=c.currency_id) pricedecimals,
      (select c.invoiceamountdecimals from currency c where h.currency_id=c.currency_id) invoicedecimals,
      (select c.code from currency c where h.currency_id=c.currency_id) currencycode,
      ( select ds.frequency from deliveryscheme ds where ds.code=lp.deliveryschemecode) dsfrequency
from   invoiceheader h,invoicelineproduct lp, invoiceline l, costreportinfo cri
where  h.invoiceheader_id = l.invoiceheader_id
       and lp.invoiceline_id = l.invoiceline_id
       and l.invoiceline_id=cri.invoiceline_id
and l.invoicelinetype_id=1 and l.invoicelinesubtype <> 6  --  all rent excepts underuse
group  by h.invoiceheader_id,h.invoicedate,l.invoiceline_id,l.code,l.billedqty,l.amount, lp.product_link_id, lp.sizedefinition_link_id,
          lp.finishingmethod_id,lp.weighingcategory_link_id, h.billtocustomer_link_id, h.invoicebusinessunit_id,
          l.description, l.price,l.discountpercentage,cri.year, cri.week, h.startyear, h.endyear, h.startweek,
           h.endweek,h.startmonth, h.endmonth,h.enddate,h.startdate,h.startyear,h.currency_id,lp.deliveryschemecode
union
select  h.invoiceheader_id,l.invoiceline_id,
       l.description item,l.code, l.billedqty qty,
       l.price, l.amount amount, l.discountpercentage,
         (case
         when lp.product_link_id is not null then
            (select pg.code from product pr, productgroup pg where lp.product_link_id = pr.product_id and pr.productgroup_id=pg.productgroup_id)
       else
         coalesce((select pg.code from weighingcategory wg, productgroup pg where wg.weighingcategory_id=lp.weighingcategory_link_id
         and wg.legacyweighingcategorycode=pg.code),
         (select wg.code from weighingcategory wg where wg.weighingcategory_id=lp.weighingcategory_link_id),'ZZZ'||l.code)
       end) productgr_code,
       ( select  sd.code from sizedefinition sd where sd.sizedefinition_id=lp.sizedefinition_link_id) sizecode,
       (select fm.code from finishingmethod fm where lp.finishingmethod_id = fm.finishingmethod_id) finishingmethodcode,
      coalesce((select fm.pricefactor from finishingmethod fm where lp.finishingmethod_id = fm.finishingmethod_id),1) fmpricefactor,
       null year,null week
       ,0 quantity,
        cast(( select to_char(max(ild.year*100+ild.week)) from costreportinfo ild, invoiceline il
          where ild.invoiceline_id=il.invoiceline_id
          and il.invoiceheader_id=h.invoiceheader_id
          and il.invoicelinetype_id = 1)as varchar2(6)) maxilaweek,
      h.startweek, h.endweek, to_number(getweeknumber(h.enddate)) endweekdate,h.startdate,h.enddate,
      (case  when h.startyear <> 0 then getweeksinyear(h.startyear)
          else getweeksinyear(to_number(getyearasvarchar(h.invoicedate))) end) weeksinyear,
      h.startmonth, h.endmonth, h.startyear, h.endyear,
      (select c.decimals from currency c where h.currency_id=c.currency_id) pricedecimals,
      (select c.invoiceamountdecimals from currency c where h.currency_id=c.currency_id) invoicedecimals,
      (select c.code from currency c where h.currency_id=c.currency_id) currencycode,
      null dsfrequency
from   invoiceheader h,invoicelineproduct lp, invoiceline l
where  h.invoiceheader_id = l.invoiceheader_id
       and lp.invoiceline_id = l.invoiceline_id
       and l.invoicelinetype_id <> 1  --  all lines excepts rent
       and l.invoicelinetype_id <> 6
group  by h.invoiceheader_id,h.invoicedate,l.invoiceline_id,l.code,l.billedqty,l.amount , lp.product_link_id, lp.sizedefinition_link_id,
          lp.finishingmethod_id,lp.weighingcategory_link_id, h.billtocustomer_link_id, h.invoicebusinessunit_id,
          l.description, l.price,l.discountpercentage, h.startyear, h.endyear, h.startweek,
           h.endweek,h.startmonth, h.endmonth,h.enddate,h.startdate,h.startyear,h.currency_id
union
select  h.invoiceheader_id,l.invoiceline_id,
       l.description item,l.code, l.billedqty qty,
       l.price, l.amount amount, l.discountpercentage,
         (case
         when lp.product_link_id is not null then
            (select pg.code from product pr, productgroup pg where lp.product_link_id = pr.product_id and pr.productgroup_id=pg.productgroup_id)
       else
         coalesce((select pg.code from weighingcategory wg, productgroup pg where wg.weighingcategory_id=lp.weighingcategory_link_id
         and wg.legacyweighingcategorycode=pg.code),
         (select wg.code from weighingcategory wg where wg.weighingcategory_id=lp.weighingcategory_link_id),'ZZZ'||l.code)
       end) productgr_code,
       ( select  sd.code from sizedefinition sd where sd.sizedefinition_id=lp.sizedefinition_link_id) sizecode,
       (select fm.code from finishingmethod fm where lp.finishingmethod_id = fm.finishingmethod_id) finishingmethodcode,
      coalesce((select fm.pricefactor from finishingmethod fm where lp.finishingmethod_id = fm.finishingmethod_id),1) fmpricefactor,
       null year,null week
       ,0 quantity,
        cast(( select to_char(max(ild.year*100+ild.week)) from costreportinfo ild, invoiceline il
          where ild.invoiceline_id=il.invoiceline_id
          and il.invoiceheader_id=h.invoiceheader_id
          and il.invoicelinetype_id = 1)as varchar2(6)) maxilaweek,
      h.startweek, h.endweek, to_number(getweeknumber(h.enddate)) endweekdate,h.startdate,h.enddate,
      (case  when h.startyear <> 0 then getweeksinyear(h.startyear)
          else getweeksinyear(to_number(getyearasvarchar(h.invoicedate))) end) weeksinyear,
      h.startmonth, h.endmonth, h.startyear, h.endyear,
      (select c.decimals from currency c where h.currency_id=c.currency_id) pricedecimals,
      (select c.invoiceamountdecimals from currency c where h.currency_id=c.currency_id) invoicedecimals,
      (select c.code from currency c where h.currency_id=c.currency_id) currencycode,
      null dsfrequency
from   invoiceheader h, invoiceline l left outer join invoicelineproduct lp on lp.invoiceline_id = l.invoiceline_id
where  h.invoiceheader_id = l.invoiceheader_id
       and l.invoicelinetype_id = 6
group  by h.invoiceheader_id,h.invoicedate,l.invoiceline_id,l.code,l.billedqty,l.amount , lp.product_link_id, lp.sizedefinition_link_id,
          lp.finishingmethod_id,lp.weighingcategory_link_id, h.billtocustomer_link_id, h.invoicebusinessunit_id,
          l.description, l.price,l.discountpercentage, h.startyear, h.endyear, h.startweek,
           h.endweek,h.startmonth, h.endmonth,h.enddate,h.startdate,h.startyear,h.currency_id

/
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_INVOICETAX_LTS
 (INVOICEDATE, INVOICENUMBER, PARENTINVOICEHEADER_ID, PREBILLAMOUNT, TOTALAMOUNTEXCLVAT, BILLTOCUSTOMERNUMBER, DELTOCUSTOMERNUMBER, INVOICELINETYPE, AMOUNT, PRICE, BILLEDQTY, TAXGROUPCODE, TAXTYPE, PERCENTAGE, TAXABLE, INVOICELINE_ID, INVOICEHEADER_ID, OVERAMOUNT, TAXRATE)
as select f.invoicedate,
       f.invoicenumber,
       f.parentinvoiceheader_id,
       f.prebillamount,
       f.totalamountexclvat,
       f.billtocustomernumber,
       f.deltocustomernumber,
       e.type invoicelinetype,
       case
         when f.invoiceheader_id = f.parentinvoiceheader_id then a.amount
         when a.invoicelinetype_id = 18 then c.overamount
         else a.amount end amount,
       a.price,
       a.billedqty,
       a.taxgroupcode,
       a.taxtype,
       case
         when ihextr.taxable = 'N' then 0
         else c.percentage
       end percentage,
       ihextr.taxable,
       a.invoiceline_id,
       a.invoiceheader_id,
       c.overamount,
       coalesce((select case when f.enddate < tg.startdatetaxrate then tg.oldtaxrate
                        else tg.taxrate
                        end taxrate
                 from taxgroup tg, customer bill
                 where a.taxgroupcode = tg.code
                       and bill.customer_id = f.billtocustomer_link_id
                       and tg.country_id = bill.country_id)
               , case when ihextr.taxable = 'N' then 0
                 else c.percentage
                 end) taxrate
from invoiceline a
LEFT OUTER JOIN invoicelinevarious c ON (a.invoiceline_id = c.invoiceline_id),
invoicelinetype e, invoiceheader f, invoiceheaderextrainfo ihextr
where a.invoicelinetype_id = e.invoicelinetype_id
and a.invoiceheader_id = f.invoiceheader_id
and f.invoiceheader_id = ihextr.invoiceheader_id
and f.documenttype in (1, 3)
and ((exists(select il.invoiceline_id from invoiceline il where il.invoiceheader_id = a.invoiceheader_id and il.invoicelinetype_id=18)
      and a.invoicelinetype_id=18)
    or not(exists(select il.invoiceline_id from invoiceline il where il.invoiceheader_id = a.invoiceheader_id and il.invoicelinetype_id=18)))

/
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 distinct plpc.customer_id,  plpc.dateinactive,
  ac.code activitycode,
  pr.code productcode,
  co.code competitorcode,
  rp.reportparam_id
from productlistpercustomer plpc
    left outer join competitor co on plpc.lostcompetitor_id = co.competitor_id
    left outer join gainlostreason gl on plpc.lostreason_id = gl.gainlostreason_id,
  product pr, productgroup pg, customeractivities ca, businessunitsperusergroup bug, activity ac,
  reportparam rp
where pr.productgroup_id = pg.productgroup_id
  and plpc.product_id = pr.product_id
  and pg.activity_id = ca.activity_id
  and ca.customer_id = plpc.customer_id
  and ca.invoicebusinessunit_id = bug.businessunit_id
  and ca.activity_id = ac.activity_id
  and plpc.dateinactive >= rp.date_value1
  and plpc.dateinactive <= rp.date_value2
  and bug.usergroup_id = rp.number_value1
  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'
group by s.customer_id

/
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_NOTRECEIVEDCUSTOMERORDERS_C
 (CUSTOMER_ID, REPORTPARAM_ID, EXISTSDV)
as select cu.customer_id,  rp.reportparam_id,
/*sum(coalesce((select count(*)
    from deliveryvariations dv
        left outer join packingnote pn on pn.packingnote_id = dv.packingnote_id
    where dv.distributionpoint_id = plpd.distributionpoint_id
      and dv.product_id = plpd.product_id
      and dv.sizedefinition_id = plpd.sizedefinition_id
      and dv.finishingmethod_id = plpd.finishingmethod_id
      and ((dv.packingnote_id is not null and pn.deliverydate >= rp.date_value1)
        or (dv.packingnote_id is null and dv.deliverydate >= rp.date_value1))
      and ((rp.number_value1 = 1 and dv.origin in (3,6)) -- manual, web
        or (rp.number_value1 = 0))),0)) existsdv */
  sum(F_EXISTSDELIVERY(plpd.productlistperdistribpoint_id, rp.number_value1, rp.date_value1)) existsdv
from productlistperdistribpoint plpd,
  Department de, DistributionPoint dip, customer cu,
  product pr, productgroup pg,
  reportparam rp
where plpd.distributionpoint_id = dip.distributionpoint_id
  and dip.department_id = de.department_id
  and de.customer_id = cu.customer_id
  and plpd.product_id = pr.product_id
  and pr.typeofmerchandise <= 3
  and pr.productgroup_id = pg.productgroup_id
  and plpd.orderingmethod = 2
  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.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 ((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, ISFORDELIVERY, REPORTPARAM_ID)
as select distinct cu.customer_id, cu.customernumber, cu.name customername,
  de.contactperson_id, de.departmentnumber, de.description departmentdesc,
  dip.distributionpoint_id, dip.distributionpointnumber, dip.description distributionpointdesc,
  F_CHECKFORDELIVERY(plpd.productlistperdistribpoint_id, cu.customer_id, de.department_id, rp.date_value1) isfordelivery,
  rp.reportparam_id
from productlistperdistribpoint plpd, --normstockamount nsa,
  Department de, DistributionPoint dip, customer cu,
  product pr, productgroup pg,
  reportparam rp
where plpd.distributionpoint_id = dip.distributionpoint_id
  and dip.department_id = de.department_id
  and de.customer_id = cu.customer_id
  and plpd.product_id = pr.product_id
  and pr.typeofmerchandise <= 3
  and pr.productgroup_id = pg.productgroup_id
  and plpd.orderingmethod = 2
  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.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 ((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))
--  and exists (select nsa.productlistperdistribpoint_id from normstockamount nsa
--    where nsa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
--    and nsa.day_id = GETABSDAYNUMBER(rp.date_value1))
--  and nsa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
--  and nsa.day_id = GETABSDAYNUMBER(rp.date_value1)

/
create or replace view V_NOTSCANNEDITEMS_AUX
 (UNIQUEITEM_ID, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDEFINITIONCODE, SIZEDEFINITIONDESCRIPTION, PRIMARYID, LASTSCANDATE, ISSUEDATE, STATUSCODE, STATUSDESCRIPTION, STAYNUMBER, STAYDESCRIPTION, LANGUAGELANGUAGEID, LANGUAGECODE)
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 /*
, finmeth.code finishingmethodCode
, (select finishingmethod_desc.description from finishingmethod_desc
where finishingmethod_desc.finishingmethod_id = finmeth.finishingmethod_id
and finishingmethod_desc.language_id = languages.language_id) finishingmethodDescription  */
, 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--, flag.code flagCode
, languages.language_id languageLanguageID , languages.code languageCode
from
  uniqueitem uq /*
    left outer join finishingmethod finmeth on uq.FINISHINGMETHOD_ID = finmeth.finishingmethod_id
    left outer join (uniqueitemflag uqf join flag on uqf.flag_id = flag.flag_id    )
                    on uq.uniqueitem_id = uqf.uniqueitem_id   */
, product prd, uniqueitemfixedinfo uqfix, sizedefinition sizedef, status, stay, languages
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

/
create or replace view V_NOTSCANNEDITEMS_AUX_CBD
 (UNIQUEITEM_ID, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDEFINITIONCODE, SIZEDEFINITIONDESCRIPTION, PRIMARYID, LASTSCANDATE, ISSUEDATE, STATUSCODE, STATUSDESCRIPTION, STAYNUMBER, STAYDESCRIPTION, LANGUAGELANGUAGEID, LANGUAGECODE, SECONDARYID)
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 /*
, finmeth.code finishingmethodCode
, (select finishingmethod_desc.description from finishingmethod_desc
where finishingmethod_desc.finishingmethod_id = finmeth.finishingmethod_id
and finishingmethod_desc.language_id = languages.language_id) finishingmethodDescription  */
, 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--, flag.code flagCode
, languages.language_id languageLanguageID , languages.code languageCode, Suq.Secondaryid
from
  uniqueitem uq
    left outer join Secondaryuniqueitem suq on Uq.Uniqueitem_Id = Suq.Uniqueitem_Id
  /*
    left outer join finishingmethod finmeth on uq.FINISHINGMETHOD_ID = finmeth.finishingmethod_id
    left outer join (uniqueitemflag uqf join flag on uqf.flag_id = flag.flag_id    )
                    on uq.uniqueitem_id = uqf.uniqueitem_id   */
, product prd, uniqueitemfixedinfo uqfix, sizedefinition sizedef, status, stay, languages
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

/
create or replace view V_NOTSCANNEDITEMS_LINE
 (UNIQUEITEM_ID, BUSINESSUNIT_ID, CUSTOMERNUMBER, CUSTOMERNAME, WEARERNUMBER, WEARERNAME, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, CUSTOMERLANGUAGEID, LOCKER, BANK, ROUTEFILTER, REPORTPARAM_ID, RESIDUALVALUE, CHAIN_CODE)
as select 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
      --      and we.customer_id = cu.customer_id
UNION ALL
select 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
--, lo.locker, lo.bank
, '' locker, '' bank
, F_ROUTEFILTER(cu.customer_id, -1, 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
  --left outer join locker lo on cu.customer_id = lo.customer_id
  , distributionpoint, department --, wearer we
  , 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 uq.uniqueitem_id = rp.number_value
            /*and cu.customer_id = we.customer_id*/
UNION ALL
select 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
--, lo.locker, lo.bank
, '' 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
 -- left outer join locker lo on cu.customer_id = lo.customer_id
  /*, wearer we , distributionpoint, department*/
  , reportparam rp
where
    uq.poolitem = 1
and uq.distributionpoint_id is null
AND uq.relatedcustomer_id = cu.customer_id and uq.uniqueitem_id = rp.number_value
    /*and cu.customer_id = department.customer_id
        and department.department_id = distributionpoint.department_id
            and cu.customer_id = we.customer_id*/
UNION ALL
select 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 uq.uniqueitem_id = rp.number_value

/
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_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_ORDERFORM_AUX_ANG
 (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, ROUTENUMBER, DELIVERYDATE
)
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 /*+index(dh XSPEEDDELIVERYHISTORY)*/ sum(dh.amountdelivered) from deliveryhistory dh
    where dh.deliverydate between RP.DATE_VALUE1-24*7 and RP.DATE_VALUE1
     and d.distributionpoint_id = dh.distributionpoint_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) amount,
(select count(1)
    from ( select cntd.distributionpoint_link_id, cntd.deliverydate
           from deliveryhistory cntd
           group by cntd.distributionpoint_link_id, cntd.deliverydate ) x
    where x.deliverydate between RP.DATE_VALUE1-24*7 and RP.DATE_VALUE1
     and x.distributionpoint_link_id = d.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
  , r.routenumber, RP.DATE_VALUE1 DeliveryDate
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_ORDERFORM_AUX_LLG
 (REPORTPARAM_ID, COPY_NUMBER, CUSTOMERNUMBER, SEARCHNAME, CUSTOMERNAME, STREET, STREET2, ADDRESS, ZIPCODE, CITY, DEPARTMENTNUMBER, DEPARTMENTNAME, DEPACTIVE, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTNUMBERNAME, DISTRIBACTIVE, SIZEDEFINITIONCODE, SIZEDEFINITIONDESC, FINISHINGMETHODCODE, FINISHINGMETHODDESC, PRODUCTCODE, PRODUCTDESC, CUSTOMCODE, CUSTOMDESCRIPTION, CUSTOMER_ID, ORDERINGMETHOD, SEQUENCENUMBER, PACKINGSEQUENCE, DELIVERYPOINT_ID, BUCODE, BUNAME, SOILCOUNTMETHOD)
as SELECT distinct RP.REPORTPARAM_ID, rp.copy_number, A.CUSTOMERNUMBER
, A.SEARCHNAME, 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, 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
  , (select bu.code from businessunit bu where bu.businessunit_id = a.defaultbusinessunit_id) bucode
  , (select bu.description from businessunit bu where bu.businessunit_id = a.defaultbusinessunit_id) buname
  , e.soilcountmethod
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.SEARCHNAME, 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, 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
  , (select bu.code from businessunit bu where bu.businessunit_id = a.defaultbusinessunit_id) bucode
  ,(select bu.description from businessunit bu where bu.businessunit_id = a.defaultbusinessunit_id) buname
  , e.soilcountmethod
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_ORDERFORM_AUX_SHL
 (REPORTPARAM_ID, COPY_NUMBER, CUSTOMERNUMBER, CUSTOMERNAME, ADDRESS, ZIPCODE, CITY, STATE, DEPARTMENTNUMBER, DEPARTMENTNAME, DEPACTIVE, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTNUMBERNAME, DISTRIBACTIVE, SIZEDEFINITIONCODE, SIZEDEFINITIONDESC, FINISHINGMETHODCODE, FINISHINGMETHODDESC, PRODUCTCODE, PRODUCTDESC, CUSTOMCODE, CUSTOMDESCRIPTION, CUSTOMER_ID, AMOUNT, ORDERINGMETHOD)
as SELECT distinct RP.REPORTPARAM_ID, rp.copy_number, A.CUSTOMERNUMBER, A.LEGALNAME CUSTOMERNAME
, cast(CONCATENATEWITHBLANK(F.STREET, F.STREET2) as varchar2(255)) ADDRESS, F.ZIPCODE, F.CITY, F.State,
  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 */
,(select sum(k.amount) from StandardDeliveryAmount K
    where k.standarddeliveryline_id = J.Standarddeliveryline_Id AND k.day_id = GETABSDAYNUMBER(RP.DATE_VALUE1)) amount
, d.orderingmethod
FROM CUSTOMER A, DEPARTMENT B, DISTRIBUTIONPOINT C, DELIVERYPOINT DP,
  PRODUCTLISTPERDISTRIBPOINT D, PRODUCTLISTPERCUSTOMER E, ADDRESS F, PRODUCT G,
  SIZEDEFINITION H, FINISHINGMETHOD I, REPORTPARAM RP, STANDARDDELIVERYLINE J
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 (b.Active='Y' or c.Active='Y')
--  and rp.reportparam_id=40155
union all
SELECT distinct RP.REPORTPARAM_ID, rp.copy_number, A.CUSTOMERNUMBER, A.LEGALNAME CUSTOMERNAME
, cast(CONCATENATEWITHBLANK(F.STREET, F.STREET2) as varchar2(255)) ADDRESS
, F.ZIPCODE, F.CITY, f.state,
  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
FROM CUSTOMER A, 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

/
create or replace view V_ORDERFORM_AUX_SMG
 (REPORTPARAM_ID, COPY_NUMBER, CPL, CUSTOMERNUMBER, CUSTNR, CUSTOMERNAME, STREET, STREET2, ZIPCODE, CITY, DEPARTMENTNUMBER, DEPARTMENTNAME, DEPACTIVE, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTNUMBERNAME, DISTRIBACTIVE, PRODUCTCODE, PRODUCTDESC, CUSTOMCODE, CUSTOMDESCRIPTION, CUSTOMER_ID, ORDERINGMETHOD, PACKINGSEQUENCE, ROUTENRDESC, DELIVERYPOINT_ID, INTERNALPROCBU)
as SELECT   RP.REPORTPARAM_ID, rp.copy_number, 0 CPL,
A.CUSTOMERNUMBER
,insertspace_after_x_characters(to_char(A.CUSTOMERNUMBER),3) custnr
, A.NAME CUSTOMERNAME,F.STREET, F.STREET2,
 F.ZIPCODE, F.CITY,
  B.DEPARTMENTNUMBER, B.DESCRIPTION DEPARTMENTNAME, b.active DepActive,
  C.DISTRIBUTIONPOINTNUMBER, C.DESCRIPTION DISTRIBUTIONPOINTNUMBERNAME, c.active DistribActive,
    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,   d.orderingmethod , g.packingsequence
, (select (castnumberasvarchar(r.routenumber) || ' ' || r.description) from routestop rs, route r
          where r.route_id = rs.route_id and rs.routestop_id = rp.number_value1) RouteNRDesc,
          DP.deliverypoint_id
,(Select min(bu.code)  from customeractivities ca, activity act, businessunit bu where ca.customer_id=a.customer_id
         and ca.activity_id=act.activity_id and act.code='BK' and ca.internalprocessingbu_id=bu.businessunit_id) internalprocbu
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,
   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 E.CUSTOMER_ID = A.CUSTOMER_ID
  and e.soilcountmethod<>0
  and e.straightevenexchange='N'
  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)
  and (b.active='Y' or c.active='Y')
  union all
SELECT  RP.REPORTPARAM_ID, rp.copy_number, 0  CPL, A.CUSTOMERNUMBER
,insertspace_after_x_characters(to_char(A.CUSTOMERNUMBER),3) custnr
, A.NAME CUSTOMERNAME,F.STREET, F.STREET2
, F.ZIPCODE, F.CITY,
  B.DEPARTMENTNUMBER, B.DESCRIPTION DEPARTMENTNAME,  b.active DepActive,
  C.DISTRIBUTIONPOINTNUMBER, C.DESCRIPTION DISTRIBUTIONPOINTNUMBERNAME, c.active DistribActive,
    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,  d.orderingmethod  , g.packingsequence
, (select (castnumberasvarchar(r.routenumber) || ' ' || r.description) from routestop rs, route r
          where r.route_id = rs.route_id and rs.routestop_id = rp.number_value1) RouteNRDesc,
          DP.deliverypoint_id
,(Select min(bu.code)  from customeractivities ca, activity act, businessunit bu where ca.customer_id=a.customer_id
  and ca.activity_id=act.activity_id and act.code='BK' and ca.internalprocessingbu_id=bu.businessunit_id) internalprocbu
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,
  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 E.CUSTOMER_ID = A.CUSTOMER_ID
  and e.soilcountmethod<>0
  and e.straightevenexchange='N'
  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)
 and (b.active='Y' or c.active='Y')
  union all
SELECT  RP.REPORTPARAM_ID, rp.copy_number,1 CPL, A.CUSTOMERNUMBER,insertspace_after_x_characters(to_char(A.CUSTOMERNUMBER),3) custnr, A.NAME CUSTOMERNAME,
F.STREET, F.STREET2
, F.ZIPCODE, F.CITY,
  B.DEPARTMENTNUMBER, B.DESCRIPTION DEPARTMENTNAME,  b.active DepActive,
  C.DISTRIBUTIONPOINTNUMBER, C.DESCRIPTION DISTRIBUTIONPOINTNUMBERNAME, c.active DistribActive,
  G.CODE PRODUCTCODE,  (SELECT Z.DESCRIPTION FROM PRODUCT_DESC Z WHERE Z.PRODUCT_ID = g.PRODUCT_ID
    AND A.LANGUAGE_ID = Z.LANGUAGE_ID) PRODUCTDESC,
  E.CUSTOMCODE, E.CUSTOMDESCRIPTION,   A.CUSTOMER_ID,
   2 orderingmethod  , g.packingsequence
, (select (castnumberasvarchar(r.routenumber) || ' ' || r.description) from routestop rs, route r
          where r.route_id = rs.route_id and rs.routestop_id = rp.number_value1) RouteNRDesc,
          DP.deliverypoint_id
,(Select min(bu.code)  from customeractivities ca, activity act, businessunit bu where ca.customer_id=a.customer_id
and ca.activity_id=act.activity_id and act.code='BK' and ca.internalprocessingbu_id=bu.businessunit_id) internalprocbu
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,
   PRODUCTLISTPERCUSTOMER E, ADDRESS F, PRODUCT G,   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 E.CUSTOMER_ID = A.CUSTOMER_ID
  AND e.product_id=g.product_id
  AND RP.NUMBER_VALUE = A.CUSTOMER_ID
  and g.typeofmerchandise=2
  and (exists(select wi.wearerinventory_id from wearer w,weareremployment we, wearerinventory wi
               where w.wearer_id=we.wearer_id and  we.weareremployment_id= wi.weareremployment_id
                     and we.distributionpoint_id=c.distributionpoint_id
                     and w.customer_id=a.customer_id  and wi.product_id=G.Product_id
                     and wi.dateactive<=RP.DATE_VALUE1 and wi.dateinactive>=RP.DATE_VALUE1))
  AND E.DATEINACTIVE > RP.DATE_VALUE1
  and g.product_id not in(select distinct plpd.product_id
      from productlistperdistribpoint plpd
      where plpd.distributionpoint_id=c.distributionpoint_id
      and plpd.product_id=g.product_id)
  and ( RP.NUMBER_VALUE2=0 or RP.NUMBER_VALUE2=r.route_id)
and (rp.number_value4=0 or rp.number_value4=dp.deliverypoint_id)
and (b.active='Y' or c.active='Y')

/
create or replace view V_ORDERFORM_AUX_VOS
 (REPORTPARAM_ID, COPY_NUMBER, CUSTOMERNUMBER, CUSTOMERNAME, ADDRESS, ZIPCODE, CITY, DEPARTMENTNUMBER, DEPARTMENTNAME, DEPACTIVE, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTNUMBERNAME, DISTRIBACTIVE, SIZEDEFINITIONCODE, SIZEDEFINITIONDESC, FINISHINGMETHODCODE, FINISHINGMETHODDESC, PRODUCTCODE, PRODUCTDESC, CUSTOMCODE, CUSTOMDESCRIPTION, CUSTOMER_ID, AMOUNT, DELIVERIES, ORDERINGMETHOD, SEQUENCENUMBER, PACKINGSEQUENCE)
as select distinct
       rp.reportparam_id
,      rp.copy_number
,      a.customernumber
,      a.name customername
,      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 = a.customer_id
            and dh.department_link_id = b.department_id
            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(distinct cntd.deliverydate)
         from deliveryhistory 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
from   customer a
,      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

/
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_PACKINGNOTELINE_ECL
 (PACKINGNOTEID, PRODUCTGROUPCODE, PRODUCTCODE, PRODUCTDESCRIPTION, ACTIVITYCODE, ACTIVITYDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, FINISHINGMETHODCODE, PACKINGSEQUENCE, PACKINGAMOUNT, THEORETICALWEIGHT, STANDARDAMOUNT, VARIATIONAMOUNT, DELIVEREDAMOUNT, TOBEDELIVEREDAMOUNT, NODELIVERYAMOUNT, PRICE, DISCOUNT, LOCATION, REMARKFORPACKINGINSTRUCTIONS, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE, BULKPUTUP
, PUTUPTYPE, PACKINGNOTELINE_ID, PACKINGAMOUNTPSZ, BUNDLEQTY, PRODUCT_ID, ISPACK, PRICECOG, SEQUENCENUMBER, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, PACKINGGROUP, REPLACEMENTQTY, REPLACEMENTLOSSQTY)
as SELECT PACKINGNOTELINE.PACKINGNOTE_ID PACKINGNOTEID,--PACKINGNOTE.PACKINGNOTE_ID,
  PRODUCTGROUP.CODE PRODUCTGROUPCODE, --PACKINGNOTE.NOTENUMBER,
  PRODUCT.CODE PRODUCTCODE,
  (SELECT DESCRIPTION FROM PRODUCT_DESC P WHERE P.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
     AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  PRODUCTDESCRIPTION, -- PRODUCTDESCRIPTION
  ACTIVITY.CODE ACTIVITYCODE,
  (SELECT DESCRIPTION FROM ACTIVITY_DESC AD WHERE AD.ACTIVITY_ID = ACTIVITY.ACTIVITY_ID
     AND AD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  ACTIVITYDESCRIPTION,
  PACKINGNOTELINE.CUSTOMCODE PRODUCTCUSTOMCODE,
  PACKINGNOTELINE.CUSTOMDESCRIPTION PRODUCTCUSTOMDESCRIPTION, -- PRODUCTCUSTOMDESCRIPTION
  SIZEDEFINITION.CODE SIZECODE,
  (SELECT DESCRIPTION FROM SIZEDEFINITION_DESC S WHERE S.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID
     AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  SIZEDESCRIPTION,
  (SELECT DESCRIPTION FROM FINISHINGMETHOD_DESC F WHERE F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
     AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  FINISHINGMETHODDESCRIPTION,
  FINISHINGMETHOD.CODE FINISHINGMETHODCODE,
  PACKINGNOTELINE.PACKINGSEQUENCE, PRODUCT.PACKINGAMOUNT,
  CASE
   WHEN PSZ.THEORETICALWEIGHT = 0 THEN PRODUCT.THEORETICALWEIGHT*PACKINGNOTELINE.Deliveredamount
   ELSE PSZ.THEORETICALWEIGHT*PACKINGNOTELINE.Deliveredamount
   END  THEORETICALWEIGHT,--  PRODUCT.THEORETICALWEIGHT
  PACKINGNOTELINE.STANDARDAMOUNT, PACKINGNOTELINE.VARIATIONAMOUNT,
  PACKINGNOTELINE.DELIVEREDAMOUNT, PACKINGNOTELINE.TOBEDELIVEREDAMOUNT,
  PACKINGNOTELINE.NODELIVERYAMOUNT NODELIVERYAMOUNT,
  (CASE WHEN PACKINGNOTELINE.PRICE IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICE END) PRICE, PACKINGNOTELINE.DISCOUNT, PACKINGNOTELINE.LOCATION,
  PACKINGNOTELINE.REMARKFORPACKINGINSTRUCTIONS, PACKINGNOTELINE.SYSTEMUSER_ID, PACKINGNOTELINE.TIMESTAMP,
  LANGUAGES.CODE LANGUAGECODE,
  CASE WHEN PACKINGNOTELINE.PUTUPTYPE = 2 THEN 'Y' ELSE 'N' END BULKPUTUP, PACKINGNOTELINE.PUTUPTYPE,
  PACKINGNOTELINE.PACKINGNOTELINE_ID, PSZ.PACKINGAMOUNT PACKINGAMOUNTPSZ,
  PACKINGNOTELINE.BUNDLEQTY,
  PRODUCT.PRODUCT_ID, PRODUCT.PACK ISPACK,
  (CASE WHEN PACKINGNOTELINE.PRICECOG IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICECOG END) PRICECOG
  , PSZ.SEQUENCENUMBER, PACKINGNOTELINE.NOCHARGEPREVSHORTAGE, PACKINGNOTELINE.NOCHARGEPREVREJECTED
  , PRODUCT.PACKINGGROUP
  , PACKINGNOTELINE.REPLACEMENTQTY
  , PACKINGNOTELINE.REPLACEMENTLOSSQTY
FROM PACKINGNOTELINE , FINISHINGMETHOD ,      --PACKINGNOTE,
      PRODUCT,PRODUCTGROUP, ACTIVITY,
      SIZEDEFINITION, LANGUAGES
      , PRODUCTSIZE PSZ
WHERE PACKINGNOTELINE.PRODUCT_ID = PRODUCT.PRODUCT_ID
  AND PACKINGNOTELINE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
  AND PRODUCTGROUP.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID
  AND FINISHINGMETHOD.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
      AND PRODUCT.PRODUCT_ID = PSZ.PRODUCT_ID
          AND PSZ.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
  AND PRODUCTGROUP.ACTIVITY_ID = ACTIVITY.ACTIVITY_ID

/
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_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_PRODID_FINMETHODCODE_SMG
 (PRODUCT_ID, PRODUCTCODE, FINMETHODCODE)
as select p.product_id
,      p.code productcode
,      case when ( select count(*)
                   from   productfinishingmethod pf1
                   where  pf1.product_id = p.product_id
                      and exists ( select 1
                                   from   productfinishingmethod pf2
                                   where  pf1.product_id = pf2.product_id ) ) <> 1
            then ' '
            else ( select fm.code
			       from   finishingmethod fm
				   where  fm.finishingmethod_id =
				     ( select pf.finishingmethod_id
                       from   productfinishingmethod pf
                       where  pf.product_id = p.product_id ) )
        end finmethodcode -- 20015217
from product p

/
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_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 >= getcurrentdate()-14 and ih1.invoicedate <= getcurrentdate()
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 >= getcurrentdate()-7 and ih1.invoicedate <= getcurrentdate()
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 <= getcurrentdate()
  ) MaxInvoicedate
, (select max(ih3.invoicedate) from invoiceheader ih3
  where ih1.deltocustomer_link_id = ih3.deltocustomer_link_id and ih3.prebillamount <> 0 and ih3.invoicedate <= getcurrentdate()
      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 <= getcurrentdate())
  ) SecondInvoicedate
from invoiceheader ih1
where ih1.prebillamount <> 0 and ih1.invoicedate <= getcurrentdate()

/
create or replace view V_ROUTELIST_REF_LLG
 (REFERENCE, ORIGIN, AMOUNT, PACKINGNOTE_ID, PRODUCT_ID, SIZEDEFINITION_ID, FINISHINGMETHOD_ID, LANGUAGECODE, REASONCODE, REASONCODEDESC)
as select dv.reference,
       dv.origin,
       dv.amount,
       pnl.packingnote_id,
       pnl.product_id,
       pnl.sizedefinition_id,
       pnl.finishingmethod_id,
       l.code languagecode,
       (select rc.code
          from reasoncode rc
          where rc.reasoncode_id = dv.reasoncode_id) reasoncode,
       (select rcd.description
          from reasoncode_desc rcd
         where rcd.reasoncode_id = dv.reasoncode_id
           and rcd.language_id = l.language_id) reasoncodedesc
  from deliveryvariations dv, packingnoteline pnl, languages l
 where dv.packingnote_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

/
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_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_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_SHIPTO_ADDRESS
 (LINETYPE, PURCHASEORDERHEADER_ID, NAME, STREET, ZIPCODE, CITY)
as select 1 linetype, poh.purchaseorderheader_id, sk.name, a.street, a.zipcode, a.city --ordering stockroom
from purchaseorderheader poh
     join stockroom sk on poh.stockroom_id = sk.stockroom_id
     join address a on sk.deliveryaddress_id = a.address_id
where poh.shipto = 0
union
select 2 linetype, poh.purchaseorderheader_id, sk.name, a.street, a.zipcode, a.city --other stockroom
from purchaseorderheader poh
     join stockroom sk on poh.shiptostockroom_id = sk.stockroom_id
     join address a on sk.deliveryaddress_id = a.address_id
where poh.shipto = 1
union
select 3 linetype, poh.purchaseorderheader_id, c.name, a.street, a.zipcode, a.city --customer
from purchaseorderheader poh
     join deliverypoint dp on poh.deliverypoint_link_id = dp.deliverypoint_id
     join customer c on dp.customer_id = c.customer_id
     join address a on dp.deliveryaddress_id = a.address_id
where poh.shipto = 2
union
select 4 linetype, poh.purchaseorderheader_id, poai.name, poai.street1, poai.zipcode, poai.city --specific delivery address
from purchaseorderheader poh
     join purchaseorderaddressinfo poai on poh.purchaseorderheader_id = poai.purchaseorderheader_id
where poh.shipto = 3

/
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, --st.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) = to_date('31-12-2099','dd-mm-yyyy')
        then 1
        else 0
       end  missed,
       case when sl.unrelatedloan = 'Y' then 0
         else min(sl.inventory) end inventoryqty
  from soilticket s,       --left outer join stop st on st.stop_id = s.stop_id,
       soilticketline sl--,       routecontrol rc
       , reportparam rp
 where s.soilticket_id = sl.soilticket_id and s.routecontrol_id = rp.number_value
 group by rp.reportparam_id,
       s.routecontrol_id,
       s.customer_id,
       sl.product_id,
       sl.sizedefinition_id,
       sl.finishingmethod_id,
       s.routestopnumber, sl.unrelatedloan--st.stopnumber

/
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 z.reportparam_id, z.routecontrol_id, z.customer_id, z.product_id, z.sizedefinition_id, z.finishingmethod_id,
       sum(z.col1) pickupqty1,
       sum(z.col2) pickupqty2,
       sum(z.col3) pickupqty3,
       sum(z.col4) pickupqty4,
       sum(z.col5) pickupqty5,
       sum(z.col6) pickupqty6,
       sum(z.col7) pickupqty7,
       sum(z.col8) pickupqty8,
       sum(z.col9) pickupqty9,
       sum(z.col10) pickupqty10,
       sum(z.col11) pickupqty11,
       sum(z.col12) pickupqty12,
       sum(z.col13) pickupqty13,
       max(z.columnnr) nr_of_columns
 from (
select y.reportparam_id, y.routecontrol_id, y.customer_id, y.product_id, y.sizedefinition_id, y.finishingmethod_id, y.columnnr,
       case when y.columnnr = 1 then sum(y.qty) else 0 end col1,
       case when y.columnnr = 2 then sum(y.qty) else 0 end col2,
       case when y.columnnr = 3 then sum(y.qty) else 0 end col3,
       case when y.columnnr = 4 then sum(y.qty) else 0 end col4,
       case when y.columnnr = 5 then sum(y.qty) else 0 end col5,
       case when y.columnnr = 6 then sum(y.qty) else 0 end col6,
       case when y.columnnr = 7 then sum(y.qty) else 0 end col7,
       case when y.columnnr = 8 then sum(y.qty) else 0 end col8,
       case when y.columnnr = 9 then sum(y.qty) else 0 end col9,
       case when y.columnnr = 10 then sum(y.qty) else 0 end col10,
       case when y.columnnr = 11 then sum(y.qty) else 0 end col11,
       case when y.columnnr = 12 then sum(y.qty) else 0 end col12,
       case when y.columnnr = 13 then sum(y.qty) else 0 end col13
 from
(
select x.*, l.product_id, l.sizedefinition_id, l.finishingmethod_id,
       nvl(l.countlightframe,0) + nvl(l.countkeypad,0) + nvl(l.countconverted,0) +  nvl(l.countabused,0) qty from soilticketline l,
(select w.*, rp1.reportparam_id
  from (select rcmain.routecontrol_id,
               t.customer_id,
               r.route_id,
               r.drivingday_id,
               rc.drivingdate,
               t.soilticket_id,
               aa.columnnr
          from soilticket   t,
               routecontrol rc,
               route        r,
               routecontrol rcmain,
               route        rmain,
              (select a.mainroutecontrol_id,
                      a.routecontrol_id,
                      a.customer_id,
                      a.drivingdate,-- the following statement is to get a row# per routecontrol per customer orderd by driving date
                      row_number( ) over (partition by a.mainroutecontrol_id, a.customer_id order by a.drivingdate desc) columnnr
                 from (
                       select -- try adding hints here to prevent full table scan on soilticket t and routecontrol rc2
                              /* +index(rcmain2 XPKROUTECONTROL) index(rmain2 XPKROUTE) index(r2 XIF850ROUTE) index(rc2 XIF888ROUTECONTROL) index(t XIF989SOILTICKET)*/
                              rcmain2.routecontrol_id mainroutecontrol_id,
                              t.routecontrol_id,
                              t.customer_id,
                              rc2.drivingdate
                         from soilticket t,
                              routecontrol rc2,       -- historical routecontrols
                              route r2,               -- route linked to history routecontrol
                              routecontrol rcmain2,   -- current routecontrol here is the link with outer select
                              route rmain2            -- route linked to current routecontrol
                        where rc2.routecontrol_id = t.routecontrol_id
                          and r2.route_id = rc2.route_id
                          and rmain2.route_id = rcmain2.route_id
                          and rc2.drivingdate < rcmain2.drivingdate
                          and r2.drivingday_id = rmain2.drivingday_id
                          and t.countdate <> to_date('31-12-2099','DD-MM-YYYY')  -- only include counted soil tickets
                        group by rcmain2.routecontrol_id, t.routecontrol_id, t.customer_id, rc2.drivingdate
                      ) a
                order by a.routecontrol_id, a.customer_id, columnnr) aa
         where t.routecontrol_id = rc.routecontrol_id
           and r.route_id = rc.route_id
           and rmain.route_id = rcmain.route_id
           and rmain.drivingday_id = r.drivingday_id
           and aa.customer_id = t.customer_id
           and aa.routecontrol_id = rc.routecontrol_id
           and aa.mainroutecontrol_id = rcmain.routecontrol_id
           and t.customer_id in
               (select distinct s.customer_link_id
                  from stop s
                 where s.routecontrol_id = rcmain.routecontrol_id)
           and rc.drivingdate < rcmain.drivingdate
         order by rcmain.routecontrol_id,
                  t.customer_id,
                  columnnr) w, reportparam rp1
 where w.columnnr <= rp1.number_value4 and w.routecontrol_id = rp1.number_value) x
 where l.soilticket_id = x.soilticket_id
 order by x.routecontrol_id, x.customer_id, x.columnnr
) y
group by y.reportparam_id, y.routecontrol_id, y.customer_id, y.product_id, y.sizedefinition_id, y.finishingmethod_id, y.columnnr) z
group by z.reportparam_id, z.routecontrol_id, z.customer_id, z.product_id, z.sizedefinition_id, z.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_STATEMENTINVOICES_AUJ
 (STATEMENTHEADER_ID, INVOICEHEADER_ID, COMMONCUSTOMER_NR, STATEMENTNUMBER)
as select distinct sh.invoiceheader_id statementheader_id, ih.invoiceheader_id
, (select comm.customernumber from customer comm, customer del where ih.deltocustomer_link_id = del.customer_id
  and comm.customer_id = coalesce(del.commoncustomer_id, del.debtor_id)) commoncustomer_nr
, sh.invoicenumber  statementnumber
from invoiceheader sh, statementline sl, artransaction ar, invoiceheader ih, invoiceheaderextrainfo she
where sh.invoiceheader_id = sl.invoiceheader_id
and sl.artransaction_id = ar.artransaction_id
and ar.invoiceheader_id = ih.invoiceheader_id
and ih.documenttype <> 2
and sh.documenttype = 2
and she.invoiceheader_id = sh.invoiceheader_id--for the Summary layout do not select child invoices
and she.formlayoutcode <> '2'

/
create or replace view V_STATEMENTLINE_AUJ
 (INVOICEDATE, STATEMENTNUMBER, INVOICELINETYPE, TRANSACTIONTYPE_ID, TRANSACTIONTYPENUMBER, TRANSACTIONTYPECODE, TRANSACTIONREFERENCE, TRANSACTIONDATE, DEBITCREDIT, AMOUNT, PERCENTAGE, SYSTEMUSER_ID, TIMESTAMP, STATEMENTLINE_ID, STATEMENTHEADER_ID, ARTRANSACTION_ID, PNNUMBER, DEL_NUMBER, DEL_NAME, COMMONCUSTOMER_NUMBER, COMMONCUSTOMER_NAME, AR_INVOICEHEADER_ID, AR_AMOUNT, VATAMOUNT, SALESAREA_CODE)
as select f.invoicedate, f.invoicenumber statementnumber, e.type invoicelinetype,
a.transactiontype_id,x.typenumber transactiontypenumber, x.code transactiontypecode,
a.transactionreference, a.transactiondate, a.debitcredit, a.amount
,a.percentage, a.systemuser_id, a.timestamp, a.statementline_id, a.invoiceheader_id statementheader_id, a.artransaction_id
, cc.pnnumber, del.customernumber Del_Number, del.name Del_Name
, cc.customernumber CommonCustomer_Number, cc.name CommonCustomer_Name, ar.invoiceheader_id AR_invoiceheader_id, ar.amount AR_Amount
, coalesce((ar.amount - (select ih.totalamountexclvat from invoiceheader ih where ar.invoiceheader_id = ih.invoiceheader_id)), 0) VATAmount
, (select sa.code from salesarea sa where cc.salesarea_id = sa.salesarea_id) salesarea_code
from statementline a
left outer join artransactiontype x ON (a.transactiontype_id = x.artransactiontype_id)
left outer join (artransaction ar
     inner join (customer del
           inner join customer cc
           on cc.customer_id = coalesce(del.commoncustomer_id, del.debtor_id))
     on del.customer_id = coalesce(ar.deltocustomer_link_id, ar.billtocustomer_link_id))
ON (a.artransaction_id = ar.artransaction_id)
join invoicelinetype e on a.invoicelinetype_id = e.invoicelinetype_id
join invoiceheader f on a.invoiceheader_id = f.invoiceheader_id
where f.documenttype = 2

/
create or replace view V_STATEMENT_PAYMENTHISTORY_AMM
 (BILLTOCUSTOMER_LINK_ID, ARTRANSACTIONDATE, REMITIDENTIFICATION, AMOUNT)
as SELECT A.BILLTOCUSTOMER_LINK_ID, A.ARTRANSACTIONDATE, A.REMITIDENTIFICATION, A.AMOUNT
FROM ARTRANSACTION A, ARTRANSACTIONTYPE B
WHERE A.ARTRANSACTIONTYPE_ID = B.ARTRANSACTIONTYPE_ID AND B.TYPENUMBER = 5 --AND rownum <= 4
order by a.artransactiondate desc

/
create or replace view V_STOCKRECEPTIONPERDATE_AUX
 (CUSTOMERNUMBER, CUSTOMERNAME, WEARERNUMBER, FULLNAME, WORKORDERNUMBER, WONEEDEDDATE, REFERENCENUMBER, QTYDIFF, 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
, 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
, 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_THEORETICALWEIGHT_AUX_ANG
 (CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESC, WEIGHINGCATCODE, CLEANWEIGHT, SOILWEIGHT, WEIGHINGDATE, CUSTOMER_LINK_ID, DEPARTMENT_LINK_ID, DISTRIBUTIONPOINT_LINK_ID, WEIGHINGHISTORY_ID, WEIGHINGCATEGORY_ID, PROCESSBUSINESSUNIT_ID)
as select
  culk.customernumber, culk.name customerName
, delk.departmentnumber, delk.description departmentDesc
, weigcat.code WeighingCatCode
, weighis.cleanweight, weighis.soilweight, weighis.weighingdate
, weighis.customer_link_id, weighis.department_link_id, weighis.distributionpoint_link_id
, weighis.weighinghistory_id, weigcat.weighingcategory_id, weighis.processbusinessunit_id
from
  customer_link culk, department_link delk
, weighingcategory weigcat,  weighinghistory weighis
where
    weighis.customer_link_id = culk.customer_link_id
and weighis.department_link_id = delk.department_link_id
and weighis.weighingcategory_link_id = weigcat.weighingcategory_id
/* weighis UQ
CUSTOMER_LINK_ID, DEPARTMENT_LINK_ID, DISTRIBUTIONPOINT_LINK_ID, WEIGHINGCATEGORY_LINK_ID
,WEIGHINGDATE , PROCESSBUSINESSUNIT_ID
*/

/
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_WORKORDEREMBLEM
 (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)
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
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
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
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_WORKORDEREMBLEM_EMBCOLORS
 (EMBLEMTEMPLATELINE_ID, EMBROIDERYCOLOR_ID, SEQUENCENUMBER, COLOR_ID, COLOR_CODE, COLOR_RALCODE, COLOR_USEDFOREMBLEM, COLOR_DESCRIPTION, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE)
as SELECT ec.emblemtemplateline_id, ec.embroiderycolor_id, ec.sequencenumber,
       ec.color_id, color.code color_code, color.ralcode color_ralcode, color.usedforemblem color_usedforemblem,
       (SELECT cd.description FROM color_desc cd WHERE cd.color_id = color.color_id AND cd.language_id = lang.language_id) color_description,
       ec.systemuser_id, ec.timestamp,
       lang.code LANGUAGECODE
FROM embroiderycolor ec, color, emblemtemplateline et, languages lang
WHERE ec.emblemtemplateline_id = et.emblemtemplateline_id
      AND ec.color_id = color.color_id

/
create or replace view V_WORKORDERPLPC
 (WORKORDERLINE_ID, WORKORDER_ID, SUPPLIERNUMBER, SUPLIERNAME, LOGOFILEPATHORIGINAL, LOGOFILEPATHPRODUCTION, BACKING, BORDERWIDTH, BORDERMATERIAL, THICKNESS, ACTUALWIDTH, ACTUALLENGTH, SHAPE, DIRECTION, MATCOLORTYPE, SEQUENCENUMBER, BG_CODE, BG_DESC, LOGO_CODE, LOGO_DESC, LANGUAGE_CODE)
as select 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
, (select c.code from color c where c.color_id=mc.color_id and mc.matcolortype=2) Bg_code
, (select cd.description from color c, color_desc cd where c.color_id=mc.color_id and mc.matcolortype=2 and cd.color_id=c.color_id and cd.language_id=lan.language_id) Bg_desc
, (select c.code from color c where c.color_id=mc.color_id and mc.matcolortype=1) Logo_code
, (select cd.description from color c, color_desc cd where c.color_id=mc.color_id and mc.matcolortype=1 and cd.color_id=c.color_id and cd.language_id=lan.language_id) Logo_desc
, lan.code Language_code
from workorderline wokli, workorder wo, productlistpercustomer plpc
left outer join matcolor mc on mc.productlistpercustomer_id=plpc.productlistpercustomer_id
, matorderinginfo moi, supplier sup, languages lan
where wokli.workorder_id=wo.workorder_id
and wo.customer_link_id=plpc.customer_id
and plpc.product_id=wokli.product_link_id
and plpc.finishingmethod_id=wokli.finishingmethod_id
and plpc.sizedefinition_id=wokli.sizedefinition_link_id
and wo.entrydate >= plpc.dateactive
and wo.entrydate <= plpc.dateinactive
and plpc.productlistpercustomer_id=moi.productlistpercustomer_id
and moi.supplier_id=sup.supplier_id

/
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_COMPLETENESSCUSTDETAILS_STX
 (LINETYPE, REPORTPARAM_ID, BUSINESSUNIT_ID, STAY, IDCODE, UNIQUEITEM_ID, LANGUAGECODE, PLANNEDDELIVERYDATE, LASTINSCANDATE, STATUS_ID, PRODUCTCODE, PRODUCTDESC, ROUTENUMBER, ROUTEDESC, SIZEDEFINITIONCODE, WEARERNAME, CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESC, DAY_ID, CUSTOMERADDRES, CUSTOMERADDRES2, MAXCOMPLETENESSDAYS, INTERNALBU, NONUNIQUEQTY, BATCHNUMBER)
as select 1 linetype, rp.reportparam_id,b.businessunit_id businessunit_id,
 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 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 = 10 and st.code = '30' THEN 6
    END "STAY",
 b.primaryid idcode, b.uniqueitem_id,
 languages.code languagecode,
 case
     when c.staynr = 36 then GETABSMINDATE()
   else b.planneddeliverydate
 end planneddeliverydate,
to_char(b.lastinscandate, 'MM/DD/YYYY HH:MI:SS AM') lastinscandate,
 b.status_id,
 ce.code productcode,
 (SELECT description FROM product_DESC w WHERE w.product_id = ce.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 1 routenumber, '' routedesc,
 ck.code sizedefinitioncode,
 cast(concatenatewithblank3(h.firstname,h.fullname,  nvl(h.customeremployeenumber,''))as varchar2(75)) 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(GETCURRENTDATE(), 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
 , 1  NonUniqueQty
 ,b.batchnumber batchnumber
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 , businessunit bu  , status st,
 product ce, customer cg, department ch, address ci, languages, sizedefinition ck
where b.poolitem = 2
 and b.stay_id = c.stay_id
 and c.staytype = 1
 and b.uniqueitem_id = e.uniqueitem_id
 and  bu.businessunit_id = b.businessunit_id
 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.sizedefinition_id = ck.sizedefinition_id
 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.customer_id=rp.number_value
  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 2 linetype,
  rp.reportparam_id,
  ds.businessunit_id, 7 stay,
   b.primaryid idcode, b.uniqueitem_id,
 languages.code languagecode,
 GETABSMINDATE()planneddeliverydate,
to_char(b.lastinscandate, 'MM/DD/YYYY HH:MI:SS AM') lastinscandate,
b.status_id, p.code productcode,
 (SELECT description FROM product_DESC w WHERE w.product_id = p.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 1 routenumber, '' routedesc,
  ck.code sizedefinitioncode,
  cast(concatenatewithblank3(h.firstname,h.fullname, nvl(h.customeremployeenumber,''))as varchar2(75)) 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,
  1 NonUniqueQty
  ,b.batchnumber batchnumber
 FROM PRODUCT p, UNIQUEITEM  b,  businessunit bu ,
  DELIVERYSCAN ds,distributionpoint g,customer cg, department ch, address ci,
   WEAREREMPLOYMENT f,WEARER h
   , stay c,sizedefinition ck,languages, reportparam rp
 WHERE p.PRODUCT_ID = b.PRODUCT_ID
 and b.sizedefinition_id=ck.sizedefinition_id
 and  bu.businessunit_id = b.businessunit_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 f.WEARER_ID = h.WEARER_ID
 and h.CUSTOMER_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 ds.WEAREREMPLOYMENT_LINK_ID = f.WEAREREMPLOYMENT_ID
 and rp.number_value=cg.customer_id
 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_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
       end "STAY", 0 flag_no, getdatediff(getcurrentdate(), 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)
as select 1 linetype, rp.reportparam_id,b.businessunit_id businessunit_id,
 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 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 = 10 and st.code = '30' THEN 6
    END "STAY",
 b.primaryid idcode, b.uniqueitem_id,
 languages.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 description FROM product_DESC w WHERE w.product_id = ce.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 1 routenumber, '' routedesc,
 (SELECT description FROM finishingmethod_DESC y WHERE y.finishingmethod_id = j.finishingmethod_id
  AND y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddesc,
 ck.code sizedefinitioncode,
 (SELECT COUNT(*) 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(GETCURRENTDATE(), 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
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
   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 bu.businessunit_id = b.businessunit_id,
    status st,
 product ce, customer cg, department ch, address ci, languages, sizedefinition ck
where b.poolitem = 2
 and b.stay_id = c.stay_id
 and c.staytype = 1
 and b.uniqueitem_id = e.uniqueitem_id
 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.sizedefinition_id = ck.sizedefinition_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 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.customer_id=rp.number_value
 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
 SELECT 2 linetype,
  rp.reportparam_id,
  ds.businessunit_id, 7 stay,
   b.primaryid idcode, b.uniqueitem_id,
 languages.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 description FROM product_DESC w WHERE w.product_id = p.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 1 routenumber, '' routedesc,
 (SELECT description FROM finishingmethod_DESC y WHERE y.finishingmethod_id = b.finishingmethod_id
  AND y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddesc,
  ck.code sizedefinitioncode,
 (SELECT COUNT(*) 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
 FROM PRODUCT p, UNIQUEITEM  b
   inner join businessunit bu
         left outer join systemsetting sst on sst.plant_id = bu.plant_id and sst.name = 'COMPCHECKNONUNIQUE'
   on bu.businessunit_id = b.businessunit_id,
   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 /*+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 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
     )
union all
select 3 linetype, rp.reportparam_id, b.businessunit_id businessunit_id,
 1 stay, ''  idcode, 0 uniqueitem_id,
 languages.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 description FROM product_DESC w WHERE w.product_id = ce.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 1 routenumber, '' routedesc,
 (SELECT description FROM finishingmethod_DESC y WHERE y.finishingmethod_id = j.finishingmethod_id
  AND y.LANGUAGE_ID = LANGUAGES.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
from  deliveryvariations dv,  distributionpoint g,reportparam rp,
  product ce, customer cg, department ch, address ci, languages, sizedefinition ck,finishingmethod j, businessunit b
         left outer join systemsetting sst on sst.plant_id = b.plant_id and sst.name = 'COMPCHECKNONUNIQUE'
where dv.distributionpoint_id=g.distributionpoint_id
 and g.department_id=ch.department_id
 and ch.customer_id=cg.customer_id
 and cg.visitaddress_id = ci.address_id
 and dv.product_id = ce.product_id
 and dv.sizedefinition_id = ck.sizedefinition_id
 and dv.finishingmethod_id=j.finishingmethod_id
-- and cg.customer_id=rp.number_value
 and 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 (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 )= b.businessunit_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
 select 4 linetype, rp.reportparam_id, b.businessunit_id businessunit_id,
 7 stay, ''  idcode, 0 uniqueitem_id,
 languages.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 description FROM product_DESC w WHERE w.product_id = ce.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 1 routenumber, '' routedesc,
 (SELECT description FROM finishingmethod_DESC y WHERE y.finishingmethod_id = j.finishingmethod_id
  AND y.LANGUAGE_ID = LANGUAGES.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
from  cleancountdelivery cc,  distributionpoint g,reportparam rp,
  product ce, customer cg, department ch, address ci, languages, sizedefinition ck,finishingmethod j, businessunit b
         left outer join systemsetting sst on sst.plant_id = b.plant_id and sst.name = 'COMPCHECKNONUNIQUE'
where cc.distributionpoint_id=g.distributionpoint_id
 and g.department_id=ch.department_id
 and ch.customer_id=cg.customer_id
 and cg.visitaddress_id = ci.address_id
 and cc.product_id = ce.product_id
 and cc.sizedefinition_id = ck.sizedefinition_id
 and cc.finishingmethod_id=j.finishingmethod_id
-- and cg.customer_id=rp.number_value
 and 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 (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 )= b.businessunit_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_COMPLETENESSCUSTOMERDET_JWR
 (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, WEARERFLAGDATE, WEAREREMPFLAGDATE, UNIQUEITEMFLAGDATE, MAXCOMPLETENESSDAYS, INTERNALBU)
as select b.businessunit_id businessunit_id,
 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 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 = 10 and st.code = '30' THEN 6
   when c.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
           or (ds.packingnote_id is not null and (( select s.code from packingnote pn, status s
               where pn.packingnote_id=ds.packingnote_id and pn.status_id=s.status_id and s.statustype='PN') ='20')))
         and ds.uniqueitem_link_id = b.uniqueitem_id
         and ds.businessunit_id = b.businessunit_id) then
          7
 END "STAY",
 b.primaryid idcode, b.uniqueitem_id,
 languages.code languagecode,
-- b.planneddeliverydate,
 case
   when c.staynr = 20 then GETABSMINDATE()
   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.lastinscandate, b.lastscandate,
 b.status_id,
 ce.code productcode,
 (SELECT description FROM product_DESC w WHERE w.product_id = ce.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 1 routenumber, '' routedesc,
 (SELECT description FROM finishingmethod_DESC y WHERE y.finishingmethod_id = j.finishingmethod_id
  AND y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddesc,
 ck.code sizedefinitioncode,
 (SELECT COUNT(*) 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, cdd.day_id,
 ci.street customeraddres
, cast(CONCATENATEWITHBLANK(ci.zipcode, ci.city) as varchar2(255)) customeraddres2,
 cast (case
   when f1.flag_id is null then null
   else h.flagstartdate
   end as date) wearerflagdate,
 cast (case
   when f2.flag_id is null then null
   else f.flagstartdate
   end as date) wearerempflagdate,
 uf.uniqueitemflagdate,
 GETDATEDIFF(GETCURRENTDATE(), 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
-- h.flagstartdate wearerflagdate, f.flagstartdate wearerempflagdate, uf.uniqueitemflagdate
from stay c, 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
   left outer join finishingmethod j on (b.finishingmethod_id = j.finishingmethod_id)
   left outer join vr_uniqueitemflag uf on uf.uniqueitem_id = b.uniqueitem_id,
 status st,
 product ce, customer cg, department ch, address ci, languages, sizedefinition ck, customerdeliveryday cdd
where b.poolitem = 2
 and b.stay_id = c.stay_id
 and c.staytype = 1
 and b.uniqueitem_id = e.uniqueitem_id
 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.sizedefinition_id = ck.sizedefinition_id
 and cg.customer_id = cdd.customer_id
 and (cdd.deliverytype = 'B' or cdd.deliverytype = 'D')
 and cdd.typeofmerchadise = 2
 and c.staynr not in (22,23,24,25)
 and (
 ((( select ss.value from systemsetting ss, businessunit bu where b.businessunit_id=bu.businessunit_id and bu.plant_id=ss.plant_id and
  ss.name='DEPOSITSTOCKINCC')=1) and c.staynr <>'37') or
  (( select ss.value from systemsetting ss, businessunit bu where b.businessunit_id=bu.businessunit_id and bu.plant_id=ss.plant_id and
  ss.name='DEPOSITSTOCKINCC')=0) )

/
create or replace view VR_COMPLETENESSCUSTOMERDET_PCO
 (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)
as select 1 linetype, rp.reportparam_id,b.businessunit_id businessunit_id,
 /*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 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 = 10 and st.code = '30' THEN 6
    END*/1 "STAY",
 b.primaryid idcode, b.uniqueitem_id,
 languages.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 description FROM product_DESC w WHERE w.product_id = ce.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 1 routenumber, '' routedesc,
 (SELECT description FROM finishingmethod_DESC y WHERE y.finishingmethod_id = j.finishingmethod_id
  AND y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddesc,
 ck.code sizedefinitioncode,
 (SELECT COUNT(*) 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(GETCURRENTDATE(), 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
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
   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 bu.businessunit_id = b.businessunit_id,
    status st,
 product ce, customer cg, department ch, address ci, languages, sizedefinition ck
where b.poolitem = 2
 and b.stay_id = c.stay_id
 and c.staytype = 1
 and b.uniqueitem_id = e.uniqueitem_id
 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.sizedefinition_id = ck.sizedefinition_id
 and (( exists (select 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))
     or (( exists (select 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))
        or (exists (select 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))))
 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.customer_id=rp.number_value
  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)
 and c.staynr = 30 and (st.code = '20' or st.code = '30')
 and ce.typeofmerchandise = 2--20308 - rework to exclude non-garments
 /*
union all
 SELECT 2 linetype,
  rp.reportparam_id,
  ds.businessunit_id, 7 stay,
   b.primaryid idcode, b.uniqueitem_id,
 languages.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 description FROM product_DESC w WHERE w.product_id = p.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 1 routenumber, '' routedesc,
 (SELECT description FROM finishingmethod_DESC y WHERE y.finishingmethod_id = b.finishingmethod_id
  AND y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddesc,
  ck.code sizedefinitioncode,
 (SELECT COUNT(*) 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
 FROM PRODUCT p, UNIQUEITEM  b
   inner join businessunit bu
         left outer join systemsetting sst on sst.plant_id = bu.plant_id and sst.name = 'COMPCHECKNONUNIQUE'
   on bu.businessunit_id = b.businessunit_id,
  DELIVERYSCAN ds,distributionpoint g,customer cg, department ch, address ci,
   WEAREREMPLOYMENT f,
   WEARER h
   , 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 f.WEARER_ID = h.WEARER_ID
 and h.CUSTOMER_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 ds.WEAREREMPLOYMENT_LINK_ID = f.WEAREREMPLOYMENT_ID
 and (( exists (select 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))
       or (( exists (select 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))
         or (exists (select 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))))
 and rp.number_value=cg.customer_id
 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
select 3 linetype, rp.reportparam_id, b.businessunit_id businessunit_id,
 1 stay, ''  idcode, 0 uniqueitem_id,
 languages.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 description FROM product_DESC w WHERE w.product_id = ce.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 1 routenumber, '' routedesc,
 (SELECT description FROM finishingmethod_DESC y WHERE y.finishingmethod_id = j.finishingmethod_id
  AND y.LANGUAGE_ID = LANGUAGES.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
from  deliveryvariations dv,  distributionpoint g,reportparam rp,
  product ce, customer cg, department ch, address ci, languages, sizedefinition ck,finishingmethod j, businessunit b
         left outer join systemsetting sst on sst.plant_id = b.plant_id and sst.name = 'COMPCHECKNONUNIQUE'
where dv.distributionpoint_id=g.distributionpoint_id
 and g.department_id=ch.department_id
 and ch.customer_id=cg.customer_id
 and cg.visitaddress_id = ci.address_id
 and dv.product_id = ce.product_id
 and dv.sizedefinition_id = ck.sizedefinition_id
 and dv.finishingmethod_id=j.finishingmethod_id
 and cg.customer_id=rp.number_value
 and (dv.packingnote_id is null or exists (select 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))
 and dv.origin  in (1, 5)
 and (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 )= b.businessunit_id
 and (( exists (select 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))
     or (( exists (select 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))
        or (exists (select 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))))
 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
    and ce.typeofmerchandise = 2--20308 - rework to exclude non-garments
/*
union all
 select 4 linetype, rp.reportparam_id, b.businessunit_id businessunit_id,
 7 stay, ''  idcode, 0 uniqueitem_id,
 languages.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 description FROM product_DESC w WHERE w.product_id = ce.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 1 routenumber, '' routedesc,
 (SELECT description FROM finishingmethod_DESC y WHERE y.finishingmethod_id = j.finishingmethod_id
  AND y.LANGUAGE_ID = LANGUAGES.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  NonUniqueQty
 , g.distributionpointnumber, g.description distributionpoint_desc
from  cleancountdelivery cc,  distributionpoint g,reportparam rp,
  product ce, customer cg, department ch, address ci, languages, sizedefinition ck,finishingmethod j, businessunit b
         left outer join systemsetting sst on sst.plant_id = b.plant_id and sst.name = 'COMPCHECKNONUNIQUE'
where cc.distributionpoint_id=g.distributionpoint_id
 and g.department_id=ch.department_id
 and ch.customer_id=cg.customer_id
 and cg.visitaddress_id = ci.address_id
 and cc.product_id = ce.product_id
 and cc.sizedefinition_id = ck.sizedefinition_id
 and cc.finishingmethod_id=j.finishingmethod_id
 and cg.customer_id=rp.number_value
 and (cc.packingnote_id is null or exists (select 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))
 and (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 )= b.businessunit_id
 and (( exists (select 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))
     or (( exists (select 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))
        or (exists (select 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))))
 and cc.deliverydate <= rp.date_value1
      and sst.value = '0'*/

/
create or replace view VR_COMPLETENESSCUSTOMERDET_STK
 (BUSINESSUNIT_ID, STAY, IDCODE, UNIQUEITEM_ID, LANGUAGECODE, PLANNEDDELIVERYDATE, LASTINSCANDATE, LASTSCANDATE, STATUS_ID, PRODUCTCODE, PRODUCTDESC, ROUTENUMBER, ROUTEDESC, FINISHINGMETHODDESC, SIZEDEFINITIONCODE, FLAG, FLAG_NO, WEARERNUMBER, WEARERNAME, CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESC, DAY_ID, CUSTOMERADDRES, CUSTOMERADDRES2, WEARERFLAGDATE, WEAREREMPFLAGDATE, UNIQUEITEMFLAGDATE, MAXCOMPLETENESSDAYS)
as select b.businessunit_id businessunit_id,
 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 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 = 10 and st.code = '30' THEN 6
 END "STAY",
 b.primaryid idcode, b.uniqueitem_id,
 languages.code languagecode,
-- b.planneddeliverydate,
 case
   when c.staynr = 36 then GETABSMINDATE()
   else b.planneddeliverydate
 end planneddeliverydate,
to_char(b.lastinscandate, 'DD-MM-YYYY HH:MI:SS AM') lastinscandate,
to_char(b.lastscandate, 'DD-MM-YYYY HH:MI:SS AM') lastscandate,
-- b.lastinscandate, b.lastscandate,
 b.status_id,
 ce.code productcode,
 (SELECT description FROM product_DESC w WHERE w.product_id = ce.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 1 routenumber, '' routedesc,
 (SELECT description FROM finishingmethod_DESC y WHERE y.finishingmethod_id = j.finishingmethod_id
  AND y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddesc,
 ck.code sizedefinitioncode,
 (SELECT COUNT(*) 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,
 cl.wearernumber, cl.fullname wearername,
 cg.customernumber, cg.name customername, ch.departmentnumber, ch.description departmentdesc, cdd.day_id,
 ci.street customeraddres
, cast(CONCATENATEWITHBLANK(ci.zipcode, ci.city) as varchar2(255)) customeraddres2,
 cast (case
   when f1.flag_id is null then null
   else h.flagstartdate
   end as date) wearerflagdate,
 cast (case
   when f2.flag_id is null then null
   else f.flagstartdate
   end as date) wearerempflagdate,
 uf.uniqueitemflagdate,
 GETDATEDIFF(GETCURRENTDATE(), B.LASTINSCANDATE) MAXCOMPLETENESSDAYS
-- h.flagstartdate wearerflagdate, f.flagstartdate wearerempflagdate, uf.uniqueitemflagdate
from stay c, 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
   left outer join finishingmethod j on (b.finishingmethod_id = j.finishingmethod_id)
   left outer join vr_uniqueitemflag uf on uf.uniqueitem_id = b.uniqueitem_id,
 status st,
 product ce, customer cg, department ch, address ci, languages, sizedefinition ck, wearer cl,
 customerdeliveryday cdd
where b.poolitem = 2
 and b.stay_id = c.stay_id
 and c.staytype = 1
 and b.uniqueitem_id = e.uniqueitem_id
 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.sizedefinition_id = ck.sizedefinition_id
 and f.wearer_id = cl.wearer_id
 and cg.customer_id = cdd.customer_id
 and (cdd.deliverytype = 'B' or cdd.deliverytype = 'D')
 and cdd.typeofmerchadise = 2
 and c.staynr not in (22,23,24,25)
 and (
 ((( select ss.value from systemsetting ss, businessunit bu where b.businessunit_id=bu.businessunit_id and bu.plant_id=ss.plant_id and
  ss.name='DEPOSITSTOCKINCC')=0) and c.staynr <>'37') or
  (( select ss.value from systemsetting ss, businessunit bu where b.businessunit_id=bu.businessunit_id and bu.plant_id=ss.plant_id and
  ss.name='DEPOSITSTOCKINCC')=1) )

/
create or replace view VR_COMPLETENESSCUSTOMER_PCO
 (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 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
           end*/1 "STAY",
       0 flag_no,
        getdatediff(getcurrentdate(), 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 (( exists (select 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))
     or (( exists (select 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))
        or (exists (select 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))))
  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 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)
  and c.staynr = 30 and (st.code = '20' or st.code = '30')
  and ce.typeofmerchandise = 2--20308 - rework to exclude non-garments
/*union
  SELECT
  rp.reportparam_id,  ds.businessunit_id, languages.code languagecode,
 GETABSMINDATE()planneddeliverydate , b.lastinscandate lastinscan_date,b.status_id, p.code productcode,
 (SELECT 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, 0 flag_no,
    0 maxcompletenessdays,
  ds.internalprocessingbu_id internalBu
 FROM PRODUCT p, UNIQUEITEM  b,
  DELIVERYSCAN ds,distributionpoint g,customer cg, department ch, address ci,
   WEAREREMPLOYMENT f,-- left outer join flag f2 on f2.flag_id = f.flag_id     and f2.includeincompletnesscheck = 'N',
   WEARER h,-- left outer join flag f1 on f1.flag_id = h.flag_id  and f1.includeincompletnesscheck = 'N'
      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 f.WEARER_ID = h.WEARER_ID
 and h.CUSTOMER_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 ds.WEAREREMPLOYMENT_LINK_ID = f.WEAREREMPLOYMENT_ID
 --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)
 and (( exists (select 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))
     or (( exists (select 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))
        or (exists (select 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))))
 and rp.number_value=cg.customer_id
 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_COMPLETENESSCUSTOMER_STX
 (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, BATCHNUMBER)
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 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
           end "STAY",
       0 flag_no,
        getdatediff(getcurrentdate(), 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,
 b.batchnumber
  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 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 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
  SELECT
  rp.reportparam_id,  ds.businessunit_id, languages.code languagecode,
 GETABSMINDATE()planneddeliverydate , b.lastinscandate lastinscan_date,b.status_id, p.code productcode,
 (SELECT 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, 0 flag_no,
    0 maxcompletenessdays,
  ds.internalprocessingbu_id internalBu,
  ds.batchnumber
 FROM PRODUCT p, UNIQUEITEM  b,
  DELIVERYSCAN ds,distributionpoint g,customer cg, department ch, address ci,
   WEAREREMPLOYMENT f,
   WEARER h,
      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 f.WEARER_ID = h.WEARER_ID
 and h.CUSTOMER_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 ds.WEAREREMPLOYMENT_LINK_ID = f.WEAREREMPLOYMENT_ID
 and rp.number_value=cg.customer_id
 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_COMPLETENESSDELNOTE_BNL
 (BUSINESSUNIT_ID, STAY, IDCODE, UNIQUEITEM_ID, LANGUAGECODE, PLANNEDDELIVERYDATE, LASTINSCANDATE, LASTSCANDATE, STATUS_ID, PRODUCTCODE, PRODUCTDESC, ROUTENUMBER, ROUTEDESC, FINISHINGMETHODDESC, SIZEDEFINITIONCODE, WEARERNUMBER, WEARERNAME, CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESC, DAY_ID, CUSTOMERADDRES, CUSTOMERADDRES2, WEARERFLAGDATE, WEAREREMPFLAGDATE, UNIQUEITEMFLAGDATE, MAXCOMPLETENESSDAYS)
as select b.businessunit_id businessunit_id,
 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
 END "STAY",
 b.primaryid idcode, b.uniqueitem_id,
 languages.code languagecode,
-- b.planneddeliverydate,
 case
   when c.staynr = 36 then GETABSMINDATE()
   else b.planneddeliverydate
 end planneddeliverydate,
 b.lastinscandate, b.lastscandate, b.status_id,
 ce.code productcode,
 (SELECT description FROM product_DESC w WHERE w.product_id = ce.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 1 routenumber, '' routedesc,
 (SELECT description FROM finishingmethod_DESC y WHERE y.finishingmethod_id = j.finishingmethod_id
  AND y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddesc,
 ck.code sizedefinitioncode,
-- (SELECT COUNT(*) FROM UNIQUEITEMFLAG Z, flag fl WHERE Z.UNIQUEITEM_ID = b.UNIQUEITEM_ID
--   and z.flag_id = fl.flag_id
--   and fl.includeincompletnesscheck = 'Y') FLAG, -- removed for speed improvment
-- 0 FLAG_NO,
 cl.wearernumber, cl.fullname wearername,
 cg.customernumber, cg.name customername, ch.departmentnumber, ch.description departmentdesc, cdd.day_id,
 ci.street customeraddres
, cast(CONCATENATEWITHBLANK(ci.zipcode, ci.city) as varchar2(255)) customeraddres2,
 cast (case
   when f1.flag_id is null then null
   else h.flagstartdate
   end as date) wearerflagdate,
 cast (case
   when f2.flag_id is null then null
   else f.flagstartdate
   end as date) wearerempflagdate,
 uf.uniqueitemflagdate,
 GETDATEDIFF(GETCURRENTDATE(), B.LASTINSCANDATE) MAXCOMPLETENESSDAYS
-- h.flagstartdate wearerflagdate, f.flagstartdate wearerempflagdate, uf.uniqueitemflagdate
from stay c, 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
   left outer join finishingmethod j on (b.finishingmethod_id = j.finishingmethod_id)
   left outer join vr_uniqueitemflag uf on uf.uniqueitem_id = b.uniqueitem_id,
 status st,
 product ce, customer cg, department ch, address ci, languages, sizedefinition ck, wearer cl,
 customerdeliveryday cdd
where b.poolitem = 2
 and b.stay_id = c.stay_id
 and c.staytype = 1
 and b.uniqueitem_id = e.uniqueitem_id
 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.sizedefinition_id = ck.sizedefinition_id
 and f.wearer_id = cl.wearer_id
 and cg.customer_id = cdd.customer_id
 and (cdd.deliverytype = 'B' or cdd.deliverytype = 'D')
 and cdd.typeofmerchadise = 2
 and c.staynr not in (22,23,24,25)

/
create or replace view VR_COMPLETENESSDELNOTE_SMG
 (BUSINESSUNIT_ID, STAY, IDCODE, UNIQUEITEM_ID, LANGUAGECODE, PLANNEDDELIVERYDATE, LASTINSCANDATE, LASTSCANDATE, STATUS_ID, PRODUCTCODE, PRODUCTDESC, ROUTENUMBER, ROUTEDESC, FINISHINGMETHODDESC, SIZEDEFINITIONCODE, WEARERNUMBER, WEARERNAME, WEARERSEARCHNAME, CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESC, DAY_ID, CUSTOMERADDRES, CUSTOMERADDRES2, WEARERFLAGDATE, WEAREREMPFLAGDATE, UNIQUEITEMFLAGDATE, REASON_CODE, MAXCOMPLETENESSDAYS)
as select b.businessunit_id businessunit_id,
 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 1
   WHEN(c.staynr between 33 and 99 and c.staynr <> 36) and (st.code = '20' or st.code = '30') THEN 1
   WHEN c.staynr = 36 and (st.code = '20' or st.code = '30') THEN 5
   WHEN c.staynr = 10 and st.code = '30' THEN 6
 END "STAY",
 b.primaryid idcode, b.uniqueitem_id,
 languages.code languagecode,
-- b.planneddeliverydate,
 case
   when c.staynr = 36 then GETABSMINDATE()
   else b.planneddeliverydate
 end planneddeliverydate,
 b.lastinscandate, b.lastscandate, b.status_id,
 ce.code productcode,
 (SELECT description FROM product_DESC w WHERE w.product_id = ce.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 1 routenumber, '' routedesc,
 (SELECT description FROM finishingmethod_DESC y WHERE y.finishingmethod_id = j.finishingmethod_id
  AND y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddesc,
 ck.code sizedefinitioncode,
-- (SELECT COUNT(*) FROM UNIQUEITEMFLAG Z, flag fl WHERE Z.UNIQUEITEM_ID = b.UNIQUEITEM_ID
--   and z.flag_id = fl.flag_id
--   and fl.includeincompletnesscheck = 'Y') FLAG, -- removed for speed improvment
-- 0 FLAG_NO,
 cl.wearernumber, cl.fullname wearername, cl.searchname wearersearchname,
 cg.customernumber, cg.name customername, ch.departmentnumber, ch.description departmentdesc, cdd.day_id,
 ci.street customeraddres
, cast(CONCATENATEWITHBLANK(ci.zipcode, ci.city) as varchar2(255)) customeraddres2,
 cast (case
   when f1.flag_id is null then null
   else h.flagstartdate
   end as date) wearerflagdate,
 cast (case
   when f2.flag_id is null then null
   else f.flagstartdate
   end as date) wearerempflagdate,
 uf.uniqueitemflagdate,
 (select rc.code
  from reasoncode rc, uniqueitemfixedinfo uifi
  where rc.reasoncode_id = uifi.reasoncode_id and uifi.uniqueitem_id = b.uniqueitem_id) reason_code,
 GETDATEDIFF(GETCURRENTDATE(), B.LASTINSCANDATE) MAXCOMPLETENESSDAYS
-- h.flagstartdate wearerflagdate, f.flagstartdate wearerempflagdate, uf.uniqueitemflagdate
from stay c, 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
   left outer join finishingmethod j on (b.finishingmethod_id = j.finishingmethod_id)
   left outer join vr_uniqueitemflag uf on uf.uniqueitem_id = b.uniqueitem_id,
 status st,
 product ce, customer cg, department ch, address ci, languages, sizedefinition ck, wearer cl,
 customerdeliveryday cdd
where b.poolitem = 2
 and b.stay_id = c.stay_id
 and c.staytype = 1
 and b.uniqueitem_id = e.uniqueitem_id
 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.sizedefinition_id = ck.sizedefinition_id
 and f.wearer_id = cl.wearer_id
 and cg.customer_id = cdd.customer_id
 and (cdd.deliverytype = 'B' or cdd.deliverytype = 'D')
 and cdd.typeofmerchadise = 2
 and c.staynr not in (22,23,24,25,37)

/
create or replace view VR_COMPLETENESSROUTEDETAILS
 (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, CUSTOMERADDRES, CUSTOMERADDRES2, ROUTE_ID, DAY_ID, MAXCOMPLETENESSDAYS, INTERNALBU, DRIVINGDATE, COMPCHECKNONUNIQUE
, NONUNIQUEQTY, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT_DESC)
as select /*VR_COMPLETENESSROUTEDETAILS version 1.0,extra union split for packingnote*/
--unique items inscans
1 linetype, rp.reportparam_id, b.businessunit_id businessunit_id,
 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 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 = 10 and st.code = '30' THEN 6
 END "STAY",
 b.primaryid idcode, b.uniqueitem_id,
 languages.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, re.code productcode,
(SELECT description FROM product_DESC w WHERE w.product_id = re.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 ro.routenumber, ro.description routedesc,
 (SELECT description FROM finishingmethod_DESC y,finishingmethod j WHERE y.finishingmethod_id = j.finishingmethod_id
  AND b.finishingmethod_id = j.finishingmethod_id and y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddesc,
 rk.code sizedefinitioncode,
 coalesce((SELECT max(fl.flag_id) FROM UNIQUEITEMFLAG Z, flag fl WHERE Z.UNIQUEITEM_ID = b.UNIQUEITEM_ID
   and z.flag_id = fl.flag_id and fl.includeincompletnesscheck = 'Y'),0) FLAG,
 0 FLAG_NO ,
 h.wearernumber, h.fullname wearername, rg.customernumber, rg.name customername, rh.departmentnumber, rh.description departmentdesc,
 ri.street customeraddres
, cast(CONCATENATEWITHBLANK(ri.zipcode, ri.city) as varchar2(255)) customeraddres2,
 ro.route_id, ro.drivingday_id day_id,
 GETDATEDIFF(GETCURRENTDATE(), B.LASTINSCANDATE) MAXCOMPLETENESSDAYS, coalesce((select ca.internalprocessingbu_id from customeractivities ca, productgroup pg
 where ca.customer_id=rg.customer_id and re.productgroup_id=pg.productgroup_id
 and pg.activity_id=ca.activity_id and b.businessunit_id=ca.processbusinessunit_id) ,-1)internalBu ,rc.drivingdate,
 cast(sst.value as Varchar2(1)) COMPCHECKNONUNIQUE
 , 1 NonUniqueQty
 , g.distributionpointnumber, g.description distributionpoint_desc
from stay c, 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
   inner join businessunit bu
         left outer join systemsetting sst on sst.plant_id = bu.plant_id and sst.name = 'COMPCHECKNONUNIQUE'
   on bu.businessunit_id = b.businessunit_id,status st,
 product re, customer rg, department rh, address ri, languages, sizedefinition rk, route ro, routecontrol rc
 ,STOP LEFT OUTER JOIN DELIVERYPOINT ON STOP.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  LEFT outer JOIN ROUTESTOP ON STOP.ROUTESTOP_ID = ROUTESTOP.ROUTESTOP_ID,
  reportparam rp
where b.poolitem = 2
 and b.stay_id = c.stay_id
 and c.staytype = 1
 and b.uniqueitem_id = e.uniqueitem_id
 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 = re.product_id
 and b.sizedefinition_id=rk.sizedefinition_id
 and h.customer_id = rg.customer_id
 and g.department_id = rh.department_id
 and rg.visitaddress_id = ri.address_id
 and (b.planneddeliverydate <= rc.drivingdate or c.staynr = 36)
 and ro.active = 'Y'
 and c.staynr not in (20,22,23,24,25)
 and ( f1.flag_id is null or h.flagstartdate > rc.drivingdate)
 and ( f2.flag_id is null or f.flagstartdate > rc.drivingdate)
 and not exists ( select 1 from vr_uniqueitemflag uf where  uf.uniqueitem_id = b.uniqueitem_id and uf.uniqueitemflagdate < rp.date_value1)
 and (( rp.number_value2 = 1 and c.staynr <>'37') or rp.number_value2 = 0)
    and STOP.CUSTOMER_LINK_ID = rg.CUSTOMER_ID
  and (nvl(STOP.DELIVERYPOINT_ID, 0) = 0 OR
         (( select locker.DELIVERYPOINT_ID from locker where locker.locker_id = f.locker_id)  = STOP.DELIVERYPOINT_ID) OR
        f.DELIVERYPOINT_ID = STOP.DELIVERYPOINT_ID)
   AND STOP.ROUTECONTROL_ID = rc.routecontrol_id
   and stop.customer_link_id=h.customer_id
   and rc.route_id=ro.route_id
   AND STOP.STATUS IN (0, 3)
   and (( exists (select 1 from customerdeliveryday cdd where cdd.customer_id=rg.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 customerdeliveryday cdd where cdd.customer_id=rg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
                  and cdd.day_id=ro.drivingday_id))
        or (exists (select 1 from routecontrol rc, stop   where stop.customer_link_id=rg.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))))
--    and rp.number_value=rc.routecontrol_id
 and ro.routenumber >= rp.number_value8 and ro.routenumber <= rp.number_value9
    and rp.date_value1=rc.originaldrivingdate
union all --unique items outscans, NVL(ds.PACKINGNOTE_ID,0) =0
 select 2 linetype,
 rp.reportparam_id,ds.businessunit_id businessunit_id,
  7 "STAY", b.primaryid idcode,b.uniqueitem_id,
 languages.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, re.code productcode,
 (SELECT description FROM product_DESC w WHERE w.product_id = re.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 ro.routenumber, ro.description routedesc,
 (SELECT description FROM finishingmethod_DESC y WHERE y.finishingmethod_id = j.finishingmethod_id
  AND y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddesc,
  rk.code sizedefinitioncode,
 coalesce((SELECT max(fl.flag_id) FROM UNIQUEITEMFLAG Z, flag fl WHERE Z.UNIQUEITEM_ID = b.UNIQUEITEM_ID
   and z.flag_id = fl.flag_id and fl.includeincompletnesscheck = 'Y'),0) FLAG,
 0 FLAG_NO,
 h.wearernumber, h.fullname wearername, rg.customernumber, rg.name customername, rh.departmentnumber, rh.description departmentdesc,
 ri.street customeraddres
, cast(CONCATENATEWITHBLANK(ri.zipcode, ri.city) as varchar2(255)) customeraddres2,
 ro.route_id, ro.drivingday_id day_id,
 0 MAXCOMPLETENESSDAYS, coalesce(ds.internalprocessingbu_id ,-1)internalBu, rc.drivingdate,
 cast(sst.value as Varchar2(1)) COMPCHECKNONUNIQUE
 , 1 NonUniqueQty
 , g.distributionpointnumber, g.description distributionpoint_desc
from uniqueitem b
   inner join businessunit bu
         left outer join systemsetting sst on sst.plant_id = bu.plant_id and sst.name = 'COMPCHECKNONUNIQUE'
   on bu.businessunit_id = b.businessunit_id, distributionpoint g ,
  product re, department rh, address ri, languages, customer rg,sizedefinition rk,finishingmethod j, route ro,routecontrol rc
 , deliveryscan ds  left outer join  weareremployment f on  ds.weareremployment_link_id=f.weareremployment_id
                left outer join wearer h on f.wearer_id = h.wearer_id
 ,routecontrol rc1,STOP
  LEFT OUTER JOIN DELIVERYPOINT ON STOP.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  LEFT outer JOIN ROUTESTOP ON STOP.ROUTESTOP_ID = ROUTESTOP.ROUTESTOP_ID,
  reportparam rp
where  b.stay_id = (select c.stay_id from stay c where  c.staytype = 1 and c.staynr = 20)
 and (f.distributionpoint_id = g.distributionpoint_id or (h.customer_id is null and b.poolitem<> 2))
 and b.status_id in ( select st.status_id from status st  where st.statustype='UI' and (st.code = '20' or st.code = '30'))
 and b.product_id = re.product_id
 and b.finishingmethod_id = j.finishingmethod_id
 and b.sizedefinition_id = rk.sizedefinition_id
 and (h.customer_id = rg.customer_id or( h.customer_id is null and b.poolitem<> 2))
 and g.department_id = rh.department_id
 and rg.visitaddress_id = ri.address_id
 and ro.active = 'Y'
 and ds.uniqueitem_link_id = b.uniqueitem_id
 and ds.businessunit_id = b.businessunit_id
 and ds.distributionpoint_link_id=g.distributionpoint_id
 and rc1.routecontrol_id = ds.routecontrol_id
 and  ( nvl( f.deliverypoint_id,0)=0 or ds.deliverypoint_link_id=f.deliverypoint_id or (h.customer_id is null and b.poolitem<> 2 and g.deliverypoint_id=ds.deliverypoint_link_id))
 and ds.customer_link_id=rg.customer_id
 and rc1.drivingdate<=rc.drivingdate
 and rc.route_id=ro.route_id
 and NVL(ds.PACKINGNOTE_ID,0) =0
 and STOP.CUSTOMER_LINK_ID = rg.CUSTOMER_ID
  and (nvl(STOP.DELIVERYPOINT_ID, 0) = 0 OR
         (( select locker.DELIVERYPOINT_ID from locker where locker.locker_id = f.locker_id)  = STOP.DELIVERYPOINT_ID) OR
        f.DELIVERYPOINT_ID = STOP.DELIVERYPOINT_ID or  (h.customer_id is null and b.poolitem<> 2 and STOP.DELIVERYPOINT_ID=ds.deliverypoint_link_id))
 and STOP.ROUTECONTROL_ID = rc.routecontrol_id
 and stop.customer_link_id=rg.customer_id
 and rc.route_id=ro.route_id
 and STOP.STATUS IN (0, 3)
 and (( exists (select 1 from customerdeliveryday cdd where cdd.customer_id=rg.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 customerdeliveryday cdd where cdd.customer_id=rg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
                  and cdd.day_id=ro.drivingday_id))
        or (exists (select 1 from routecontrol rc, stop   where stop.customer_link_id=rg.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))))
 and ds.outscannodelivery in (0,2 )
-- and rp.number_value=rc.routecontrol_id
 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 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 --unique items outscans, NVL(ds.PACKINGNOTE_ID,0) =packingnote_id in progress
 select 2 linetype,
 rp.reportparam_id,ds.businessunit_id businessunit_id,
  7 "STAY", b.primaryid idcode,b.uniqueitem_id,
 languages.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, re.code productcode,
 (SELECT description FROM product_DESC w WHERE w.product_id = re.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 ro.routenumber, ro.description routedesc,
 (SELECT description FROM finishingmethod_DESC y WHERE y.finishingmethod_id = j.finishingmethod_id
  AND y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddesc,
  rk.code sizedefinitioncode,
 coalesce((SELECT max(fl.flag_id) FROM UNIQUEITEMFLAG Z, flag fl WHERE Z.UNIQUEITEM_ID = b.UNIQUEITEM_ID
   and z.flag_id = fl.flag_id and fl.includeincompletnesscheck = 'Y'),0) FLAG,
 0 FLAG_NO,
 h.wearernumber, h.fullname wearername, rg.customernumber, rg.name customername, rh.departmentnumber, rh.description departmentdesc,
 ri.street customeraddres
, cast(CONCATENATEWITHBLANK(ri.zipcode, ri.city) as varchar2(255)) customeraddres2,
 ro.route_id, ro.drivingday_id day_id,
 0 MAXCOMPLETENESSDAYS, coalesce(ds.internalprocessingbu_id ,-1)internalBu, rc.drivingdate,
 cast(sst.value as Varchar2(1)) COMPCHECKNONUNIQUE
 , 1 NonUniqueQty
 , g.distributionpointnumber, g.description distributionpoint_desc
from uniqueitem b
   inner join businessunit bu
         left outer join systemsetting sst on sst.plant_id = bu.plant_id and sst.name = 'COMPCHECKNONUNIQUE'
   on bu.businessunit_id = b.businessunit_id, distributionpoint g ,
  product re, department rh, address ri, languages, customer rg,sizedefinition rk,finishingmethod j, route ro,routecontrol rc
 , deliveryscan ds  left outer join  weareremployment f on  ds.weareremployment_link_id=f.weareremployment_id
                left outer join wearer h on f.wearer_id = h.wearer_id
 ,routecontrol rc1,STOP
  LEFT OUTER JOIN DELIVERYPOINT ON STOP.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  LEFT outer JOIN ROUTESTOP ON STOP.ROUTESTOP_ID = ROUTESTOP.ROUTESTOP_ID,
  reportparam rp
where  b.stay_id = (select c.stay_id from stay c where  c.staytype = 1 and c.staynr = 20)
 and (f.distributionpoint_id = g.distributionpoint_id or (h.customer_id is null and b.poolitem<> 2))
 and b.status_id in ( select st.status_id from status st  where st.statustype='UI' and (st.code = '20' or st.code = '30'))
 and b.product_id = re.product_id
 and b.finishingmethod_id = j.finishingmethod_id
 and b.sizedefinition_id = rk.sizedefinition_id
 and (h.customer_id = rg.customer_id or( h.customer_id is null and b.poolitem<> 2))
 and g.department_id = rh.department_id
 and rg.visitaddress_id = ri.address_id
 and ro.active = 'Y'
 and ds.uniqueitem_link_id = b.uniqueitem_id
 and ds.businessunit_id = b.businessunit_id
 and ds.distributionpoint_link_id=g.distributionpoint_id
 and rc1.routecontrol_id = ds.routecontrol_id
 and  ( nvl( f.deliverypoint_id,0)=0 or ds.deliverypoint_link_id=f.deliverypoint_id or (h.customer_id is null and b.poolitem<> 2 and g.deliverypoint_id=ds.deliverypoint_link_id))
 and ds.customer_link_id=rg.customer_id
 and rc1.drivingdate<=rc.drivingdate
 and rc.route_id=ro.route_id
 and NVL(ds.PACKINGNOTE_ID,0) in ( select pn.packingnote_id  from packingnote pn, status s
                                 where  pn.routecontrol_id=rc.routecontrol_id
                                 and pn.status_id=s.status_id and s.statustype='PN' and s.code ='20')
 and STOP.CUSTOMER_LINK_ID = rg.CUSTOMER_ID
  and (nvl(STOP.DELIVERYPOINT_ID, 0) = 0 OR
         (( select locker.DELIVERYPOINT_ID from locker where locker.locker_id = f.locker_id)  = STOP.DELIVERYPOINT_ID) OR
        f.DELIVERYPOINT_ID = STOP.DELIVERYPOINT_ID or  (h.customer_id is null and b.poolitem<> 2 and STOP.DELIVERYPOINT_ID=ds.deliverypoint_link_id))
 and STOP.ROUTECONTROL_ID = rc.routecontrol_id
 and stop.customer_link_id=rg.customer_id
 and rc.route_id=ro.route_id
 and STOP.STATUS IN (0, 3)
 and (( exists (select 1 from customerdeliveryday cdd where cdd.customer_id=rg.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 customerdeliveryday cdd where cdd.customer_id=rg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
                  and cdd.day_id=ro.drivingday_id))
        or (exists (select 1 from routecontrol rc, stop   where stop.customer_link_id=rg.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))))
 and ds.outscannodelivery in (0,2 )
-- and rp.number_value=rc.routecontrol_id
 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 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 --NonUnique items in scans
select 3 linetype, rp.reportparam_id, bu.businessunit_id,
 1 "STAY",
 '' idcode, 0 uniqueitem_id,
 languages.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, re.code productcode,
(SELECT description FROM product_DESC w WHERE w.product_id = re.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 ro.routenumber, ro.description routedesc,
 (SELECT y.description FROM finishingmethod_DESC y WHERE y.finishingmethod_id = j.finishingmethod_id
  and y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddesc,
 rk.code sizedefinitioncode,
 0 FLAG,
 0 FLAG_NO ,
 -1 wearernumber, '' wearername, rg.customernumber, rg.name customername, rh.departmentnumber, rh.description departmentdesc,
 ri.street customeraddres
, cast(CONCATENATEWITHBLANK(ri.zipcode, ri.city) as varchar2(255)) customeraddres2,
 ro.route_id, ro.drivingday_id day_id,
 0 MAXCOMPLETENESSDAYS, coalesce((select ca.internalprocessingbu_id from customeractivities ca, productgroup pg
 where ca.customer_id=rg.customer_id and re.productgroup_id=pg.productgroup_id
 and pg.activity_id=ca.activity_id and bu.businessunit_id=ca.processbusinessunit_id) ,-1)internalBu ,rc.drivingdate,
 cast(sst.value as Varchar2(1)) COMPCHECKNONUNIQUE
 , dv.amount NonUniqueQty
 , g.distributionpointnumber, g.description distributionpoint_desc
from DeliveryVariations dv,
 distributionpoint g,
 product re, customer rg, department rh, address ri, languages, sizedefinition rk,finishingmethod j, route ro, routecontrol rc
 ,STOP LEFT OUTER JOIN DELIVERYPOINT ON STOP.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  LEFT outer JOIN ROUTESTOP ON STOP.ROUTESTOP_ID = ROUTESTOP.ROUTESTOP_ID,
  reportparam rp,businessunit bu
         left outer join systemsetting sst on sst.plant_id = bu.plant_id and sst.name = 'COMPCHECKNONUNIQUE'
where dv.distributionpoint_id = g.distributionpoint_id
 and dv.product_id = re.product_id
 and dv.sizedefinition_id=rk.sizedefinition_id
 and g.department_id = rh.department_id
 and rh.customer_id = rg.customer_id
 and rg.visitaddress_id = ri.address_id
 and ro.active = 'Y'
 and STOP.CUSTOMER_LINK_ID = rg.CUSTOMER_ID
   AND STOP.ROUTECONTROL_ID = rc.routecontrol_id
   and rc.route_id=ro.route_id
   AND STOP.STATUS IN (0, 3)
   and (( exists (select 1 from customerdeliveryday cdd where cdd.customer_id=rg.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 customerdeliveryday cdd where cdd.customer_id=rg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
                  and cdd.day_id=ro.drivingday_id))
        or (exists (select 1 from routecontrol rc, stop   where stop.customer_link_id=rg.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))))
--    and rp.number_value=rc.routecontrol_id
 and ro.routenumber >= rp.number_value8 and ro.routenumber <= rp.number_value9
    and rp.date_value1=rc.originaldrivingdate
    and dv.distributionpoint_id = g.distributionpoint_id and dv.product_id = re.product_id and dv.sizedefinition_id =rk.sizedefinition_id
      and dv.finishingmethod_id = j.finishingmethod_id
      and (dv.packingnote_id is null or exists (select 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
          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, bu.businessunit_id,
  7 "STAY", '' idcode, 0 uniqueitem_id,
 languages.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, re.code productcode,
 (SELECT description FROM product_DESC w WHERE w.product_id = re.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 ro.routenumber, ro.description routedesc,
 (SELECT description FROM finishingmethod_DESC y WHERE y.finishingmethod_id = j.finishingmethod_id
  AND y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddesc,
  rk.code sizedefinitioncode,
 0 FLAG,
 0 FLAG_NO,
 -1 wearernumber, '' wearername, rg.customernumber, rg.name customername, rh.departmentnumber, rh.description departmentdesc,
 ri.street customeraddres
, cast(CONCATENATEWITHBLANK(ri.zipcode, ri.city) as varchar2(255)) customeraddres2,
 ro.route_id, ro.drivingday_id day_id,
 0 MAXCOMPLETENESSDAYS, coalesce((select ca.internalprocessingBu_id from customeractivities ca, productgroup pg
 where ca.customer_id=rg.customer_id and re.productgroup_id=pg.productgroup_id
 and pg.activity_id=ca.activity_id and bu.businessunit_id=ca.processbusinessunit_id) ,-1) internalBu, rc.drivingdate,
 cast(sst.value as Varchar2(1)) COMPCHECKNONUNIQUE
 , (ccd.quantity+ccd.quantitycog) NonUniqueQty
 , g.distributionpointnumber, g.description distributionpoint_desc
from businessunit bu
         left outer join systemsetting sst on sst.plant_id = bu.plant_id and sst.name = 'COMPCHECKNONUNIQUE'
 , distributionpoint g, product re, department rh, address ri, languages, customer rg,sizedefinition rk,finishingmethod j, route ro,routecontrol rc
 , routecontrol rc1, STOP
  LEFT OUTER JOIN DELIVERYPOINT ON STOP.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  LEFT outer JOIN ROUTESTOP ON STOP.ROUTESTOP_ID = ROUTESTOP.ROUTESTOP_ID,
  reportparam rp, Cleancountdelivery ccd
where  ccd.distributionpoint_id = g.distributionpoint_id
 and ccd.product_id = re.product_id
 and ccd.finishingmethod_id = j.finishingmethod_id
 and ccd.sizedefinition_id = rk.sizedefinition_id
 and g.department_id = rh.department_id
 and rh.customer_id = rg.customer_id
 and rg.visitaddress_id = ri.address_id
 and ro.active = 'Y'
 and rc1.drivingdate<=rc.drivingdate
 and rc.route_id=ro.route_id
 and STOP.CUSTOMER_LINK_ID = rg.CUSTOMER_ID
 and STOP.ROUTECONTROL_ID = rc.routecontrol_id
 and rc.route_id=ro.route_id
 and STOP.STATUS IN (0, 3)
 and (( exists (select 1 from customerdeliveryday cdd where cdd.customer_id=rg.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 customerdeliveryday cdd where cdd.customer_id=rg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
                  and cdd.day_id=ro.drivingday_id))
        or (exists (select 1 from routecontrol rc, stop   where stop.customer_link_id=rg.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))))
-- and rp.number_value=rc.routecontrol_id
 and ro.routenumber >= rp.number_value8 and ro.routenumber <= rp.number_value9
 and rp.date_value1=rc.drivingdate
 and (ccd.packingnote_id is null or exists (select 1 from packingnote pn, status stat where ccd.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
          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_COMPLETENESSROUTEDET_PCO
 (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, CUSTOMERADDRES, CUSTOMERADDRES2, ROUTE_ID, DAY_ID, MAXCOMPLETENESSDAYS, INTERNALBU, DRIVINGDATE, COMPCHECKNONUNIQUE
, NONUNIQUEQTY, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT_DESC)
as select --unique items inscans
1 linetype, rp.reportparam_id, b.businessunit_id businessunit_id,
 /*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 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 = 10 and st.code = '30' THEN 6
 END*/1 "STAY",
 b.primaryid idcode, b.uniqueitem_id,
 languages.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, re.code productcode,
(SELECT description FROM product_DESC w WHERE w.product_id = re.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 ro.routenumber, ro.description routedesc,
 (SELECT description FROM finishingmethod_DESC y,finishingmethod j WHERE y.finishingmethod_id = j.finishingmethod_id
  AND b.finishingmethod_id = j.finishingmethod_id and y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddesc,
 rk.code sizedefinitioncode,
 coalesce((SELECT max(fl.flag_id) FROM UNIQUEITEMFLAG Z, flag fl WHERE Z.UNIQUEITEM_ID = b.UNIQUEITEM_ID
   and z.flag_id = fl.flag_id and fl.includeincompletnesscheck = 'Y'),0) FLAG,
 0 FLAG_NO ,
 h.wearernumber, h.fullname wearername, rg.customernumber, rg.name customername, rh.departmentnumber, rh.description departmentdesc,
 ri.street customeraddres
, cast(CONCATENATEWITHBLANK(ri.zipcode, ri.city) as varchar2(255)) customeraddres2,
 ro.route_id, ro.drivingday_id day_id,
 GETDATEDIFF(GETCURRENTDATE(), B.LASTINSCANDATE) MAXCOMPLETENESSDAYS, coalesce((select ca.internalprocessingbu_id from customeractivities ca, productgroup pg
 where ca.customer_id=rg.customer_id and re.productgroup_id=pg.productgroup_id
 and pg.activity_id=ca.activity_id and b.businessunit_id=ca.processbusinessunit_id) ,-1)internalBu ,rc.drivingdate,
 cast(sst.value as Varchar2(1)) COMPCHECKNONUNIQUE
 , 1 NonUniqueQty
 , g.distributionpointnumber, g.description distributionpoint_desc
from stay c, 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
   inner join businessunit bu
         left outer join systemsetting sst on sst.plant_id = bu.plant_id and sst.name = 'COMPCHECKNONUNIQUE'
   on bu.businessunit_id = b.businessunit_id,status st,
 product re, customer rg, department rh, address ri, languages, sizedefinition rk, route ro, routecontrol rc
 ,STOP LEFT OUTER JOIN DELIVERYPOINT ON STOP.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  LEFT outer JOIN ROUTESTOP ON STOP.ROUTESTOP_ID = ROUTESTOP.ROUTESTOP_ID,
  reportparam rp
where b.poolitem = 2
 and b.stay_id = c.stay_id
 and c.staytype = 1
 and b.uniqueitem_id = e.uniqueitem_id
 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 = re.product_id
 and b.sizedefinition_id=rk.sizedefinition_id
 and h.customer_id = rg.customer_id
 and g.department_id = rh.department_id
 and rg.visitaddress_id = ri.address_id
 and (b.planneddeliverydate <= rc.drivingdate or c.staynr = 36)
 and ro.active = 'Y'
 and c.staynr not in (20,22,23,24,25)
 and ( f1.flag_id is null or h.flagstartdate > rc.drivingdate)
 and ( f2.flag_id is null or f.flagstartdate > rc.drivingdate)
 and not exists ( select 1 from vr_uniqueitemflag uf where  uf.uniqueitem_id = b.uniqueitem_id and uf.uniqueitemflagdate < rp.date_value1)
 and (( rp.number_value2 = 1 and c.staynr <>'37') or rp.number_value2 = 0)
    and STOP.CUSTOMER_LINK_ID = rg.CUSTOMER_ID
  and (nvl(STOP.DELIVERYPOINT_ID, 0) = 0 OR
         (( select locker.DELIVERYPOINT_ID from locker where locker.locker_id = f.locker_id)  = STOP.DELIVERYPOINT_ID) OR
        f.DELIVERYPOINT_ID = STOP.DELIVERYPOINT_ID)
   AND STOP.ROUTECONTROL_ID = rc.routecontrol_id
   and stop.customer_link_id=h.customer_id
   and rc.route_id=ro.route_id
   AND STOP.STATUS IN (0, 3)
   and (( exists (select 1 from customerdeliveryday cdd where cdd.customer_id=rg.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 customerdeliveryday cdd where cdd.customer_id=rg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
                  and cdd.day_id=ro.drivingday_id))
        or (exists (select 1 from routecontrol rc, stop   where stop.customer_link_id=rg.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))))
    and rp.number_value=rc.routecontrol_id
    and rp.date_value1=rc.originaldrivingdate
    and c.staynr = 30 and (st.code = '20' or st.code = '30')
    and re.typeofmerchandise = 2--20308 - rework to exclude non-garments
    /*
union all --unique items outscans
 select 2 linetype,
 rp.reportparam_id,ds.businessunit_id businessunit_id,
  7 "STAY", b.primaryid idcode,b.uniqueitem_id,
 languages.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, re.code productcode,
 (SELECT description FROM product_DESC w WHERE w.product_id = re.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 ro.routenumber, ro.description routedesc,
 (SELECT description FROM finishingmethod_DESC y WHERE y.finishingmethod_id = j.finishingmethod_id
  AND y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddesc,
  rk.code sizedefinitioncode,
 coalesce((SELECT max(fl.flag_id) FROM UNIQUEITEMFLAG Z, flag fl WHERE Z.UNIQUEITEM_ID = b.UNIQUEITEM_ID
   and z.flag_id = fl.flag_id and fl.includeincompletnesscheck = 'Y'),0) FLAG,
 0 FLAG_NO,
 h.wearernumber, h.fullname wearername, rg.customernumber, rg.name customername, rh.departmentnumber, rh.description departmentdesc,
 ri.street customeraddres
, cast(CONCATENATEWITHBLANK(ri.zipcode, ri.city) as varchar2(255)) customeraddres2,
 ro.route_id, ro.drivingday_id day_id,
 0 MAXCOMPLETENESSDAYS, coalesce(ds.internalprocessingbu_id ,-1)internalBu, rc.drivingdate,
 cast(sst.value as Varchar2(1)) COMPCHECKNONUNIQUE
 , 1 NonUniqueQty
 , g.distributionpointnumber, g.description distributionpoint_desc
from uniqueitem b
   inner join businessunit bu
         left outer join systemsetting sst on sst.plant_id = bu.plant_id and sst.name = 'COMPCHECKNONUNIQUE'
   on bu.businessunit_id = b.businessunit_id, weareremployment f,
 distributionpoint g ,  wearer h,
  product re, department rh, address ri, languages, customer rg,sizedefinition rk,finishingmethod j, route ro,routecontrol rc
 , deliveryscan ds,routecontrol rc1,STOP
  LEFT OUTER JOIN DELIVERYPOINT ON STOP.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  LEFT outer JOIN ROUTESTOP ON STOP.ROUTESTOP_ID = ROUTESTOP.ROUTESTOP_ID,
  reportparam rp
where b.poolitem = 2
 and b.stay_id = (select c.stay_id from stay c where  c.staytype = 1 and c.staynr = 20)
 and f.distributionpoint_id = g.distributionpoint_id
 and f.wearer_id = h.wearer_id
 and b.status_id in ( select st.status_id from status st  where st.statustype='UI' and (st.code = '20' or st.code = '30'))
 and b.product_id = re.product_id
 and b.finishingmethod_id = j.finishingmethod_id
 and b.sizedefinition_id = rk.sizedefinition_id
 and h.customer_id = rg.customer_id
 and g.department_id = rh.department_id
 and rg.visitaddress_id = ri.address_id
 and ro.active = 'Y'
 and ds.uniqueitem_link_id = b.uniqueitem_id
 and ds.businessunit_id = b.businessunit_id
 and ds.distributionpoint_link_id=g.distributionpoint_id
 and ds.weareremployment_link_id=f.weareremployment_id
 and rc1.routecontrol_id = ds.routecontrol_id
 and ds.customer_link_id=rg.customer_id
 and rc1.drivingdate<=rc.drivingdate
 and rc.route_id=ro.route_id
 and (ds.packingnote_id is null
           or (ds.packingnote_id is not null and (( select s.code from packingnote pn, status s
               where pn.packingnote_id=ds.packingnote_id  and pn.routecontrol_id = rc.routecontrol_id
               and pn.status_id=s.status_id and s.statustype='PN') ='20')) )
 and STOP.CUSTOMER_LINK_ID = rg.CUSTOMER_ID
 and (nvl(STOP.DELIVERYPOINT_ID, 0) = 0 OR
         (( select locker.DELIVERYPOINT_ID from locker where locker.locker_id = f.locker_id)  = STOP.DELIVERYPOINT_ID) OR
        f.DELIVERYPOINT_ID = STOP.DELIVERYPOINT_ID)
 and STOP.ROUTECONTROL_ID = rc.routecontrol_id
 and stop.customer_link_id=h.customer_id
 and rc.route_id=ro.route_id
 and STOP.STATUS IN (0, 3)
 and (( exists (select 1 from customerdeliveryday cdd where cdd.customer_id=rg.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 customerdeliveryday cdd where cdd.customer_id=rg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
                  and cdd.day_id=ro.drivingday_id))
        or (exists (select 1 from routecontrol rc, stop   where stop.customer_link_id=rg.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))))
 and ds.outscannodelivery in (0,2 )
 and rp.number_value=rc.routecontrol_id
 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 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 --NonUnique items in scans
select 3 linetype, rp.reportparam_id, bu.businessunit_id,
 1 "STAY",
 '' idcode, 0 uniqueitem_id,
 languages.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, re.code productcode,
(SELECT description FROM product_DESC w WHERE w.product_id = re.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 ro.routenumber, ro.description routedesc,
 (SELECT y.description FROM finishingmethod_DESC y WHERE y.finishingmethod_id = j.finishingmethod_id
  and y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddesc,
 rk.code sizedefinitioncode,
 0 FLAG,
 0 FLAG_NO ,
 -1 wearernumber, '' wearername, rg.customernumber, rg.name customername, rh.departmentnumber, rh.description departmentdesc,
 ri.street customeraddres
, cast(CONCATENATEWITHBLANK(ri.zipcode, ri.city) as varchar2(255)) customeraddres2,
 ro.route_id, ro.drivingday_id day_id,
 0 MAXCOMPLETENESSDAYS, coalesce((select ca.internalprocessingbu_id from customeractivities ca, productgroup pg
 where ca.customer_id=rg.customer_id and re.productgroup_id=pg.productgroup_id
 and pg.activity_id=ca.activity_id and bu.businessunit_id=ca.processbusinessunit_id) ,-1)internalBu ,rc.drivingdate,
 cast(sst.value as Varchar2(1)) COMPCHECKNONUNIQUE
 , dv.amount NonUniqueQty
 , g.distributionpointnumber, g.description distributionpoint_desc
from DeliveryVariations dv,
 distributionpoint g,
 product re, customer rg, department rh, address ri, languages, sizedefinition rk,finishingmethod j, route ro, routecontrol rc
 ,STOP LEFT OUTER JOIN DELIVERYPOINT ON STOP.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  LEFT outer JOIN ROUTESTOP ON STOP.ROUTESTOP_ID = ROUTESTOP.ROUTESTOP_ID,
  reportparam rp,businessunit bu
         left outer join systemsetting sst on sst.plant_id = bu.plant_id and sst.name = 'COMPCHECKNONUNIQUE'
where dv.distributionpoint_id = g.distributionpoint_id
 and dv.product_id = re.product_id
 and dv.sizedefinition_id=rk.sizedefinition_id
 and g.department_id = rh.department_id
 and rh.customer_id = rg.customer_id
 and rg.visitaddress_id = ri.address_id
 and ro.active = 'Y'
 and STOP.CUSTOMER_LINK_ID = rg.CUSTOMER_ID
   AND STOP.ROUTECONTROL_ID = rc.routecontrol_id
   and rc.route_id=ro.route_id
   AND STOP.STATUS IN (0, 3)
   and (( exists (select 1 from customerdeliveryday cdd where cdd.customer_id=rg.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 customerdeliveryday cdd where cdd.customer_id=rg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
                  and cdd.day_id=ro.drivingday_id))
        or (exists (select 1 from routecontrol rc, stop   where stop.customer_link_id=rg.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))))
    and rp.number_value=rc.routecontrol_id
    and rp.date_value1=rc.originaldrivingdate
    and dv.distributionpoint_id = g.distributionpoint_id and dv.product_id = re.product_id and dv.sizedefinition_id =rk.sizedefinition_id
      and dv.finishingmethod_id = j.finishingmethod_id
      and (dv.packingnote_id is null or exists (select 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
          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
    and re.typeofmerchandise = 2--20308 - rework to exclude non-garments
    /*
union all --Non Unique items outscans
 select 4 linetype,
 rp.reportparam_id, bu.businessunit_id,
  7 "STAY", '' idcode, 0 uniqueitem_id,
 languages.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, re.code productcode,
 (SELECT description FROM product_DESC w WHERE w.product_id = re.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 ro.routenumber, ro.description routedesc,
 (SELECT description FROM finishingmethod_DESC y WHERE y.finishingmethod_id = j.finishingmethod_id
  AND y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddesc,
  rk.code sizedefinitioncode,
 0 FLAG,
 0 FLAG_NO,
 -1 wearernumber, '' wearername, rg.customernumber, rg.name customername, rh.departmentnumber, rh.description departmentdesc,
 ri.street customeraddres
, cast(CONCATENATEWITHBLANK(ri.zipcode, ri.city) as varchar2(255)) customeraddres2,
 ro.route_id, ro.drivingday_id day_id,
 0 MAXCOMPLETENESSDAYS, coalesce((select ca.internalprocessingBu_id from customeractivities ca, productgroup pg
 where ca.customer_id=rg.customer_id and re.productgroup_id=pg.productgroup_id
 and pg.activity_id=ca.activity_id and bu.businessunit_id=ca.processbusinessunit_id) ,-1) internalBu, rc.drivingdate,
 cast(sst.value as Varchar2(1)) COMPCHECKNONUNIQUE
 , ccd.quantity NonUniqueQty
 , g.distributionpointnumber, g.description distributionpoint_desc
from businessunit bu
         left outer join systemsetting sst on sst.plant_id = bu.plant_id and sst.name = 'COMPCHECKNONUNIQUE'
 , distributionpoint g, product re, department rh, address ri, languages, customer rg,sizedefinition rk,finishingmethod j, route ro,routecontrol rc
 , routecontrol rc1, STOP
  LEFT OUTER JOIN DELIVERYPOINT ON STOP.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  LEFT outer JOIN ROUTESTOP ON STOP.ROUTESTOP_ID = ROUTESTOP.ROUTESTOP_ID,
  reportparam rp, Cleancountdelivery ccd
where  ccd.distributionpoint_id = g.distributionpoint_id
 and ccd.product_id = re.product_id
 and ccd.finishingmethod_id = j.finishingmethod_id
 and ccd.sizedefinition_id = rk.sizedefinition_id
 and g.department_id = rh.department_id
 and rh.customer_id = rg.customer_id
 and rg.visitaddress_id = ri.address_id
 and ro.active = 'Y'
 and rc1.drivingdate<=rc.drivingdate
 and rc.route_id=ro.route_id
 and STOP.CUSTOMER_LINK_ID = rg.CUSTOMER_ID
 and STOP.ROUTECONTROL_ID = rc.routecontrol_id
 and rc.route_id=ro.route_id
 and STOP.STATUS IN (0, 3)
 and (( exists (select 1 from customerdeliveryday cdd where cdd.customer_id=rg.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 customerdeliveryday cdd where cdd.customer_id=rg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
                  and cdd.day_id=ro.drivingday_id))
        or (exists (select 1 from routecontrol rc, stop   where stop.customer_link_id=rg.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))))
 and rp.number_value=rc.routecontrol_id
 and rp.date_value1=rc.drivingdate
 and (ccd.packingnote_id is null or exists (select 1 from packingnote pn, status stat where ccd.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
          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_COMPLETENESSROUTEDET_STK
 (BUSINESSUNIT_ID, STAY, IDCODE, UNIQUEITEM_ID, LANGUAGECODE, PLANNEDDELIVERYDATE, 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, WEARERFLAGDATE, WEAREREMPFLAGDATE, UNIQUEITEMFLAGDATE, MAXCOMPLETENESSDAYS)
as select b.businessunit_id businessunit_id,
 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 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 = 10 and st.code = '30' THEN 6
 END "STAY",
 b.primaryid idcode, b.uniqueitem_id,
 languages.code languagecode,
-- b.planneddeliverydate,
 case
   when c.staynr = 36 then GETABSMINDATE()
   else b.planneddeliverydate
 end planneddeliverydate,
 to_char(b.lastinscandate, 'DD-MM-YYYY HH:MI:SS AM') lastinscandate,
 to_char(b.lastscandate, 'DD-MM-YYYY HH:MI:SS AM') lastscandate,
 --b.lastinscandate, b.lastscandate,
 b.status_id,
 re.code productcode,
 (SELECT description FROM product_DESC w WHERE w.product_id = re.product_id
  AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 ro.routenumber, ro.description routedesc,
 (SELECT description FROM finishingmethod_DESC y WHERE y.finishingmethod_id = j.finishingmethod_id
  AND y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) finishingmethoddesc,
 rk.code sizedefinitioncode,
 (SELECT COUNT(*) 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,
 rl.wearernumber, rl.fullname wearername,
 rg.customernumber, rg.name customername, rh.departmentnumber, rh.description departmentdesc,
 ri.street customeraddres
, cast(CONCATENATEWITHBLANK(ri.zipcode, ri.city) as varchar2(255)) customeraddres2,
 ro.route_id, ro.drivingday_id day_id,
 cast (case
   when f1.flag_id is null then null
   else h.flagstartdate
   end as date) wearerflagdate,
 cast (case
   when f2.flag_id is null then null
   else f.flagstartdate
   end as date) wearerempflagdate,
 uf.uniqueitemflagdate,
 GETDATEDIFF(GETCURRENTDATE(), B.LASTINSCANDATE) MAXCOMPLETENESSDAYS
-- h.flagstartdate wearerflagdate, f.flagstartdate wearerempflagdate, uf.uniqueitemflagdate
from stay c, 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
   left outer join finishingmethod j on (b.finishingmethod_id = j.finishingmethod_id)
   left outer join vr_uniqueitemflag uf on uf.uniqueitem_id = b.uniqueitem_id,
 status st,
 product re, customer rg, department rh, address ri, languages, sizedefinition rk, wearer rl,
 route ro, uniqueitemroute uir
where b.poolitem = 2
 and b.stay_id = c.stay_id
 and c.staytype = 1
 and b.uniqueitem_id = e.uniqueitem_id
 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 = re.product_id
 and rl.customer_id = rg.customer_id
 and g.department_id = rh.department_id
 and rg.visitaddress_id = ri.address_id
 and b.sizedefinition_id = rk.sizedefinition_id
 and f.wearer_id = rl.wearer_id
 and b.uniqueitem_id = uir.uniqueitem_id
 and uir.plannedoutroute_id = ro.route_id
 and ro.active = 'Y'
 and c.staynr not in (22,23,24,25)
 and (
 ((( select ss.value from systemsetting ss, businessunit bu where b.businessunit_id=bu.businessunit_id and bu.plant_id=ss.plant_id and
  ss.name='DEPOSITSTOCKINCC')=0) and c.staynr <>'37') or
  (( select ss.value from systemsetting ss, businessunit bu where b.businessunit_id=bu.businessunit_id and bu.plant_id=ss.plant_id and
  ss.name='DEPOSITSTOCKINCC')=1) )

/
create or replace view VR_SALESJOURNAL
 (SALESJOURNALCODE, SALESJOURNALDESC, PLANTCODE, PLANTNAME, BUSINESSUNITCODE, BUSINESSUNITDESC, PRCBUSINESSUNITCODE, PRCBUSINESSUNITDESC, DEPOTCODE, DEPOTDESC, ROUTENUMBER, ROUTEDESC, TURNOVERGROUPCODE, TURNOVERGROUPDESC, ARTRANSACTIONDATE, CASHAMOUNT, CHARGEAMOUNT, CURRENCYCODE, LANGUAGECODE, LANGUAGE_ID)
as select d.code salesjournalcode,
 (SELECT description FROM salesjournalgroup_desc x WHERE x.salesjournalgroup_id = a.salesjournalgroup_id
  AND x.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) salesjournaldesc,
 e.code plantcode, e.name plantname,
 b.code businessunitcode, b.description businessunitdesc,
 pb.code prcbusinessunitcode, pb.description prcbusinessunitdesc,
 w.code depotcode, w.description depotdesc,
 c.routenumber, c.description routedesc,
 f.code turnovergroupcode,
 (SELECT description FROM turnovergroup_desc y WHERE y.turnovergroup_id = a.turnovergroup_id
  AND y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) turnovergroupdesc,
 a.artransactiondate artransactiondate,
 a.cashamount, a.chargeamount, a.currencycode
, languages.code languagecode, languages.language_id
from VR_SALESJOURNALAMOUNT a
 left outer join (route c left outer join depot w on c.depot_id = w.depot_id)
   on c.route_id = a.route_id,
 businessunit b, businessunit pb, salesjournalgroup d, plant e, turnovergroup f, languages
where a.businessunit_id = b.businessunit_id
 and a.processbusinessunit_id = pb.businessunit_id
 and a.salesjournalgroup_id = d.salesjournalgroup_id
 and b.plant_id = e.plant_id
 and a.turnovergroup_id = f.turnovergroup_id

/
create or replace view VR_SALESJOURNAL_AUS
 (SALESJOURNALCODE, SALESJOURNALDESC, PLANTCODE, PLANTNAME, BUSINESSUNITCODE, BUSINESSUNITDESC, PRCBUSINESSUNITCODE, PRCBUSINESSUNITDESC, DEPOTCODE, DEPOTDESC, ROUTENUMBER, ROUTEDESC, TURNOVERGROUPCODE, TURNOVERGROUPDESC, ARTRANSACTIONDATE, CASHAMOUNT, CHARGEAMOUNT, CURRENCYCODE, LANGUAGECODE, LANGUAGE_ID, INVOICEDATE)
as select d.code salesjournalcode,
 (SELECT description FROM salesjournalgroup_desc x WHERE x.salesjournalgroup_id = a.salesjournalgroup_id
  AND x.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) salesjournaldesc,
 e.code plantcode, e.name plantname,
 b.code businessunitcode, b.description businessunitdesc,
 pb.code prcbusinessunitcode, pb.description prcbusinessunitdesc,
 w.code depotcode, w.description depotdesc,
 c.routenumber, c.description routedesc,
 f.code turnovergroupcode,
 (SELECT description FROM turnovergroup_desc y WHERE y.turnovergroup_id = a.turnovergroup_id
  AND y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) turnovergroupdesc,
 a.artransactiondate artransactiondate,
 a.cashamount, a.chargeamount, a.currencycode
, languages.code languagecode, languages.language_id language_id
,a.invoicedate
from VR_SALESJOURNALAMOUNT_AUS a
 left outer join (route c left outer join depot w on c.depot_id = w.depot_id)
   on c.route_id = a.route_id,
 businessunit b, businessunit pb, salesjournalgroup d, plant e, turnovergroup f, languages
where a.businessunit_id = b.businessunit_id
 and a.processbusinessunit_id = pb.businessunit_id
 and a.salesjournalgroup_id = d.salesjournalgroup_id
 and b.plant_id = e.plant_id
 and a.turnovergroup_id = f.turnovergroup_id

/
create or replace view VR_SALESJOURNAL_SMG
 (SALESJOURNALCODE, SALESJOURNALDESC, PLANTCODE, PLANTNAME, BUSINESSUNITCODE, BUSINESSUNITDESC, PRCBUSINESSUNITCODE, PRCBUSINESSUNITDESC, DEPOTCODE, DEPOTDESC, ROUTENUMBER, ROUTEDESC, TURNOVERGROUPCODE, TURNOVERGROUPDESC, ARTRANSACTIONDATE, CASHAMOUNT, CHARGEAMOUNT, CURRENCYCODE, LANGUAGECODE, LANGUAGE_ID)
as select d.code salesjournalcode,
 (SELECT description FROM salesjournalgroup_desc x WHERE x.salesjournalgroup_id = a.salesjournalgroup_id
  AND x.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) salesjournaldesc,
 e.code plantcode, e.name plantname,
 b.code businessunitcode, b.description businessunitdesc,
 pb.code prcbusinessunitcode, pb.description prcbusinessunitdesc,
 w.code depotcode, w.description depotdesc,
 c.routenumber, c.description routedesc,
 f.code turnovergroupcode,
 (SELECT description FROM turnovergroup_desc y WHERE y.turnovergroup_id = a.turnovergroup_id
  AND y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) turnovergroupdesc,
 a.artransactiondate artransactiondate,
 a.cashamount, a.chargeamount, a.currencycode
, languages.code languagecode, languages.language_id
from VR_SALESJOURNALAMOUNT_SMG a
 left outer join (route c left outer join depot w on c.depot_id = w.depot_id)
   on c.route_id = a.route_id,
 businessunit b, businessunit pb, salesjournalgroup d, plant e, turnovergroup f, languages
where a.businessunit_id = b.businessunit_id
 and a.processbusinessunit_id = pb.businessunit_id
 and a.salesjournalgroup_id = d.salesjournalgroup_id
 and b.plant_id = e.plant_id
 and a.turnovergroup_id = f.turnovergroup_id

/
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_AGEANALYSIS_CUSTOMERROUTE
 (CUSTOMER_ID, EXPDATE, ROUTENUMBER, ROUTEDESC, REPORTPARAM_ID)
as select v.customer_id, V.expdate,
  r.routenumber, r.description routedesc,
  v.reportparam_id
from V_AGEANALYSIS_ROUTE v
  left outer 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, DAY, ROUTE, STOPNUMBER, DRIVERNUMBER, LASTPAYMENTDATE, LASTPAYMENT, LASTDEBITDATE, REPORTPARAM_ID, BUSINESSUNIT_ID, CUSTOMER_ID, DISTRICTCODE, DISTRICTDESC, ROUTEMANAGERNO, ROUTEMANAGERNAME
, COUNTINV)
as SELECT 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,
  F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 0, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4)) CURRENT_AMOUNT,
  F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 1, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4)) AMOUNT_30,
  F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 2, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4)) AMOUNT_60,
  F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 3, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4)) AMOUNT_90,
  F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 4, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4)) AMOUNT_120,
  (select sum(y.amount-y.totalappliedamount) from artransaction y, artransactiontype z
     where y.billtocustomer_link_id = C.CUSTOMER_ID       --and y.closingtransaction_id is null
       and y.debitcredit = 'C' and y.isopen_yn = 'Y'
       and y.artransactiontype_id = z.artransactiontype_id and z.typenumber <> 2) 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((select min(y.artransactiondate) lastpaymentdate
           from   artransaction y
           where  y.debitcredit = 'D'
           and    nvl(y.parentartransaction_id, y.artransaction_id) = y.artransaction_id
           and    nvl(y.closingtransaction_id, 0) = 0
           and    y.billtocustomer_link_id = c.customer_id
           and    y.businessunit_id = c.defaultbusinessunit_id
           group  by y.billtocustomer_link_id, y.businessunit_id), trunc(sysdate))  LASTDEBITDATE
  , REPORTPARAM.REPORTPARAM_ID
  , 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
, (select count(ar1.invoicenumber) from artransaction ar1, artransactiontype art1
          where ar1.debitcredit = 'D' --and ar1.closingtransaction_id is null
          and nvl(ar1.parentartransaction_id, ar1.artransaction_id) = ar1.artransaction_id
          and ar1.billtocustomer_link_id = c.customer_id and ar1.isopen_yn = 'Y'
          and ar1.artransactiontype_id = art1.artransactiontype_id and art1.typenumber <> 2) countinv
FROM 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)
    INNER JOIN CUSTOMERBILLINGINFO B
          LEFT OUTER JOIN EMPLOYEE E1 ON (B.COLLECTIONRESPONSIBLE_ID = E1.EMPLOYEE_ID)
    ON C.DEBTOR_ID = B.CUSTOMER_ID
    INNER JOIN ADDRESS D ON C.VISITADDRESS_ID = D.ADDRESS_ID
    INNER JOIN BUSINESSUNIT BU
          INNER JOIN PLANT P ON BU.PLANT_ID = P.PLANT_ID
    ON C.DEFAULTBUSINESSUNIT_ID = BU.BUSINESSUNIT_ID,
  REPORTPARAM

/
create or replace view V_ARTRIALBALANCE_NIW
 (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, DAY, ROUTE, STOPNUMBER, DRIVERNUMBER, LASTPAYMENTDATE, LASTPAYMENT, LASTDEBITDATE, REPORTPARAM_ID, BUSINESSUNIT_ID, CUSTOMER_ID, DISTRICTCODE, DISTRICTDESC, ROUTEMANAGERNO, ROUTEMANAGERNAME
, BILLTO_NR, BILLTO_NAME, BILLTO_ACTIVE, CUSTOMER_ACTIVE)
as SELECT
    /*+ index(B XPKCUSTOMERBILLINGINFO)
    index(E1 XPKEMPLOYEE)
    index(C XPKCUSTOMER)
    index(I XPKCHAIN)
    index(E2 XPKEMPLOYEE)
    index(D XPKADDRESS)
    index(BU XPKBUSINESSUNIT)
    index(P XPKPLANT) */
    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,
    F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 0, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4)) CURRENT_AMOUNT,
    F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 1, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4)) AMOUNT_30,
    F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 2, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4)) AMOUNT_60,
    F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 3, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4)) AMOUNT_90,
    F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 4, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4)) AMOUNT_120,
   (select sum(y.amount-y.totalappliedamount) from artransaction y, artransactiontype z
     where y.billtocustomer_link_id = C.CUSTOMER_ID       --and y.closingtransaction_id is null
       and y.debitcredit = 'C' and y.isopen_yn = 'Y'
       and y.artransactiontype_id = z.artransactiontype_id and z.typenumber <> 2) 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, GETCURRENTDATE()) LASTDEBITDATE ,
    REPORTPARAM.REPORTPARAM_ID ,
    BU.BUSINESSUNIT_ID,
    BILL.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,
    BILL.CUSTOMERNUMBER BillTo_NR, bill.name BillTo_Name, BILL.active BillTo_active, c.active Customer_active
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  ON C.CUSTOMER_ID = V1.CUSTOMER_ID
        LEFT OUTER JOIN EMPLOYEE E2  ON V1.DRIVER_ID = E2.EMPLOYEE_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, REPORTPARAM--  , V_LASTPAYMENTD V3
      , CUSTOMER BILL
WHERE C.DEBTOR_ID = B.CUSTOMER_ID AND C.VISITADDRESS_ID = D.ADDRESS_ID
      AND BU.PLANT_ID = P.PLANT_ID AND BILL.DEFAULTBUSINESSUNIT_ID = BU.BUSINESSUNIT_ID
      AND C.DEBTOR_ID = BILL.CUSTOMER_ID

/
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, GETCURRENTDATE()) 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_BATCHCARDS_STX
 (BATCH_ID, BATCHNUMBER, CUSTOMERNUMBER, CUSTOMERNAME, DELIVERYDATE, REMARK, ROUTEDESCRIPTION, WASHINGPROCESS, THEORETICALWEIGHT)
as select distinct b.batch_id,
       b.batchnumber,
       c.customernumber,
       c.name customername,
       trunc(b.timestamp) deliverydate,
       c.remark,
       cri.routedescription,
       (select max(w.code)
        from washingprocess w
        WHERE w.washingprocess_id = v.washingprocess_id) washingprocess,
       (select sum(ps.theoreticalweight)
from garmentbatchscan gb join uniqueitem u on gb.uniqueitem_id=u.uniqueitem_id
join product p on p.product_id=u.product_id
join productsize ps on (ps.product_id=p.product_id
AND u.sizedefinition_id=ps.sizedefinition_id)
where gb.garmentbatch_id=b.batch_id
) theoreticalweight
from batch b
  left outer join customer c
       left outer join customerrouteinfo cri on cri.customer_id = c.customer_id
  on c.customer_id = b.customer_link_id
  inner join v_batchcard_aux v on v.batch_id = b.batch_id
where v.linetype in (1,2)
union all
select distinct gba.garmentbatch_id batch_id,
       gba.garmentbatchnumber batchnumber,
       c.customernumber,
       c.name customername,
       trunc(gba.timestamp) deliverydate,
       c.remark,
       cri.routedescription,
       wp.code washingprocess,
       (select sum(ps.theoreticalweight)
from garmentbatchscan gb
join uniqueitem u on gb.uniqueitem_id=u.uniqueitem_id
join product p on p.product_id=u.product_id
join productsize ps on( ps.product_id=p.product_id
AND u.sizedefinition_id=ps.sizedefinition_id)
where gb.garmentbatch_id=gba.garmentbatch_id) theoreticalweight
from
   garmentbatch gba
   join v_batchcard_aux x
        join customer c
             left outer join customerrouteinfo cri on cri.customer_id = c.customer_id
        on c.customer_id = x.customer_link_id
        left outer join washingprocess wp on wp.washingprocess_id = x.washingprocess_id
   on x.batch_id = gba.garmentbatch_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 between rp.date_value1 and 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 on cb.businessunit_id = bu.businessunit_id
    inner join plant p on bu.plant_id = p.plant_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, 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, ADDITIONALTONOTE_ID, ADDITIONALCDNNUMBER, CLIENTDELNOTEFORMLAYOUT, WORKSTATION_ID, WORKSTATION_CODE, EMPTIED, LANGUAGEID, LEGACYCODE, CORRECTIONCLIENTDELNOTE_ID, CORRECTIONCLIENTDELIVERYNOTE
)
as SELECT
  --+index(cds XIE2CLIENTDELNOTELINESCAN)
  1 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, 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
, ( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
  and fmd.language_id = languages.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
, null flagCode, null flagDesc
, 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 GETCURRENTDATE() between wghc.dateactive and wghc.dateinactive ) then 1
          else 0
            end PrintWeight
, --( select count(*) from v_cdn_DelayedDelivery where v_cdn_DelayedDelivery.clientdeliverynote_id = cdn.clientdeliverynote_id ) Print_v_cdn_DelayedDelivery
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
, --( select count(*) from v_cdn_DeliveredAfter where v_cdn_DeliveredAfter.clientdeliverynote_id = cdn.clientdeliverynote_id ) Print_v_cdn_DeliveredAfter
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
--, cdr.remark
, 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
, languages.code languageCode
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cu.customer_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 (cu.customer_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
, cds.uniqueresidentialitem_link_id, GETDATEONLY(cds.outscantimestamp) outscantimestamp/* Added 10-06-09 ROP */
, 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/* end of additions 10-06-09 ROP */
,(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
, 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, languages.language_id languageid,client.LEGACYCODE, cdn.correctionclientdelnote_id, cdn1.clientdeliverynotenumber correctionclientdeliverynote
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 on cdl.clientdeliverynoteline_id = cds.outscanclientdelnoteline_id
      ) on cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
    left outer join clientdeliverynote cdn1 on cdn.correctionclientdelnote_id = cdn1.clientdeliverynote_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
, customerresidentialsettings crs, businessunit bu, systemsetting ss
, languages
, workstation ws
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.processbusinessunit_id = bu.businessunit_id
    and bu.plant_id = ss.plant_id
        AND ss.name = 'BATCHCODEUSAGE'
and cu.currency_id = crr.currency_id
and not exists
(select PDFM.FinishingMethod_ID from PlantDepartmentFinMethod PDFM where PDFM.PlantDepartment_ID = WS.PlantDepartment_ID
)
union all
SELECT
  --+index(cds XIE2CLIENTDELNOTELINESCAN)
  2 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, 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
, ( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = fm.finishingmethod_id
  and fmd.language_id = languages.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
, null flagCode, null flagDesc
, 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 GETCURRENTDATE() between wghc.dateactive and wghc.dateinactive ) then 1
          else 0
            end PrintWeight
, --( select count(*) from v_cdn_DelayedDelivery where v_cdn_DelayedDelivery.clientdeliverynote_id = cdn.clientdeliverynote_id ) Print_v_cdn_DelayedDelivery
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
, --( select count(*) from v_cdn_DeliveredAfter where v_cdn_DeliveredAfter.clientdeliverynote_id = cdn.clientdeliverynote_id ) Print_v_cdn_DeliveredAfter
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
--, cdr.remark
, 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
, languages.code languageCode
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cu.customer_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 (cu.customer_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
, cds.uniqueresidentialitem_link_id, GETDATEONLY(cds.outscantimestamp) outscantimestamp/* Added 10-06-09 ROP */
, 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/* end of additions 10-06-09 ROP */
,(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
, 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, languages.language_id languageid,client.LEGACYCODE, cdn.correctionclientdelnote_id, cdn1.clientdeliverynotenumber correctionclientdeliverynote
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 on cdl.clientdeliverynoteline_id = cds.outscanclientdelnoteline_id
      ) on cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
    left outer join clientdeliverynote cdn1 on cdn.correctionclientdelnote_id = cdn1.clientdeliverynote_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
, customerresidentialsettings crs, businessunit bu, systemsetting ss
, languages
, workstation ws
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.processbusinessunit_id = bu.businessunit_id
    and bu.plant_id = ss.plant_id
        AND ss.name = 'BATCHCODEUSAGE'
and cu.currency_id = crr.currency_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_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 GETCURRENTDATE() 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 GETDATEONLY(cds.outscantimestamp) = GETDATEONLY(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_CBD
 (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, STREET2, ZIPCODE_CITY, CLIENTDELIVERYNOTENUMBER, CLOSINGDATE, DELIVERYDATE, BOXNUMBER, BATCHCODE, BATCHNUMBER
, BATCHYEAR, BATCHWEEK, INFECTION, 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, EMPLOYEEPHONENO, EMPLOYEEMOBILENO, EMPLOYEEFAXNO, EMPLOYEEEMAIL, RECORDEMPLCLIENTDELNOTE, LANGUAGECODE, PRODCUSTOM_CODE, PRODCUSTOM_DESC, UNIQUERESIDENTIALITEM_LINK_ID, OUTSCANTIMESTAMP, SEQUENCENUMBER, DEPTDELSTREET, DEPTDELZIPCODE, DEPTDELCITY, LOCATION, ADDITIONALTONOTE_ID, ADDITIONALCDNNUMBER, CLIENTDELNOTEFORMLAYOUT, PROCESSBUDESCRIPTION, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL
, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, LOADINGDOCK, WEEK, PRINTSTICKERATOUTSCAN, DELIVERYPOINTDESCRIPTION, DISTRIBUTIONPOINTDESCRIPTION, ORIGIN, CORRECTEDCDNNUMBER, HASFLAGS, EMPTIED)
as SELECT -- +index(cds XIE2CLIENTDELNOTELINESCAN)
  1 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, coalesce(client.legacycode, 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
, coalesce(cdn.street, address2.street)--, address.street)
street, --coalesce(
address2.street2--, address.street2) street2
, cast(( case when cdn.street is null then case when coalesce(address.zipcode, address2.zipcode) is null then ' '
                   else CONCATENATEWITHSIGN(coalesce(address.zipcode, address2.zipcode), '  ', coalesce(address.city, address2.city)) end
              else CONCATENATEWITHSIGN(cdn.zipcode, '  ', cdn.city) end) as varchar2(255))  zipcode_city
, cdn.clientdeliverynotenumber, cdn.closingdate, cdn.deliverydate,
coalesce( (select cn.boxnumber
           from   clientdeliverynote cn
           where  cn.clientdeliverynote_id = cdn.correctionclientdelnote_id), cdn.boxnumber ) boxnumber
, batch.batchcode, batch.batchnumber, batch.year batchYear, batch.week batchWeek, BATCH.INFECTION, batchcolor.description batchcolorDesc
, cast(( case
  when ss.value = '-2' then CONCATENATE(GETSUBSTRINGONLENGTH(batch.batchcode, 1, 2), cast(batch.batchnumber as varchar2(60)))
  when ss.value = '-1' then CONCATENATE(GETSUBSTRINGONLENGTH(batch.batchcode, 1, 1), cast(batch.batchnumber as varchar2(60)))
  when ss.value =  '0' then cast(batch.batchnumber as varchar2(60))
  when ss.value =  '1' then CONCATENATE(cast(batch.batchnumber as varchar2(60)), GETSUBSTRINGONLENGTH(batch.batchcode, 1, 1))
  when ss.value =  '2' then CONCATENATE(cast(batch.batchnumber as varchar2(60)), GETSUBSTRINGONLENGTH(batch.batchcode, 1, 2))
  end) as varchar2(60)) batch_CodeNumber
, ( select day_desc.description from day_desc where --batch.day_id
getabsdaynumber(cdn.deliverydate) = 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
, (   select uri.primaryid
  from uniqueresidentialitem uri where cds.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id  ) primaryid
, null flagCode, null flagDesc,
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 GETCURRENTDATE() 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 exists (select 1 from v_cdn_SendToOwner where v_cdn_SendToOwner.clientdeliverynote_id = cdn.clientdeliverynote_id
     and v_cdn_SendToOwner.ownerNumber <> client.clientnumber ) then 1
          else 0
            end Print_v_cdn_SendToOwner
, case when exists ( select 1 from v_cdn_ReceiveFromOwner where v_cdn_ReceiveFromOwner.clientdeliverynote_id = cdn.clientdeliverynote_id ) 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, emp.phoneno employeephoneno, emp.mobileno employeemobileno, emp.faxno employeefaxno, emp.email employeeemail
, (select cast(systemsetting.value as varchar2(5)) 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, 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 (cu.customer_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
, cds.uniqueresidentialitem_link_id, GETDATEONLY(cds.outscantimestamp) outscantimestamp/* Added 10-06-09 ROP */
, 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
, 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
, processbu.description processbudescription,
plant.code plantcode, plant.name plantname, plant.website plantwebsite, plant.email plantemail,
plantaddress.street plantstreet, plantaddress.zipcode plantzipcode,
plantaddress.city plantcity, plantaddress.state plantstate, plant.phoneno plantphoneno, plant.faxno plantfaxno
, route.loadingdock, cast(getweeknumber(cdn.deliverydate) as varchar2(20)) week, fm.printstickeratoutscan
, coalesce(delvp.description, devp.description) deliverypointdescription
, (select distp.description from distributionpoint distp where distp.distributionpoint_id = coalesce(cpp.distributionpoint_id, dr.distributionpoint_id)) distributionpointdescription
, cdn.origin
, (select cn.clientdeliverynotenumber
   from   clientdeliverynote cn
   where  cn.clientdeliverynote_id = cdn.correctionclientdelnote_id) CorrectedCDNnumber
, (select count(1) from v_clientdeliverynote_flag cdf where cdf.uniqueresidentialitem_link_id =  cds.uniqueresidentialitem_link_id
and cdf.scantimestamp = GETDATEONLY(cds.outscantimestamp) and cdf.Language_code = languages.code) HasFlags
, cdn.emptied
from
  clientdeliverynote cdn
    left outer join route on cdn.route_id = route.route_id
    left outer join ( clientdeliverynoteline cdl
      join product prd join productgroup pg on pg.productgroup_id = prd.productgroup_id
      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 on cdl.clientdeliverynoteline_id = cds.outscanclientdelnoteline_id
      ) on cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
, customer cu
        LEFT OUTER JOIN EMPLOYEE emp ON (cu.SERVICEEMPLOYEE_ID = emp.EMPLOYEE_ID), currency crr
, batch --left outer join employee emp on batch.employee_id = emp.employee_id
, batchcolor
, 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 address2.address_id = devp.deliveryaddress_id
                     on devp.deliverypoint_id = dip.deliverypoint_id
               on dip.distributionpoint_id = dr.distributionpoint_id
         on dr.departmentroom_id = cr.departmentroom_id
    on cr.client_id = client.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
, customerresidentialsettings crs, businessunit bu, systemsetting ss
, languages
, businessunit processbu, plant, address plantaddress
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.processbusinessunit_id = bu.businessunit_id
    and bu.plant_id = ss.plant_id
        AND ss.name = 'BATCHCODEUSAGE'
and cu.currency_id = crr.currency_id
and cdn.processbusinessunit_id = processbu.businessunit_id
and processbu.plant_id = plant.plant_id
and plant.address_id = plantaddress.address_id
and coalesce(pg.code, 'NULL') <> 'PWFLAT'

/
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 GETCURRENTDATE() 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 GETDATEONLY(cds.outscantimestamp) = GETDATEONLY(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_LTS
 (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, CLIENTSEARCHNAME, GENDER, ROOM, STREET, ZIPCODE_CITY, CLIENTDELIVERYNOTENUMBER, CLOSINGDATE, DELIVERYDATE, BOXNUMBER, BATCHCODE, BATCHNUMBER
, BATCHYEAR, BATCHWEEK, BATCHCOLORDESC, BATCH_CODENUMBER, DAYDESC, ROUTENUMBER, ROUTEDESC, STOPNUMBER, GROSSWEIGHT, WEIGHTDECIMALS, TAREWEIGHT, WEIGHTUNIT, PACKINGSEQUENCE, PRODUCTCODE, SIZECODE, FINISHINGMETHODCODE, FINISHINGMETHODDESC, PRODUCTDESC, QTYRECEIVED, QTYDELIVERED, FLAGCODE, FLAGDESC, PRINT_V_CDN_OUTSCANNEDID, CUSTOMERCLIENTS, PRINTIDCODE, PRINTLATEPIECES, ACCEPTOTHERCLIENTS, PRINTQTYRECEIVED, SYSTEMSETTINGVALUE, EMPLOYEENUMBER, EMPLOYEENAME, RECORDEMPLCLIENTDELNOTE
, LANGUAGECODE, PRODCUSTOM_CODE, PRODCUSTOM_DESC, SEQUENCENUMBER, DEPTDELSTREET, DEPTDELZIPCODE, DEPTDELCITY, BU_DESC, PLANTCODE, PLANTNAME, PLANT_STREET, PLANT_ZIP, PLANT_CITY, PLANT_PHONE, PLANT_FAX, PLANT_EMAIL, PLANT_WEB, ROUTEDRIVINGDAYDESC, ACTIVITY_CODE_PRODUCT, ACTIVITY_DESC_PRODUCT, VATNUMBER, CREATIONDATE, BATCHDAY_ID, REGUNIT, CLIENTREMARK, LABELLAYOUTCODE, WEIGHTCATEGCODE, WEIGHTCATEGDESC, YEAR, WEEK)
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(*) 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, coalesce(client.searchname, cdn.name, client.name) clientsearchname
, client.gender
, 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, cdn.tareweight
, ( 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 fd.description from finishingmethod_desc fd where fd.finishingmethod_id = fm.finishingmethod_id and fd.language_id = languages.language_id) finishingmethoddesc
, ( 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
/*, (   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 getdateonly(cds.outscantimestamp) = getdateonly(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 getdateonly(cds.outscantimestamp) = getdateonly(ris.scantimestamp)
          and ris.transactiontype_id = 2 and flag_desc.language_id = languages.language_id )
else null
end 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 getcurrentdate() 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
, ( select count(*) from v_cdn_outscannedids_lts vo where vo.clientdeliverynote_id = cdn.clientdeliverynote_id ) print_v_cdn_outscannedid
, 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, 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 (cu.customer_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) prodcustom_desc
--, cds.uniqueresidentialitem_link_id, getdateonly(cds.outscantimestamp) outscantimestamp/* added 10-06-09 rop */
, 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/* end of additions 10-06-09 rop */
, bu.description bu_desc
, pla.code plantcode, pla.name plantname
, (select adr.street from address adr where pla.address_id = adr.address_id) plant_street
, (select adr.zipcode from address adr where pla.address_id = adr.address_id) plant_zip
, (select adr.city from address adr where pla.address_id = adr.address_id) plant_city
, pla.phoneno plant_phone
, pla.faxno plant_fax
, pla.email plant_email
, pla.website plant_web
, (select dd.description from day_desc dd where dd.day_id = route.drivingday_id and dd.language_id = languages.language_id) routedrivingdaydesc
, (select ac.code from productgroup pg, activity ac where pg.activity_id = ac.activity_id and prd.productgroup_id = pg.productgroup_id) activity_code_product
, (select acd.description from productgroup pg, activity_desc acd where pg.activity_id = acd.activity_id and prd.productgroup_id = pg.productgroup_id and acd.language_id = languages.language_id) activity_desc_product
, bu.vatnumber, cdn.creationdate, batch.day_id batchday_id
, (select rgd.description
         from   registrationunit_desc rgd
         where  rgd.registrationunit_id = prd.registrationunit_id and rgd.language_id = languages.language_id) regunit
, client.remark clientremark
, (select fl.code from formlayout fl where fl.formlayout_id = crs.clientdelnoteformlayout_id) labellayoutcode
, (select we.code from weighingcategory we where we.weighingcategory_id = cdn.weighingcategory_link_id) weightcategcode
, (select wed.description from weighingcategory_desc wed where wed.weighingcategory_id = cdn.weighingcategory_link_id and wed.language_id = languages.language_id) weightcategdesc
, batch.year, batch.week
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 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
, customerresidentialsettings crs, businessunit bu, systemsetting ss, plant pla
, 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.processbusinessunit_id = bu.businessunit_id
    and bu.plant_id = pla.plant_id
    and bu.plant_id = ss.plant_id
        and ss.name = 'BATCHCODEUSAGE'
and cu.currency_id = crr.currency_id
-- Next line added to suppress 0-lines on printed Clientdeliverynote. dd 03-10-2013, Edwin de Groot - Synergy
-- additional check on weight being > 0. dd 07-10-2013, Edwin de Groot - Synergy
  and ((cdl.qtyscannedin + cdl.qtycountedin+ cdl.qtyscannedout+cdl.qtycountedout) <> 0 or nvl(cdn.grossweight,0) > 0)

/
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 GETCURRENTDATE() 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 GETDATEONLY(cds.outscantimestamp) = GETDATEONLY(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_CLIENTDELIVERYNOTE_WBA
 (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, PRODCUSTOM_CODE, PRODCUSTOM_DESC, UNIQUERESIDENTIALITEM_LINK_ID, OUTSCANTIMESTAMP, SEQUENCENUMBER, DEPTDELSTREET, DEPTDELZIPCODE, DEPTDELCITY, DELIVERYLAYOUTCODE)
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(*) 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
, (   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 GETDATEONLY(cds.outscantimestamp) = GETDATEONLY(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 GETDATEONLY(cds.outscantimestamp) = GETDATEONLY(ris.scantimestamp)
          and ris.transactiontype_id = 2 and flag_desc.language_id = languages.language_id )
else null
end 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 GETCURRENTDATE() between wghc.dateactive and wghc.dateinactive ) PrintWeight*/
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 GETCURRENTDATE() between wghc.dateactive and wghc.dateinactive ) then 1
          else 0
            end PrintWeight
, --( select count(*) from v_cdn_DelayedDelivery where v_cdn_DelayedDelivery.clientdeliverynote_id = cdn.clientdeliverynote_id ) Print_v_cdn_DelayedDelivery
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
, --( select count(*) from v_cdn_DeliveredAfter where v_cdn_DeliveredAfter.clientdeliverynote_id = cdn.clientdeliverynote_id ) Print_v_cdn_DeliveredAfter
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
, /*( 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*/
  case when exists (select 1 from v_cdn_SendToOwner where v_cdn_SendToOwner.clientdeliverynote_id = cdn.clientdeliverynote_id
     and v_cdn_SendToOwner.ownerNumber <> client.clientnumber ) then 1
          else 0
            end Print_v_cdn_SendToOwner
, --( select count(*) from v_cdn_ReceiveFromOwner where v_cdn_ReceiveFromOwner.clientdeliverynote_id = cdn.clientdeliverynote_id ) Print_v_cdn_ReceiveFromOwner
case when exists ( select 1 from v_cdn_ReceiveFromOwner where v_cdn_ReceiveFromOwner.clientdeliverynote_id = cdn.clientdeliverynote_id ) then 1
          else 0
            end 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, 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 (cu.customer_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
, cds.uniqueresidentialitem_link_id, GETDATEONLY(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 fl.code
    from   formlayout fl
    where  fl.formlayout_id = ( select crs.clientdelnoteformlayout_id
                                from   customerresidentialsettings crs
                                where customer_id = cu.customer_id
                              )
  ) deliverylayoutcode
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 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
, 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.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_COMCUST_INFO_AMM
 (DEBTOR_ID, CUSTOMER_ID, COMMONCUSTOMER_ID, NAME, CUSTOMERNUMBER, COMMON_ID, COLLECTION_PERSON, COMMON_MARKET_ID, COMMON_STATEMENT, COMMON_FAX, COMMON_NAME, COMMON_NUMBER)
as select c.debtor_id, c.customer_id, c.commoncustomer_id, c.name, c.customernumber, cc.common_id,
       (select e.name from employee e, customerbillinginfo cb
          where e.employee_id= cb.collectionresponsible_id and
          cb.customer_id = cc.debtor_id) collection_person,
       (select c.marketsegment_id from customer c
          where c.customer_id = cc.common_id) common_market_id,
       (select cb.statementpercustomer from customerbillinginfo cb
	        where cb.customer_id = cc.debtor_id) common_statement,
       (select cp.fax from contactperson cp
	        where cp.customer_id = cc.common_id and cp.invoicecontactperson = 'Y') common_fax,
       (select c.legalname from customer c
          where c.customer_id = cc.common_id) common_name,
       (select c.customernumber from customer c
          where c.customer_id = cc.common_id) common_number
from customer c join v_common_cust_id_amm cc
on c.customer_id = cc.customer_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_CONDENSEDCOSTREPORTWEEK_SMG
 (INVOICEHEADER_ID, INVOICENUMBER, ACTIVITYREFERENCE, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, DELTOCUSTVATNR, 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
, CUSTTYPE, PARENTINVOICEHEADER_ID)
as select
  v.invoiceheader_id, coalesce(v.parentinvnr, v.invoicenumber) invoicenumber, v.activityreference, v.startweek, v.endweek, v.startmonth, v.endmonth
, v.billtocustomernumber, v.billtocustomername, v.deltocustomernumber, v.deltocustomername,
( select c.vatnumber from customer c  where c.customernumber=v.deltocustomernumber) deltocustvatnr
, v.city, v.zipcode, v.street, v.contactpersonname
, v.costcenter_code, v.costcenter_description
, sum(v.costcenterinvoiceline_amount) costcenterinvoiceline_amount
, ' ' taxgroupcode
, 0 percentage
, sum(v.Amount_VAT) Amount_VAT
, sum(v.Amount_Gross) Amount_Gross
, v.currencycode, v.invoiceamountdecimals
, v.printtaxonappendix
, v.languageCode
, v.showvatoncondcostrep
, v.year, v.week, v.yearweek
, v.billtosendinvoiceto
, F_GetCustType_smg(v.invoiceheader_id) custtype
, v.parentinvoiceheader_id
from V_CondensedCostReportWeek_AUX v
group by
  v.invoiceheader_id, coalesce(v.parentinvnr, v.invoicenumber), v.activityreference, v.startweek, v.endweek, v.startmonth, v.endmonth
, v.billtocustomernumber, v.billtocustomername, v.deltocustomernumber, v.deltocustomername
, v.city, v.zipcode, v.street, v.contactpersonname, v.costcenter_code, v.costcenter_description--, ' ' taxgroupcode, 0 percentage
, v.currencycode, v.invoiceamountdecimals, v.printtaxonappendix, v.languageCode, v.showvatoncondcostrep, v.yearweek, v.year, v.week, v.billtosendinvoiceto
, v.parentinvoiceheader_id

/
create or replace view V_CONSDELIVEREDPRODUCTS_ECL
 (CONSIGNMENTNOTENUMBER, PACKINGNOTELINE_ID, TYPEOFMERCHANDISE, PRODUCTCODE, PRODUCT_ID, PACKINGNOTE_ID, SIZEDEFINITION_ID, FINISHINGMETHOD_ID, PRODUCTDESCRIPTION, DELIVEREDAMOUNT, PRODTHEORET, TAREWEIGHT, LANGUAGECODE, BU_CODE, SHORTSIN, REDUCTION, ROUNDINGBF, ROUNDINGCF, SHORTSOUT, CHARGEABLE)
as SELECT DISTINCT
    CN.CONSIGNMENTNOTENUMBER, PNL.PACKINGNOTELINE_ID
  , PRD.TYPEOFMERCHANDISE
  , PRD.CODE PRODUCTCODE, PRD.PRODUCT_ID, PN.PACKINGNOTE_ID, PNL.SIZEDEFINITION_ID , PNL.FINISHINGMETHOD_ID
  , ( SELECT PD.DESCRIPTION FROM PRODUCT_DESC PD WHERE PD.PRODUCT_ID = PRD.PRODUCT_ID
    AND PD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) PRODUCTDESCRIPTION,
  PNL.DELIVEREDAMOUNT,
  COALESCE(PNL.DELIVEREDAMOUNT * PRD.THEORETICALWEIGHT, 0) PRODTHEORET,
  (SELECT COALESCE(SUM(VK.TAREWEIGHT), 0) FROM V_CONSIG_CNT_ECL VK JOIN PACKINGNOTE PN2 ON PN2.PACKINGNOTE_ID=VK.PACKINGNOTE_ID WHERE VK.LANGUAGECODE=LANGUAGES.CODE AND PN2.CONSIGNMENTNOTE_ID=CN.CONSIGNMENTNOTE_ID AND PN2.DELIVERYDATE=PN.DELIVERYDATE) TAREWEIGHT,
   LANGUAGES.CODE LANGUAGECODE
  ,(SELECT BU.CODE FROM BUSINESSUNIT BU WHERE PN.PROCESSBUSINESSUNIT_ID = BU.BUSINESSUNIT_ID) BU_CODE,
  /*COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
  WHERE DV.PACKINGNOTE_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 IN (2,3,6)--AND DV.AMOUNT>0
  ),0)+PNL.STANDARDAMOUNT REQUIREDPOZ,
  COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
  WHERE DV.PACKINGNOTE_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
  ), 0) + PNL.STANDARDAMOUNT REQUIRED,*/
  COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
  WHERE DV.PACKINGNOTE_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 = 5
  AND DV.CAUSENOTE_ID IS NOT NULL
  ), 0) SHORTSIN,
  COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
  WHERE DV.PACKINGNOTE_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 = 3
  AND DV.AMOUNT < 0
  ), 0) REDUCTION,
  COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
  WHERE DV.PACKINGNOTE_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 = 4
  AND DV.CAUSENOTE_ID IS NOT NULL
  AND DV.AMOUNT < 0
  ), 0) ROUNDINGBF,
  COALESCE((SELECT SUM(DV.AMOUNT)*(-1) FROM DELIVERYVARIATIONS DV
  WHERE DV.PACKINGNOTE_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 = 4
  AND DV.CAUSENOTE_ID IS NOT NULL
  AND DV.AMOUNT < 0
  AND DV.DELIVERYDATE > CN.DELIVERYDATE
  ), 0) ROUNDINGCF,
  COALESCE((SELECT SUM(DV.AMOUNT) FROM DELIVERYVARIATIONS DV
  WHERE DV.PACKINGNOTE_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 = 5
  AND DV.CAUSENOTE_ID IN (SELECT PN2.PACKINGNOTE_ID FROM PACKINGNOTE PN2 WHERE PN2.CONSIGNMENTNOTE_ID = CN.CONSIGNMENTNOTE_ID)
  AND DV.DELIVERYDATE > CN.DELIVERYDATE
  ), 0) SHORTSOUT
  , (PNL.DELIVEREDAMOUNT - PNL.NOCHARGEPREVREJECTED - PNL.NOCHARGEPREVSHORTAGE) CHARGEABLE
FROM
  CONSIGNMENTNOTE CN, PACKINGNOTE PN, PACKINGNOTELINE PNL
, PRODUCT PRD, SIZEDEFINITION SIZDEF, FINISHINGMETHOD FINMETH, LANGUAGES
WHERE
    CN.CONSIGNMENTNOTE_ID = PN.CONSIGNMENTNOTE_ID
    AND PN.PACKINGNOTE_ID = PNL.PACKINGNOTE_ID
    AND PNL.PRODUCT_ID = PRD.PRODUCT_ID
    AND PNL.SIZEDEFINITION_ID = SIZDEF.SIZEDEFINITION_ID
    AND PNL.FINISHINGMETHOD_ID = FINMETH.FINISHINGMETHOD_ID

/
create or replace view V_CONSDELIVEREDPRODUCTS_FIS
 (CONSIGNMENTNOTENUMBER, PRODUCTGROUPCODE, PRODUCTGROUPDESC, PRODUCTCODE, SIZEDEFINITIONCODE, FINMETHCODE, PRODUCTDESCRIPTION, FINMETHDESC, DELIVEREDAMOUNT, LANGUAGECODE, ADJUSTMENT, SHORTAGE, SOILCOUNT, SHORT, REJECT, OWINGS, ORDERED)
as SELECT
        CN.CONSIGNMENTNOTENUMBER
,       PRDG.CODE PRODUCTGROUPCODE
,       ( SELECT DESCRIPTION
          FROM   PRODUCTGROUP_DESC
          WHERE  PRODUCTGROUP_DESC.PRODUCTGROUP_ID = PRDG.PRODUCTGROUP_ID
             AND PRODUCTGROUP_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) PRODUCTGROUPDESC
,       PRD.CODE PRODUCTCODE
,       SIZDEF.CODE SIZEDEFINITIONCODE
,       FINMETH.CODE FINMETHCODE
,       ( SELECT DESCRIPTION
          FROM   PRODUCT_DESC
          WHERE  PRODUCT_DESC.PRODUCT_ID = PRD.PRODUCT_ID
             AND PRODUCT_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) PRODUCTDESCRIPTION
,       ( SELECT FINISHINGMETHOD_DESC.DESCRIPTION
          FROM   FINISHINGMETHOD_DESC
          WHERE  FINISHINGMETHOD_DESC.FINISHINGMETHOD_ID = FINMETH.FINISHINGMETHOD_ID
             AND FINISHINGMETHOD_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) FINMETHDESC
,      SUM(PNL.DELIVEREDAMOUNT) DELIVEREDAMOUNT
,      LANGUAGES.CODE LANGUAGECODE
/*,      COALESCE(( SELECT SUM(VDV1.AMOUNT)
                  FROM   V_DELIVERYVARIATIONS_FIS VDV1
                  WHERE  VDV1.PACKINGNOTENUMBER = PN.NOTENUMBER
                     AND VDV1.PRODUCTCODE = PRD.CODE
                     AND VDV1.FINISHINGMETHODCODE = FINMETH.CODE
                     AND VDV1.LANGUAGECODE = LANGUAGES.CODE
                     AND VDV1.ORIGIN = 3), 0) ADJUSTMENT*/
, nvl((select sum(q.quantity)
         from   rentalqtyadjustment q, productlistperdistribpoint plpd, distributionpoint dp,
                department t, deliveryvariations dev
         where  q.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
         and    plpd.distributionpoint_id = dp.distributionpoint_id
         and    dp.department_id = t.department_id
         and    t.customer_id = CN.Customer_Link_Id
         and    PRD.Product_Id = plpd.product_id
         and    SIZDEF.sizedefinition_id = plpd.sizedefinition_id
         and    FINMETH.finishingmethod_id = plpd.finishingmethod_id
				 AND    q.deliveryvariations_id = dev.deliveryvariations_id AND dev.packingnote_id = pn.packingnote_id
         --and    q.adjustmentdate >= CN.Deliverydate and    q.adjustmentdate <= CN.Deliverydate and    q.quantity > 0
				 ), 0) ADJUSTMENT
,      COALESCE(( SELECT SUM(VDV2.AMOUNT)
                  FROM   V_DELIVERYVARIATIONS_FIS VDV2
                  WHERE  VDV2.PACKINGNOTENUMBER = PN.NOTENUMBER
                     AND VDV2.PRODUCTCODE = PRD.CODE
                     AND VDV2.FINISHINGMETHODCODE = FINMETH.CODE
                     AND VDV2.LANGUAGECODE = LANGUAGES.CODE --AND VDV2.UPDATERENTQTY = 'Y'
                     AND VDV2.ORIGIN = 5), 0) SHORTAGE
,  COALESCE(( SELECT SUM(VDV2.AMOUNT)
                  FROM   V_DELIVERYVARIATIONS_FIS VDV2
                  WHERE  VDV2.PACKINGNOTENUMBER = PN.NOTENUMBER
                     AND VDV2.PRODUCTCODE = PRD.CODE
                     AND VDV2.FINISHINGMETHODCODE = FINMETH.CODE
                     AND VDV2.LANGUAGECODE = LANGUAGES.CODE--AND VDV2.UPDATERENTQTY = 'Y'
                     AND VDV2.ORIGIN = 1 AND VDV2.SOILCOUNTSUBTYPE = 1), 0) SOILCOUNT
,   COALESCE(SUM(pnl.nochargeprevshortage), 0) SHORT
,   COALESCE(SUM(pnl.nochargeprevrejected),0) REJECT
,   COALESCE(( SELECT SUM(VDV2.AMOUNT)
                  FROM   V_DELIVERYVARIATIONS_FIS VDV2
                  WHERE  VDV2.PACKINGNOTENUMBER = PN.NOTENUMBER
                     AND VDV2.CAUSENOTENUMBER IS NOT NULL
                     AND VDV2.PRODUCTCODE = PRD.CODE
                     AND VDV2.FINISHINGMETHODCODE = FINMETH.CODE
                     AND VDV2.LANGUAGECODE = LANGUAGES.CODE--AND VDV2.UPDATERENTQTY = 'Y'
                     AND ((VDV2.ORIGIN = 1) AND (VDV2.SOILCOUNTSUBTYPE in (2,3))
                       OR (VDV2.ORIGIN = 5))), 0) OWINGS
, SUM(pnl.tobedeliveredamount) Ordered
FROM   CONSIGNMENTNOTE CN
,      PACKINGNOTE PN
,      PACKINGNOTELINE PNL
,      PRODUCT PRD
         LEFT OUTER JOIN PRODUCTGROUP PRDG
           ON PRD.PRODUCTGROUP_ID = PRDG.PRODUCTGROUP_ID
,      SIZEDEFINITION SIZDEF
,      FINISHINGMETHOD FINMETH
,      LANGUAGES
WHERE  CN.CONSIGNMENTNOTE_ID = PN.CONSIGNMENTNOTE_ID
   AND PN.PACKINGNOTE_ID = PNL.PACKINGNOTE_ID
   AND PNL.PRODUCT_ID = PRD.PRODUCT_ID
   AND PNL.SIZEDEFINITION_ID = SIZDEF.SIZEDEFINITION_ID
   AND PNL.FINISHINGMETHOD_ID = FINMETH.FINISHINGMETHOD_ID
GROUP BY
       LANGUAGES.LANGUAGE_ID
,      LANGUAGES.CODE
,      CN.CONSIGNMENTNOTENUMBER
,      PRDG.CODE
,      PRDG.PRODUCTGROUP_ID
,      PRD.CODE
,      PRD.PRODUCT_ID
,      SIZDEF.CODE
,      FINMETH.FINISHINGMETHOD_ID
,      FINMETH.CODE
,      PN.NOTENUMBER --, pnl.tobedeliveredamount, pnl.nochargeprevshortage, pnl.nochargeprevrejected
, CN.Customer_Link_Id, SIZDEF.sizedefinition_id, pn.packingnote_id

/
create or replace view V_CONSIGNMENTDELIVERYNOTES_ECL
 (CONSIGNMENTNOTENUMBER, DEPARTMENTNUMBER, DELIVERYDATE, NOTENUMBER, PNNUMBERLIST, DEPARTMENTDESCRIPTION, CONSPOINT, PACKINGNOTE_ID, CONTAINERRECORDINGACTIVE, LANGUAGECODE, ORIGIN, BU_CODE, CONTAINERIDS)
as select /*+index (department XPKDEPARTMENT)*/
       cn.consignmentnotenumber, department.departmentnumber, pn.deliverydate, pn.notenumber,
       (select listagg(pn2.notenumber, ', ') within group(order by pn2.notenumber) from packingnote pn2 where pn2.consignmentnote_id=cn.consignmentnote_id and pn2.deliverydate=pn.deliverydate) pnnumberlist,
       department.description departmentdescription,
       distributionpoint.distributionpointnumber conspoint, pn.packingnote_id,
       ss2.value containerrecordingactive, languages.code languagecode, pn.origin,
			 bu.code BU_code,
       (select listagg(vk.CONTAINER_PRIMARYID, ', ') within group (order by vk.CONTAINER_PRIMARYID) from v_consig_cnt_ecl vk join packingnote pn2 on pn2.packingnote_id=vk.packingnote_id where vk.LANGUAGECODE=languages.code and pn2.consignmentnote_id=cn.consignmentnote_id and pn2.deliverydate=pn.deliverydate) containerids
from   consignmentnote cn, packingnote pn, distributionpoint, department, transportarticle,
       businessunit bu, systemsetting ss, systemsetting ss2, languages
where  cn.consignmentnote_id = pn.consignmentnote_id and
       pn.distributionpoint_id = distributionpoint.distributionpoint_id and
       distributionpoint.department_id = department.department_id and
       pn.transportarticle_id = transportarticle.transportarticle_id and
       pn.processbusinessunit_id = bu.businessunit_id and bu.plant_id = ss.plant_id and
       ss.name = 'WEIGHTUNIT' and ss2.plant_id = bu.plant_id and
       ss2.name = 'CONTAINERRECORDINGACTIVE'

/
create or replace view V_CONSIGNMENTNOTELINES_EDE
 (CONSIGNMENTNOTE_ID, NOTENUMBER, WEEK, DEPARTMENTNUMBER, PROD_CODE, PRODUCTDESC, SIZECODE, DELIVEREDAMOUNT, PRIMARYID, DAYCODE, LANGUAGECODE, WEIGHT, WEIGHINGCODE, WEIGHING_DESC, WEIGHTDECIMALS)
as select pn.consignmentnote_id, pn.notenumber, pn.week,
       dep.departmentnumber,
       vcp.Prod_code,
       (select pd.description from product_desc pd where pd.product_id = vcp.product_id and pd.language_id= lan.language_id) productdesc,
       (select sd.code from sizedefinition sd where sd.sizedefinition_id = pnl.sizedefinition_id) sizecode,
       pnl.deliveredamount,
       cnt.primaryid,
       (select min(dc.code) from day_desc dc where dc.day_id = pn.daynumber) daycode,
       lan.code languagecode,
       (pnc.grossweight - pnc.tareweight) weight,
       (select w.code from weighingcategory_link w where pnc.weighingcategory_id = w.weighingcategory_id) weighingcode,
       (select wd.description from weighingcategory_link_desc wd where pnc.weighingcategory_id = wd.weighingcategory_link_id and wd.language_id = lan.language_id) weighing_desc,
       pnc.weightdecimals
from packingnote pn
       left outer join (packingnotecontainer pnc inner join container cnt on pnc.container_id = cnt.container_id) on pn.packingnote_id = pnc.packingnote_id and pnc.grossweight - pnc.tareweight > 0
       left outer join (packingnoteline pnl inner join v_consignote_prod_ede vcp on pnl.packingnoteline_id = vcp.packingnoteline_id) on pn.packingnote_id = pnl.packingnote_id
     , distributionpoint dp, department dep
     --, packingnoteline pnl
     --, v_consignote_prod_ede vcp
     , languages lan
where pn.distributionpoint_id = dp.distributionpoint_id
      and dp.department_id = dep.department_id
      --and pn.packingnote_id = pnl.packingnote_id
      --and pnl.packingnoteline_id = vcp.packingnoteline_id

/
create or replace view V_CONSIGNMENTNOTE_ECL
 (PLANTNAME, CUSTOMERNAME, SIGNATUREREQUIRED, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTPHONENO, PLANTFAXNO, CONSIGNMENTNOTE_ID, EMAIL, CONSIGNMENTNOTENUMBER, CUSTOMERREF, DNCOMMENT, ROUTENUMBER, ROUTEDESCRIPTION, CUSTOMERNUMBER, LEGACYCUSTOMERNUMBER, CUSTOMERSTREET, CUSTOMERSTREET2, CUSTOMERZIPCODE, CUSTOMERCITY, DELIVERYDATE, DEPARTMENT_LINK_ID, DELIVERYPOINT_LINK_ID, EXTERNALORDERNUMBER, DEL_POINT_CODE, DEPARTMENTNUMBER, DEPARTMENTDESC, BU_CODE, SCANSONDELIVERYNOTE
, LAYOUTCODE, PLANTGLOBALREMARK)
as select
  plant.name PlantName, cu.name customername, cu.signaturerequired, address.street plantstreet, address.street2 plantstreet2, address.zipcode plantzipcode, address.city plantcity
, plant.phoneno plantphoneno, plant.faxno plantfaxno, CN.CONSIGNMENTNOTE_ID, plant.email,
 cn.consignmentnotenumber,
 (select listagg(dv.reference, ', ') WITHIN GROUP (order BY dv.reference) from v_dvreference  dv where dv.consignmentnote_id= cn.consignmentnote_id) customerref,
 (select listagg(pn.remark, ', ') WITHIN GROUP (order BY pn.remark) from v_dnremark pn where pn.consignmentnote_id= cn.consignmentnote_id) dncomment, route.routenumber, route.description routeDescription
, cu.customernumber, cu.legacycustomernumber
, ads.street customerstreet, ads.street2 customerstreet2, ads.zipcode customerzipcode, ads.city customercity
, CN.DELIVERYDATE
, cn.department_link_id, cn.deliverypoint_link_id, cn.externalordernumber
, dp.code del_point_code
, d.departmentnumber, d.description departmentdesc
, bu.code BU_code, cu.scansondeliverynote
, (select fl.code from formlayout fl where fl.formlayout_id = cu.consignmentnotelayout_id) layoutcode
, (select dnrd.description from deliverynoteremark dnr, deliverynoteremark_desc dnrd where dnr.deliverynoteremark_id = dnrd.deliverynoteremark_id and dnr.plant_id = plant.plant_id and dnr.dateactive <= sysdate and dnr.dateinactive > sysdate and dnrd.language_id = cu.language_id) plantGlobalRemark
from
  ConsignmentNote cn
     left outer join route on cn.route_id = route.route_id
     left outer join department d on d.department_id = cn.department_link_id
     left outer join deliverypoint dp on dp.deliverypoint_id = cn.deliverypoint_link_id
, businessunit bu, plant, address, address ads, customer cu
where cn.businessunit_id = bu.businessunit_id
and bu.plant_id = plant.plant_id
and plant.address_id = address.address_id
and cn.customer_link_id = cu.customer_id
and cu.visitaddress_id = ads.address_id
and cu.consignmentnotelevel > 0

/
create or replace view V_CONTACTDETAILS
 (NEWDATE, CUSTOMERNUMBER, CUSTOMERNAME, PLANT_ID, CATEGORYCODE, CATEGORYDESC, ACTIONDATE, CALLNUMBER, STATUS, PRIORITY, CREATEDBYUSERNAME, FOLLOWUPBYUSERNAME, CONTACTNOTES, FOLLOWUPNOTES, LANGUAGECODE)
as select
  ct.newdate, cu.customernumber, cu.name customerName, vx.plant_id
, 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
, case ct.status when 1 then ct.newdate
                 when 2 then ct.followupdate
                 when 3 then ct.inprogressdate
                 when 4 then ct.closedate end ActionDate
, 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
    left outer join SYSTEMUSER FSY on CT.FOLLOWUPBYUSER_ID = FSY.SYSTEMUSER_ID
, contactcategory cty, SYSTEMUSER CSY, customer cu
, v_contactpercategory_aux vx
, languages
where
    ct.contactcategory_id  = cty.contactcategory_id
AND CT.CREATEDBYUSER_ID = CSY.SYSTEMUSER_ID
and ct.customer_link_id = cu.customer_id
    and cu.customer_id = vx.customer_id
    and ct.businessunit_id = vx.businessunit_id

/
create or replace view V_CONTACTPERCATEGORY
 (CALLNUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CITY, PLANT_ID, BUSINESSUNIT_ID, STATUS, PRIORITY, EVALDATE, CATEGORYCODE, CATEGORYDESC, QUANTITY, 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
                 when 3 then ct.inprogressdate
                 when 4 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
, languages.code languageCode
from
  contact ct, contactcategory cty
, customer cu
, v_contactpercategory_aux vx
, address, languages
where
    ct.contactcategory_id = cty.contactcategory_id
and ct.customer_link_id = cu.customer_id
    and cu.visitaddress_id = address.address_id
        and cu.customer_id = vx.customer_id
        and ct.businessunit_id = vx.businessunit_id
group by
  cu.customernumber, cu.name,address.city, vx.plant_id, vx.businessunit_id
, ct.status, CT.PRIORITY, ct.newdate, ct.followupdate, ct.inprogressdate, ct.closedate
, cty.code, cty.contactcategory_id
, languages.language_id, languages.code,ct.callnumber

/
create or replace view V_CONTACTPERCATEGORY_ECL
 (CALLNUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CITY, PLANT_ID, BUSINESSUNIT_ID, CONTACTNOTES, FOLLOWUPNOTES, STATUS, PRIORITY, EVALDATE, CATEGORYCODE, CATEGORYDESC, QUANTITY, LANGUAGECODE)
as select distinct -- 1 --
  ct.callnumber,cu.customernumber, cu.name customerName, address.city, vx.plant_id, vx.businessunit_id,  ct.contactnotes, ct.followupnotes
, ct.status, CT.PRIORITY --  1 = Low, 2 = Medium, 3 = High
, case ct.status when 1 then ct.newdate
                 when 2 then ct.followupdate
                 when 3 then ct.inprogressdate
                 when 4 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
, languages.code languageCode
from
  contact ct, contactcategory cty
, customer cu
, v_contactpercategory_aux vx
, address, languages
where
    ct.contactcategory_id = cty.contactcategory_id
and ct.customer_link_id = cu.customer_id
    and cu.visitaddress_id = address.address_id
        and cu.customer_id = vx.customer_id
        and ct.businessunit_id = vx.businessunit_id
group by
  cu.customernumber, cu.name,address.city, vx.plant_id, vx.businessunit_id
, ct.status, CT.PRIORITY, ct.newdate, ct.followupdate, ct.inprogressdate, ct.closedate
, cty.code, cty.contactcategory_id
, languages.language_id, languages.code,ct.callnumber, ct.contactnotes, ct.followupnotes

/
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_CONTRACTEXPIRATIONROUTE_HUE
 (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
, (select max(r.description) from route r, routestop rs where r.route_id = rs.route_id
    and r.routenumber = cu.routenumber and rs.customer_id = cu.customer_id
    and r.drivingday_id = cu.drivingday_id) 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_GETSTOPANDDELSCHEMEHUE(cu.customer_id, cu.routenumber) 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_hue 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_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, CUSTOMER_NAME
, CUSTOMERNUMBER, CITY, PROD_CODE, PROD_DESC, SIZEDEF_DESC, FINISH_DESC, QUANTITY, 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)
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
, (select crr.invoiceamountdecimals from currency crr where cus.currency_id=crr.currency_id) invoiceamountdecimals
, (select crr.decimals from currency crr where cus.currency_id=crr.currency_id) pricedecimals
, cdn.closingdate--, cbi.residentialservicesallowed
, crs.customerclients, cr.laundryservicesparticipant
, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber, cli.clientnumber
, cli.searchname, cli.name Client_name
, 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 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--SUM(ctx.TAXAMOUNT) 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
from clientdeliverynoteline cdl
left outer join invoiceline il
     join (invoiceheader ih
            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
, client cli --left outer join clientbillinginfo cbi on cbi.client_id = cli.client_id
left outer join clientresident cr on cli.client_id=cr.client_id
, v_ClientDepartment v
, address a, 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
, clientdeliverynote cdn
  left outer join invoiceline ilh
       join invoiceheader ihh on (ihh.invoiceheader_id = ilh.invoiceheader_id)
  on cdn.invoiceline_id = ilh.invoiceline_id
  left outer join clientdeliverynotetax ctx
	     join taxgroup txg on (ctx.taxgroup_id = txg.taxgroup_id)
	ON ctx.CLIENTDELIVERINOTE_ID = cdn.ClientDeliveryNote_ID
, languages l
, product p, sizedefinition s, finishingmethod f
where cdl.clientdeliverinote_id = cdn.clientdeliverynote_id
and cdn.customer_link_id = cus.customer_id
and cli.client_id = cdn.client_link_id
and cus.visitaddress_id = a.address_id
and cdl.product_link_id = p.product_id
and cdl.sizedefinition_link_id = s.sizedefinition_id
and cdl.finishingmethod_id = f.finishingmethod_id
and cli.client_id=v.client_id
and cdn.closingdate is not null
and cus.language_id=l.language_id
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
, (select crr.invoiceamountdecimals from currency crr where cus.currency_id=crr.currency_id) invoiceamountdecimals
, (select crr.decimals from currency crr where cus.currency_id=crr.currency_id) pricedecimals
, cdn.closingdate--, cbi.residentialservicesallowed
, crs.customerclients, cr.laundryservicesparticipant
, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber, cli.clientnumber
, cli.searchname, cli.name Client_name
, 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 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--SUM(ctx.TAXAMOUNT) 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
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
, client cli --left outer join clientbillinginfo cbi on cbi.client_id = cli.client_id
left outer join clientresident cr on cli.client_id=cr.client_id
, v_ClientDepartment v
, address a, customer cus
left outer join Customerresidentialsettings crs on cus.customer_id=crs.customer_id
, clientdeliverynote cdn left outer join invoiceline ilh
       join invoiceheader ihh on (ihh.invoiceheader_id = ilh.invoiceheader_id)
  on cdn.invoiceline_id = ilh.invoiceline_id
  left outer join clientdeliverynotetax ctx
	     join taxgroup txg on (ctx.taxgroup_id = txg.taxgroup_id)
	ON ctx.CLIENTDELIVERINOTE_ID = cdn.ClientDeliveryNote_ID
, languages l
, specialcharge sc
where cdc.clientdeliverinote_id=cdn.clientdeliverynote_id
and cdn.customer_link_id=cus.customer_id
and cli.client_id=cdn.client_link_id
and cus.visitaddress_id=a.address_id
and cdc.specialcharge_id=sc.specialcharge_id
and cli.client_id=v.client_id
and cdn.closingdate is not null
and cus.language_id=l.language_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
, (select crr.invoiceamountdecimals from currency crr where cus.currency_id=crr.currency_id) invoiceamountdecimals
, (select crr.decimals from currency crr where cus.currency_id=crr.currency_id) pricedecimals
, cdn.closingdate--, cbi.residentialservicesallowed
, crs.customerclients, cr.laundryservicesparticipant
, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber, cli.clientnumber
, cli.searchname, cli.name Client_name
, 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, 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--SUM(ctx.TAXAMOUNT) 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
from clientdeliverynote cdn
  left outer join invoiceline il
     join invoiceheader ih on (ih.invoiceheader_id=il.invoiceheader_id)
  on cdn.invoiceline_id=il.invoiceline_id
  left outer join clientdeliverynotetax ctx
	     join taxgroup txg on (ctx.taxgroup_id = txg.taxgroup_id)
	ON ctx.CLIENTDELIVERINOTE_ID = cdn.ClientDeliveryNote_ID
, client cli --left outer join clientbillinginfo cbi on cbi.client_id = cli.client_id
left outer join clientresident cr on cli.client_id=cr.client_id
, v_ClientDepartment v
, address a, customer cus
left outer join Customerresidentialsettings crs on cus.customer_id=crs.customer_id
, languages l
, weighingcategory wc
where cdn.customer_link_id=cus.customer_id
and cli.client_id=cdn.client_link_id
and cus.visitaddress_id=a.address_id
and wc.weighingcategory_id=cdn.weighingcategory_link_id
and cli.client_id=v.client_id
and cdn.closingdate is not null
and cus.language_id=l.language_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--, cbi.residentialservicesallowed
, crs.customerclients, cr.laundryservicesparticipant
, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber, cli.clientnumber
, cli.searchname, cli.name Client_name
, cus.name Customer_name, cus.customernumber, a.city
, ll.code Prod_code
, pqr.preprinted Sizedef_Desc
, pqr.chargeable Prod_Desc
, '11' Finish_desc
, count(*) quantity, 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--SUM(ctx.TAXAMOUNT) 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
from printqueueresidentialitem pqr
left outer join invoiceline il
     join invoiceheader ih on (ih.invoiceheader_id=il.invoiceheader_id)
on pqr.invoiceline_id=il.invoiceline_id
, client cli --left outer join clientbillinginfo cbi on cbi.client_id = cli.client_id
left outer join clientresident cr on cli.client_id=cr.client_id
, v_ClientDepartment v
, address a, customer cus
left outer join Customerresidentialsettings crs on cus.customer_id=crs.customer_id
, currency crr
, clientdeliverynote cdn
  left outer join invoiceline ilh
	     join invoiceheader ihh on (ihh.invoiceheader_id = ilh.invoiceheader_id)
  on cdn.invoiceline_id = ilh.invoiceline_id
  left outer join clientdeliverynotetax ctx
	     join taxgroup txg on (ctx.taxgroup_id = txg.taxgroup_id)
	ON ctx.CLIENTDELIVERINOTE_ID = cdn.ClientDeliveryNote_ID
, languages l
, labellayout ll
where pqr.clientdeliverynote_id=cdn.clientdeliverynote_id
and cdn.customer_link_id=cus.customer_id
and cli.client_id=cdn.client_link_id
and cus.visitaddress_id=a.address_id
and cus.currency_id=crr.currency_id
and pqr.labellayout_id=ll.labellayout_id
and cli.client_id=v.client_id
and cdn.closingdate is not null
and cus.language_id=l.language_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--, cbi.residentialservicesallowed
, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber, 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, cdn.batch_id

/
create or replace view V_COSTSSPECPERCLIENT_LTS
 (LINE_TYPE, L_INVOICELINE_ID, INVOICEHEADER_ID, L_INVOICENUMBER, L_DOCUMENTTYPE, L_INVOICEDATE, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, L_BILLSTREET, L_BILLCITY, L_BILLZIP, PURCHASEORDER, INVOICEFREQUENCYNUMBER, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, STARTWEEK, STARTMONTH, ENDWEEK, ENDMONTH, DELTOCUSTVATNUMBER, IHINVOICEBUSINESSUNIT_ID, CDNINVOICEBUSINESSUNIT_ID, PROCESSBUSINESSUNIT_ID, CUSTOMER_ID, DELIVERYDATE, INVOICEAMOUNTDECIMALS
, PRICEDECIMALS, CLOSINGDATE, CUSTOMERCLIENTS, LAUNDRYSERVICESPARTICIPANT, DEPARTMENTNUMBER, DEP_DESC, ROOMNUMBER, CLIENTDELIVERYNOTENUMBER, CLIENTNUMBER, SEARCHNAME, CLIENT_NAME, ADMINNUMBER, CLIENT_ID, CUSTOMER_NAME, CUSTOMERNUMBER, CITY, CUSTOMER_EXTRANAME, CUSTMER_STR, CUSTOMER_ZIP, CUSTOMER_COUNTRY, PROD_CODE, PROD_DESC, SIZEDEF_DESC, FINISH_DESC, QUANTITY, WEIGHTDECIMALS, IL_PRICE, PRICE, LINEINVOICEBUSINESSUNIT_ID, LANGUAGE_CODE, SIZE_CODE, FINISHING_CODE
, FMWASHTYPE, TAXPERCENTAGE, TAXAMOUNT, TAXRATE, TAXGROUP_CODE, TAXGROUP_DESC, PNNUMBER, CLIENTINVOICECATEG, WEIGHTCODE, CALCULATEDWEIGHT, WEIGHTPRICE, SPECIALPRICE, PLANTNAME, PLANTSTREET, PLANTZIP, PLANTCITY, PLANTPHONE, PLANTFAX, PLANTEMAIL, PLANTWEBSITE, CLIENT_REMARK, INVOICEPLANTCONTACT, INVOICELAYOUTCODE, BATCHDATE)
as select 1 line_type
, il.invoiceline_id l_invoiceline_id, ih.invoiceheader_id invoiceheader_id, ih.invoicenumber l_invoicenumber, ih.documenttype l_documenttype
, ih.invoicedate l_invoicedate
, ih.billtocustomernumber, ih.billtocustomername, ih.street l_billstreet, ih.city l_billcity, ih.zipcode l_billzip, ih.purchaseorder
, ih.invoicefrequency_id invoicefrequencynumber, ih.nextperiodstartdate, ih.nextperiodenddate, ih.nextperiodstartweek, ih.nextperiodendweek, ih.startweek, ih.startmonth, ih.endweek, ih.endmonth
, (select ihextr.deltocustvatnumber from invoiceheaderextrainfo ihextr where ihextr.invoiceheader_id = ih.invoiceheader_id) deltocustvatnumber
, 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 cus.currency_id=crr.currency_id) invoiceamountdecimals
, (select crr.decimals from currency crr where cus.currency_id=crr.currency_id) pricedecimals
, cdn.closingdate--, cbi.residentialservicesallowed
, crs.customerclients, cr.laundryservicesparticipant
, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber, cli.clientnumber
, cli.searchname, cli.name Client_name, cli.adminnumber, cli.client_id
, cus.name Customer_name, cus.customernumber, a.city
, cus.extraname1 customer_extraname, a.street custmer_str, a.zipcode customer_zip
, (select cou.description from country cou where cus.country_id = cou.country_id) customer_country
, 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 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)
  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--SUM(ctx.TAXAMOUNT) TAXAMOUNT
,
         (select case when ih.enddate < tg.startdatetaxrate then tg.oldtaxrate
               else tg.taxrate
               end taxrate
         from taxgroup tg, customer bill
         where il.taxgroupcode = tg.code
               and bill.customer_id = ih.billtocustomer_link_id
               and tg.country_id = bill.country_id) taxrate
, txg.code taxgroup_code, txg.description taxgroup_desc, cus.PNNUMBER
, (select cic.code
   from clientbillinginfo cbi, clientinvoicecategory cic
   where cbi.client_id = cli.client_id
         and cbi.clientinvoicecategory_id = cic.clientinvoicecategory_id) clientinvoicecateg
, (select wc.code from weighingcategory_link wc where wc.weighingcategory_link_id = cdn.weighingcategory_link_id) weightcode
, (cdn.grossweight-cdn.tareweight) calculatedweight
, cdn.weightprice weightprice
,(select wp.price
  from generalwashprice wp, generalpricelist g
  where wp.generalpricelist_id = g.generalpricelist_id
    and g.code = to_char(cus.pnnumber)
    and cdl.product_link_id = wp.product_id
    and cdl.sizedefinition_link_id = wp.sizedefinition_id
    and cdl.finishingmethod_id = wp.finishingmethod_id
    and wp.pricetype = 1
    and wp.startdate = ( select max(x.startdate)
      from generalwashprice x
      where x.generalpricelist_id  = wp.generalpricelist_id
        and x.startdate <= cdn.Deliverydate
        and x.product_id = wp.product_id
        and x.sizedefinition_id = wp.sizedefinition_id
        and x.finishingmethod_id = wp.finishingmethod_id
        and x.pricetype = wp.pricetype )) specialprice
, pp.name plantname, pladdress.street plantstreet
, pladdress.zipcode plantzip, pladdress.city plantcity
, pp.phoneno plantphone, pp.faxno plantfax
, pp.email plantemail, pp.website plantwebsite
, cli.remark client_remark
, (select max(pt.name || ' ' || pt.phoneno)
   from plant pt, businessunit bu, productgroup pg, customeractivities ca
   where pt.plant_id = bu.plant_id
         and ca.invoicebusinessunit_id = bu.businessunit_id
         and pg.activity_id = ca.activity_id
         and pg.productgroup_id = p.productgroup_id
         and ca.customer_id = cus.customer_id) invoiceplantcontact
, (select ihextr.formlayoutcode
   from invoiceheaderextrainfo ihextr
   where ihextr.invoiceheader_id = ih.invoiceheader_id) invoicelayoutcode
, (select ba.batchdate from batch ba where ba.batch_id = cdn.batch_id) batchdate
from clientdeliverynoteline cdl
left outer join invoiceline il
     join invoiceheader ih on (ih.invoiceheader_id=il.invoiceheader_id)
on cdl.invoiceline_id=il.invoiceline_id
, client cli --left outer join clientbillinginfo cbi on cbi.client_id = cli.client_id
left outer join clientresident cr on cli.client_id=cr.client_id
, v_ClientDepartment v
, address a, customer cus
left outer join Customerresidentialsettings crs on cus.customer_id=crs.customer_id
, clientdeliverynote cdn
  left outer join clientdeliverynotetax ctx
       join taxgroup txg on (ctx.taxgroup_id = txg.taxgroup_id)
  ON ctx.CLIENTDELIVERINOTE_ID = cdn.ClientDeliveryNote_ID
, languages l
, product p, sizedefinition s, finishingmethod f
, address pladdress, businessunit bu, plant pp
where cdl.clientdeliverinote_id = cdn.clientdeliverynote_id
and cdn.customer_link_id = cus.customer_id
and cli.client_id = cdn.client_link_id
and cus.visitaddress_id = a.address_id
and cdl.product_link_id = p.product_id
and cdl.sizedefinition_link_id = s.sizedefinition_id
and cdl.finishingmethod_id = f.finishingmethod_id
and cli.client_id=v.client_id
and cdn.closingdate is not null
and cus.language_id=l.language_id
and cdn.processbusinessunit_id = bu.businessunit_id
and bu.plant_id = pp.plant_id
and pp.address_id = pladdress.address_id
union all
select 2 line_type
, il.invoiceline_id l_invoiceline_id, ih.invoiceheader_id invoiceheader_id, ih.invoicenumber l_invoicenumber, ih.documenttype l_documenttype
, ih.invoicedate l_invoicedate
, ih.billtocustomernumber, ih.billtocustomername, ih.street l_billstreet, ih.city l_billcity, ih.zipcode l_billzip, ih.purchaseorder
, ih.invoicefrequency_id invoicefrequencynumber, ih.nextperiodstartdate, ih.nextperiodenddate, ih.nextperiodstartweek, ih.nextperiodendweek, ih.startweek, ih.startmonth, ih.endweek, ih.endmonth
, (select ihextr.deltocustvatnumber from invoiceheaderextrainfo ihextr where ihextr.invoiceheader_id = ih.invoiceheader_id) deltocustvatnumber
, 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 cus.currency_id=crr.currency_id) invoiceamountdecimals
, (select crr.decimals from currency crr where cus.currency_id=crr.currency_id) pricedecimals
, cdn.closingdate--, cbi.residentialservicesallowed
, crs.customerclients, cr.laundryservicesparticipant
, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber, cli.clientnumber
, cli.searchname, cli.name Client_name, cli.adminnumber, cli.client_id
, cus.name Customer_name, cus.customernumber, a.city
, cus.extraname1 customer_extraname, a.street custmer_str, a.zipcode customer_zip
, (select cou.description from country cou where cus.country_id = cou.country_id) customer_country
, 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 weightdecimals, il.price Il_Price, cdc.price
, -2 LineInvoicebusinessunit_id
, l.code Language_code
, '' Size_code, '' Finishing_code,  -1 FMwashtype
, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT--SUM(ctx.TAXAMOUNT) TAXAMOUNT
, null taxrate
, txg.code taxgroup_code, txg.description taxgroup_desc, cus.PNNUMBER
, (select cic.code
   from clientbillinginfo cbi, clientinvoicecategory cic
   where cbi.client_id = cli.client_id
         and cbi.clientinvoicecategory_id = cic.clientinvoicecategory_id) clientinvoicecateg
, (select wc.code from weighingcategory_link wc where wc.weighingcategory_link_id = cdn.weighingcategory_link_id) weightcode
, (cdn.grossweight-cdn.tareweight) calculatedweight
, cdn.weightprice weightprice
, null specialprice
, pp.name plantname, pladdress.street plantstreet
, pladdress.zipcode plantzip, pladdress.city plantcity
, pp.phoneno plantphone, pp.faxno plantfax
, pp.email plantemail, pp.website plantwebsite
, cli.remark client_remark
, (select max(pt.name || ' ' || pt.phoneno)
   from plant pt, businessunit bu, customeractivities ca
   where pt.plant_id = bu.plant_id
         and ca.invoicebusinessunit_id = bu.businessunit_id
         and ca.customer_id = cus.customer_id
         and ca.includenotactivityrelcharges = 'Y') invoiceplantcontact
, (select ihextr.formlayoutcode
   from invoiceheaderextrainfo ihextr
   where ihextr.invoiceheader_id = ih.invoiceheader_id) invoicelayoutcode
, (select ba.batchdate from batch ba where ba.batch_id = cdn.batch_id) batchdate
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
, client cli --left outer join clientbillinginfo cbi on cbi.client_id = cli.client_id
left outer join clientresident cr on cli.client_id=cr.client_id
, v_ClientDepartment v
, address a, customer cus
left outer join Customerresidentialsettings crs on cus.customer_id=crs.customer_id
, clientdeliverynote cdn
  left outer join clientdeliverynotetax ctx
       join taxgroup txg on (ctx.taxgroup_id = txg.taxgroup_id)
  ON ctx.CLIENTDELIVERINOTE_ID = cdn.ClientDeliveryNote_ID
, languages l
, specialcharge sc
, address pladdress, businessunit bu, plant pp
where cdc.clientdeliverinote_id=cdn.clientdeliverynote_id
and cdn.customer_link_id=cus.customer_id
and cli.client_id=cdn.client_link_id
and cus.visitaddress_id=a.address_id
and cdc.specialcharge_id=sc.specialcharge_id
and cli.client_id=v.client_id
and cdn.closingdate is not null
and cus.language_id=l.language_id
and cdn.processbusinessunit_id = bu.businessunit_id
and bu.plant_id = pp.plant_id
and pp.address_id = pladdress.address_id
union all
select 3 line_type
, il.invoiceline_id l_invoiceline_id, ih.invoiceheader_id invoiceheader_id,ih.invoicenumber l_invoicenumber, ih.documenttype l_documenttype
, ih.invoicedate l_invoicedate
, ih.billtocustomernumber, ih.billtocustomername, ih.street l_billstreet, ih.city l_billcity, ih.zipcode l_billzip, ih.purchaseorder
, ih.invoicefrequency_id invoicefrequencynumber, ih.nextperiodstartdate, ih.nextperiodenddate, ih.nextperiodstartweek, ih.nextperiodendweek, ih.startweek, ih.startmonth, ih.endweek, ih.endmonth
, (select ihextr.deltocustvatnumber from invoiceheaderextrainfo ihextr where ihextr.invoiceheader_id = ih.invoiceheader_id) deltocustvatnumber
, 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 cus.currency_id=crr.currency_id) invoiceamountdecimals
, (select crr.decimals from currency crr where cus.currency_id=crr.currency_id) pricedecimals
, cdn.closingdate--, cbi.residentialservicesallowed
, crs.customerclients, cr.laundryservicesparticipant
, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber, cli.clientnumber
, cli.searchname, cli.name Client_name, cli.adminnumber, cli.client_id
, cus.name Customer_name, cus.customernumber, a.city
, cus.extraname1 customer_extraname, a.street custmer_str, a.zipcode customer_zip
, (select cou.description from country cou where cus.country_id = cou.country_id) customer_country
, 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, 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--SUM(ctx.TAXAMOUNT) TAXAMOUNT
, (select tg.taxrate
   from taxgroup tg, weighingcategorytax wct
   where tg.taxgroup_id = wct.taxgroup_id
         and wct.weighingcategory_id = wc.weighingcategory_id) taxrate
, txg.code taxgroup_code, txg.description taxgroup_desc, cus.PNNUMBER
, (select cic.code
   from clientbillinginfo cbi, clientinvoicecategory cic
   where cbi.client_id = cli.client_id
         and cbi.clientinvoicecategory_id = cic.clientinvoicecategory_id) clientinvoicecateg
, (select wc.code from weighingcategory_link wc where wc.weighingcategory_link_id = cdn.weighingcategory_link_id) weightcode
, (cdn.grossweight-cdn.tareweight) calculatedweight
, cdn.weightprice weightprice
, null specialprice
, pp.name plantname, pladdress.street plantstreet
, pladdress.zipcode plantzip, pladdress.city plantcity
, pp.phoneno plantphone, pp.faxno plantfax
, pp.email plantemail, pp.website plantwebsite
, cli.remark client_remark
, (select max(pt.name || ' ' || pt.phoneno)
   from plant pt, businessunit bu, productgroup pg, customeractivities ca
   where pt.plant_id = bu.plant_id
         and ca.invoicebusinessunit_id = bu.businessunit_id
         and wc.activity_id = ca.activity_id
         and ca.customer_id = cus.customer_id) invoiceplantcontact
, (select ihextr.formlayoutcode
   from invoiceheaderextrainfo ihextr
   where ihextr.invoiceheader_id = ih.invoiceheader_id) invoicelayoutcode
, (select ba.batchdate from batch ba where ba.batch_id = cdn.batch_id) batchdate
from clientdeliverynote cdn
  left outer join invoiceline il
     join invoiceheader ih on (ih.invoiceheader_id=il.invoiceheader_id)
  on cdn.invoiceline_id=il.invoiceline_id
  left outer join clientdeliverynotetax ctx
       join taxgroup txg on (ctx.taxgroup_id = txg.taxgroup_id)
  ON ctx.CLIENTDELIVERINOTE_ID = cdn.ClientDeliveryNote_ID
, client cli --left outer join clientbillinginfo cbi on cbi.client_id = cli.client_id
left outer join clientresident cr on cli.client_id=cr.client_id
, v_ClientDepartment v
, address a, customer cus
left outer join Customerresidentialsettings crs on cus.customer_id=crs.customer_id
, languages l
, weighingcategory wc
, address pladdress, businessunit bu, plant pp
where cdn.customer_link_id=cus.customer_id
and cli.client_id=cdn.client_link_id
and cus.visitaddress_id=a.address_id
and wc.weighingcategory_id=cdn.weighingcategory_link_id
and cli.client_id=v.client_id
and cdn.closingdate is not null
and cus.language_id=l.language_id
and cdn.processbusinessunit_id = bu.businessunit_id
and bu.plant_id = pp.plant_id
and pp.address_id = pladdress.address_id
union all
select  4 line_type
, il.invoiceline_id l_invoiceline_id,ih.invoiceheader_id invoiceheader_id,ih.invoicenumber l_invoicenumber, ih.documenttype l_documenttype
, ih.invoicedate l_invoicedate
, ih.billtocustomernumber, ih.billtocustomername, ih.street l_billstreet, ih.city l_billcity, ih.zipcode l_billzip, ih.purchaseorder
, ih.invoicefrequency_id invoicefrequencynumber, ih.nextperiodstartdate, ih.nextperiodenddate, ih.nextperiodstartweek, ih.nextperiodendweek, ih.startweek, ih.startmonth, ih.endweek, ih.endmonth
, (select ihextr.deltocustvatnumber from invoiceheaderextrainfo ihextr where ihextr.invoiceheader_id = ih.invoiceheader_id) deltocustvatnumber
, 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--, cbi.residentialservicesallowed
, crs.customerclients, cr.laundryservicesparticipant
, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber, cli.clientnumber
, cli.searchname, cli.name Client_name, max(cli.adminnumber) adminnumber, cli.client_id
, cus.name Customer_name, cus.customernumber, a.city
, cus.extraname1 customer_extraname, a.street custmer_str, a.zipcode customer_zip
, (select cou.description from country cou where cus.country_id = cou.country_id) customer_country
, ll.code Prod_code
, pqr.preprinted Sizedef_Desc
, pqr.chargeable Prod_Desc
, '11' 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--SUM(ctx.TAXAMOUNT) TAXAMOUNT
, null taxrate
, txg.code taxgroup_code, txg.description taxgroup_desc, max(cus.PNNUMBER) PNNUMBER
, (select cic.code
   from clientbillinginfo cbi, clientinvoicecategory cic
   where cbi.client_id = cli.client_id
         and cbi.clientinvoicecategory_id = cic.clientinvoicecategory_id) clientinvoicecateg
, (select wc.code from weighingcategory_link wc where wc.weighingcategory_link_id = cdn.weighingcategory_link_id) weightcode
, (cdn.grossweight-cdn.tareweight) calculatedweight
, cdn.weightprice weightprice
, il.price specialprice
, pp.name plantname, pladdress.street plantstreet
, pladdress.zipcode plantzip, pladdress.city plantcity
, pp.phoneno plantphone, pp.faxno plantfax
, pp.email plantemail, pp.website plantwebsite
, cli.remark client_remark
, (select max(pt.name || ' ' || pt.phoneno)
   from plant pt, businessunit bu, customeractivities ca
   where pt.plant_id = bu.plant_id
         and ca.invoicebusinessunit_id = bu.businessunit_id
         and ca.customer_id = cus.customer_id
         and ca.includenotactivityrelcharges = 'Y') invoiceplantcontact
, (select ihextr.formlayoutcode
   from invoiceheaderextrainfo ihextr
   where ihextr.invoiceheader_id = ih.invoiceheader_id) invoicelayoutcode
, (select ba.batchdate from batch ba where ba.batch_id = cdn.batch_id) batchdate
from printqueueresidentialitem pqr
left outer join invoiceline il
     join invoiceheader ih on (ih.invoiceheader_id=il.invoiceheader_id)
on pqr.invoiceline_id=il.invoiceline_id
, client cli --left outer join clientbillinginfo cbi on cbi.client_id = cli.client_id
left outer join clientresident cr on cli.client_id=cr.client_id
, v_ClientDepartment v
, address a, customer cus
left outer join Customerresidentialsettings crs on cus.customer_id=crs.customer_id
, currency crr
, clientdeliverynote cdn
  left outer join clientdeliverynotetax ctx
       join taxgroup txg on (ctx.taxgroup_id = txg.taxgroup_id)
  ON ctx.CLIENTDELIVERINOTE_ID = cdn.ClientDeliveryNote_ID
, languages l
, labellayout ll
, address pladdress, businessunit bu, plant pp
where pqr.clientdeliverynote_id=cdn.clientdeliverynote_id
and cdn.customer_link_id=cus.customer_id
and cli.client_id=cdn.client_link_id
and cus.visitaddress_id=a.address_id
and cus.currency_id=crr.currency_id
and pqr.labellayout_id=ll.labellayout_id
and cli.client_id=v.client_id
and cdn.closingdate is not null
and cus.language_id=l.language_id
and cdn.processbusinessunit_id = bu.businessunit_id
and bu.plant_id = pp.plant_id
and pp.address_id = pladdress.address_id
group by ll.labellayout_id, il.invoiceline_id, pqr.chargeable , pqr.preprinted
, ih.invoiceheader_id , ih.invoicenumber, ih.invoicedate, 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.client_id
, cus.name , cus.customernumber, cus.customer_id, cus.extraname1, a.city, a.street, a.zipcode, cus.country_id
, ll.code, il.price, pqr.price, cdn.invoicebusinessunit_id, l.code
, ih.documenttype
, crr.invoiceamountdecimals, crr.decimals, crs.customerclients, cr.laundryservicesparticipant
, pqr.invoicebusinessunit_id
, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT, txg.code, txg.description, cli.flag_id
, cdn.weighingcategory_link_id, cdn.grossweight, cdn.tareweight, cdn.weightprice
, pp.name, pladdress.street, pladdress.zipcode, pladdress.city, pp.phoneno, pp.faxno
, pp.email, pp.website, cli.remark, ih.purchaseorder, ih.billtocustomernumber, ih.billtocustomername, ih.street, ih.city, ih.zipcode
, ih.invoicefrequency_id, ih.startweek, ih.startmonth, ih.endweek, ih.endmonth
, ih.nextperiodstartdate, ih.nextperiodenddate, ih.nextperiodstartweek, ih.nextperiodendweek, cdn.batch_id, pp.plant_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)
as SELECT RP.NUMBER_VALUE2 DELINQUENCY_GROUP, --COALESCE(GET_DELINQUENT_AMOUNT(CU.CUSTOMER_ID, RP.NUMBER_VALUE2, RP.DATE_VALUE1, RP.DATE_VALUE2),0)
  COALESCE(RP.NUMBER_VALUE6, 0)+COALESCE(RP.NUMBER_VALUE7, 0)+COALESCE(RP.NUMBER_VALUE8, 0)+COALESCE(RP.NUMBER_VALUE9, 0) DELINQUENTAMOUNT,
  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) 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,
  (SELECT CP.NAME FROM CONTACTPERSON CP WHERE CP.CUSTOMER_ID = CU.CUSTOMER_ID AND CP.INVOICECONTACTPERSON = 'Y') CONTACTPERSONNAME,
  (SELECT CP.CONTACTPERSONNUMBER FROM CONTACTPERSON CP WHERE CP.CUSTOMER_ID = CU.CUSTOMER_ID AND CP.INVOICECONTACTPERSON = 'Y') CCONTACTPERSONNUMBER,
  AD.STREET, AD.STREET2, AD.HOUSENUMBER,
  AD.CITY, AD.STATE, AD.ZIPCODE,
  GETCURRENTDATE() CURRENTDATE,
  RP.DATE_VALUE1 STARTDATE, RP.DATE_VALUE2 ENDDATE,
  CR.INVOICEAMOUNTDECIMALS,
  RP.REPORTPARAM_ID
/*, (SELECT L.CODE FROM LANGUAGES L WHERE CU.LANGUAGE_ID = L.LANGUAGE_ID) LANGUAGE_CODE
, (SELECT MAX(SS.VALUE) FROM SYSTEMSETTING SS
WHERE RP.NUMBER_VALUE3 = SS.PLANT_ID AND SS.NAME = 'COMPANYCODE') COMPANYCODE
, (SELECT E.NAME FROM EMPLOYEE E WHERE E.EMPLOYEE_ID = CBI.COLLECTIONRESPONSIBLE_ID) COLLECTIONRESPONSIBLE
, X.STREET PLANTSTREET, X.STREET2 PLANTSTREET2, X.CITY PLANTCITY, X.STATE PLANTSTATE, X.ZIPCODE PLANTZIPCODE
, P.PHONENO PLANTPHONE, P.FAXNO PLANTFAX, P.EMAIL PLANTEMAIL*/
FROM CUSTOMER CU, CURRENCY CR, ADDRESS AD, CUSTOMERBILLINGINFO CBI,
  REPORTPARAM RP, PLANT P, ADDRESS X
WHERE RP.NUMBER_VALUE = CU.CUSTOMER_ID
  AND CU.CURRENCY_ID = CR.CURRENCY_ID
  AND CU.INVOICEADDRESS_ID = AD.ADDRESS_ID
  AND CU.CUSTOMER_ID = CBI.CUSTOMER_ID
  AND RP.NUMBER_VALUE3 = P.PLANT_ID
      AND P.ADDRESS_ID = X.ADDRESS_ID

/
create or replace view V_DELINQUENCYLETTER_AMM
 (DELINQUENCY_GROUP, DELINQUENTAMOUNT, CURRENTAMOUNT, LASTSTATEMENTAMOUNT, UNNAPLIEDCREDIT, CUSTOMERNUMBER, CUSTOMERNAME, SENDSTATEMENT, CUSTOMER_ID, CONTACTPERSONNAME, CCONTACTPERSONNUMBER, CONTACTPERSONFAX, STREET, STREET2, HOUSENUMBER, CITY, STATE, ZIPCODE, CURRENTDATE, STARTDATE, ENDDATE, INVOICEAMOUNTDECIMALS, REPORTPARAM_ID, LANGUAGE_CODE, COMPANYCODE, COLLECTIONRESPONSIBLE, PLANTSTREET, PLANTSTREET2, PLANTCITY, PLANTSTATE, PLANTZIPCODE, PLANTPHONE, PLANTFAX, PLANTEMAIL, UNNAPLIEDDEBIT
, BU_CODE, EXT, SICCODE, DUEINVOICES)
as SELECT RP.NUMBER_VALUE2 DELINQUENCY_GROUP, --COALESCE(GET_DELINQUENT_AMOUNT(CU.CUSTOMER_ID, RP.NUMBER_VALUE2, RP.DATE_VALUE1, RP.DATE_VALUE2),0)
  COALESCE(RP.NUMBER_VALUE6, 0)+COALESCE(RP.NUMBER_VALUE7, 0)+COALESCE(RP.NUMBER_VALUE8, 0)+COALESCE(RP.NUMBER_VALUE9, 0) DELINQUENTAMOUNT,
  rp.number_value5 CURRENTAMOUNT,
  COALESCE((SELECT SUM(IH.PREBILLAMOUNT) FROM V_DELINQUENCYLETTER_IH DIH, INVOICEHEADER IH
    WHERE DIH.INVOICEDATE = IH.INVOICEDATE
      AND DIH.CUSTOMER_ID = coalesce(ih.deltocustomer_link_id, ih.billtocustomer_link_id)
      AND coalesce(ih.deltocustomer_link_id, ih.billtocustomer_link_id) = CU.CUSTOMER_ID),0) LASTSTATEMENTAMOUNT,
  COALESCE((SELECT SUM(AR.AMOUNT - AR.Totalappliedamount) FROM ARTRANSACTION AR, Artransactiontype ART
    WHERE coalesce(ar.deltocustomer_link_id, 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,
  (SELECT CP.NAME FROM CONTACTPERSON CP WHERE CP.CUSTOMER_ID = CU.CUSTOMER_ID AND CP.INVOICECONTACTPERSON = 'Y') CONTACTPERSONNAME,
  (SELECT CP.CONTACTPERSONNUMBER FROM CONTACTPERSON CP WHERE CP.CUSTOMER_ID = CU.CUSTOMER_ID AND CP.INVOICECONTACTPERSON = 'Y') CCONTACTPERSONNUMBER,
  (SELECT CP.Fax FROM CONTACTPERSON CP WHERE CP.CUSTOMER_ID = CU.CUSTOMER_ID AND CP.INVOICECONTACTPERSON = 'Y') CONTACTPERSONFAX,
  AD.STREET, AD.STREET2, AD.HOUSENUMBER,
  AD.CITY, AD.STATE, AD.ZIPCODE,
  GETCURRENTDATE() CURRENTDATE,
  RP.DATE_VALUE1 STARTDATE, RP.DATE_VALUE2 ENDDATE,
  CR.INVOICEAMOUNTDECIMALS,
  RP.REPORTPARAM_ID
, (SELECT L.CODE FROM LANGUAGES L WHERE CU.LANGUAGE_ID = L.LANGUAGE_ID) LANGUAGE_CODE
, (SELECT MAX(SS.VALUE) FROM SYSTEMSETTING SS
WHERE RP.NUMBER_VALUE3 = SS.PLANT_ID AND SS.NAME = 'COMPANYCODE') COMPANYCODE
, (SELECT E.NAME FROM EMPLOYEE E WHERE E.EMPLOYEE_ID = CBI.COLLECTIONRESPONSIBLE_ID) COLLECTIONRESPONSIBLE
, X.STREET PLANTSTREET, X.STREET2 PLANTSTREET2, X.CITY PLANTCITY, X.STATE PLANTSTATE, X.ZIPCODE PLANTZIPCODE
, P.PHONENO PLANTPHONE, P.FAXNO PLANTFAX, P.EMAIL PLANTEMAIL
,  COALESCE((SELECT SUM(AR.AMOUNT - AR.Totalappliedamount) FROM ARTRANSACTION AR, Artransactiontype ART
    WHERE coalesce(ar.deltocustomer_link_id, AR.BILLTOCUSTOMER_LINK_ID) = CU.CUSTOMER_ID
      AND AR.DEBITCREDIT = 'D'--      AND AR.CLOSINGTRANSACTION_ID IS NULL
      and ar.isopen_yn = 'Y' and ar.artransactiontype_id = art.artransactiontype_id and art.typenumber <> 2),0) UNNAPLIEDDEBIT
, rp.string_value Bu_code
, (SELECT ef.code FROM EMPLOYEE E, Employeefunction Ef WHERE ef.employeefunction_id = e.employeefunction_id AND E.EMPLOYEE_ID = CBI.COLLECTIONRESPONSIBLE_ID) ext
, cu.siccode
, (SELECT MAX(getdatediff(rp.date_value1, v.duedate))--COUNT(1)
FROM V_DELINQUENCYLETTER_DET v WHERE rp.reportparam_id = v.reportparam_id AND cu.customer_id = v.billtocustomer_link_id
AND getdatediff(rp.date_value1, v.duedate) IN (7, 14)) DueInvoices
FROM CUSTOMER CU, CURRENCY CR, ADDRESS AD, CUSTOMERBILLINGINFO CBI,
  REPORTPARAM RP, PLANT P, ADDRESS X, Plantcompany pc
WHERE RP.NUMBER_VALUE = CU.CUSTOMER_ID
  AND CU.CURRENCY_ID = CR.CURRENCY_ID
  AND CU.Visitaddress_Id = AD.ADDRESS_ID
  AND CU.Debtor_Id = CBI.CUSTOMER_ID
  AND RP.NUMBER_VALUE3 = P.PLANT_ID
      AND Pc.ADDRESS_ID = X.ADDRESS_ID
  AND p.plant_id = pc.plant_id--  AND (cu.siccode IS NULL OR cu.siccode <> 'XXXX')

/
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_DELIVERYHISTORY_FIS
 (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, CIRCINV, MINTURNAROUND)
as SELECT DELIVERYHISTORY.Processbusinessunit_Id
,      CUSTOMER_LINK.CUSTOMER_ID
,      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
,      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
,      parentproduct.CODE parentproductcode
,      ( SELECT E.DESCRIPTION
         FROM   PRODUCT_LINK_DESC E
         WHERE  E.PRODUCT_LINK_ID = DELIVERYHISTORY.PARENTPRODUCT_LINK_ID
            AND E.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) parentproductdescription
,      DELIVERYHISTORY.PACKINDICATION
,      pack.CODE packcode
,      ( SELECT F.DESCRIPTION
         FROM   PRODUCT_LINK_DESC F
         WHERE  F.PRODUCT_LINK_ID = DELIVERYHISTORY.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
,      PRODUCT.THEORETICALWEIGHT
,      PRODUCT.typeofmerchandise
,      PRODUCT.MODEL
,      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
,      FINISHINGMETHOD.CODE finishingmethodcode
,      ( SELECT D.DESCRIPTION
         FROM   FINISHINGMETHOD_DESC D
         WHERE  D.FINISHINGMETHOD_ID = DELIVERYHISTORY.FINISHINGMETHOD_ID
            AND D.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODdescription
,      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.PARENTPACKPRODUCT_LINK_ID
,      DELIVERYHISTORY.PARENTPRODUCT_LINK_ID
,      PROCESSBU.CODE processbucode
,      PROCESSBU.DESCRIPTION processbudescription
,      INVOICEBU.CODE invoicebucode
,      INVOICEBU.DESCRIPTION invoicebudescription
,      DELIVERYHISTORY.SYSTEMUSER_ID
,      DELIVERYHISTORY.TIMESTAMP
,      CUSTOMER_LINK.LANGUAGECODE CUSTOMERLANGUAGECODE
,      LANGUAGES.CODE LANGUAGECODE
,      ( select sum(ciq.quantity)
         from   v_circulatinginventoryqty ciq
         where  CUSTOMER_LINK.CUSTOMERNUMBER = CIQ.CUSTOMERNUMBER
            AND DEPARTMENT_LINK.DEPARTMENTNUMBER = CIQ.DEPARTMENTNUMBER
            AND DISTRIBUTIONPOINT_LINK.DISTRIBUTIONPOINTNUMBER = CIQ.DISTRIBUTIONPOINTNUMBER
            AND FINISHINGMETHOD.CODE = CIQ.FINISHING_CODE
            AND LANGUAGES.CODE = CIQ.LANGUAGE_CODE
            AND DELIVERYHISTORY.Processbusinessunit_Id = CIQ.BUSINESSUNIT_ID
            AND PRODUCT_LINK.CODE = CIQ.PRODUCT_CODE
            AND SIZEDEFINITION_LINK.CODE = CIQ.SIZEDEF_CODE
            and sysdate >= CIQ.ADJUSTMENTDATE
            AND CIQ.ADJUSTMENTDATE <=(select MAX(CIQ2.ADJUSTMENTDATE)
                                     from   v_circulatinginventoryqty ciq2
                                     where  CUSTOMER_LINK.CUSTOMERNUMBER = CIQ2.CUSTOMERNUMBER
                                        AND DEPARTMENT_LINK.DEPARTMENTNUMBER = CIQ2.DEPARTMENTNUMBER
                                        AND DISTRIBUTIONPOINT_LINK.DISTRIBUTIONPOINTNUMBER = CIQ2.DISTRIBUTIONPOINTNUMBER
                                        AND FINISHINGMETHOD.CODE = CIQ2.FINISHING_CODE
                                        AND LANGUAGES.CODE = CIQ2.LANGUAGE_CODE
                                        AND DELIVERYHISTORY.Processbusinessunit_Id = CIQ2.BUSINESSUNIT_ID
                                        AND PRODUCT_LINK.CODE = CIQ2.PRODUCT_CODE
                                        AND SIZEDEFINITION_LINK.CODE = CIQ2.SIZEDEF_CODE
                                        and sysdate >= CIQ2.ADJUSTMENTDATE )
            ) CIRCINV
, plpc.minimumturnaround MINTURNAROUND
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
,      CUSTOMER_LINK
,      DEPARTMENT_LINK
,      DISTRIBUTIONPOINT_LINK
,      SIZEDEFINITION_LINK
,      BUSINESSUNIT PROCESSBU
,      BUSINESSUNIT INVOICEBU
,      FINISHINGMETHOD
,      productlistpercustomer plpc
,      LANGUAGES
,      PRODUCT_LINK parentproduct
,      PRODUCT_LINK pack
,      PRODUCT_LINK
          LEFT OUTER JOIN PRODUCTGROUP ON (PRODUCT_LINK.PRODUCTGROUPCODE = PRODUCTGROUP.CODE)
WHERE  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_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.PARENTPACKPRODUCT_LINK_ID = pack.PRODUCT_LINK_ID
   AND DELIVERYHISTORY.SIZEDEFINITION_LINK_ID = SIZEDEFINITION_LINK.SIZEDEFINITION_LINK_ID
   AND DELIVERYHISTORY.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
   AND DELIVERYHISTORY.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
   AND FINISHINGMETHOD.FINISHINGMETHOD_ID = DELIVERYHISTORY.FINISHINGMETHOD_ID
   AND PRODUCT.PRODUCT_ID = PRODUCTSIZE.PRODUCT_ID
   AND SIZEDEFINITION.SIZEDEFINITION_ID = PRODUCTSIZE.SIZEDEFINITION_ID
	 and PLPC.CUSTOMER_ID = CUSTOMER_LINK.CUSTOMER_ID
   AND PLPC.PRODUCT_ID = PRODUCT_LINK.PRODUCT_ID
   AND PLPC.SIZEDEFINITION_ID = SIZEDEFINITION_LINK.SIZEDEFINITION_ID
   AND PLPC.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
   and DELIVERYHISTORY.Deliverydate between plpc.dateactive and plpc.dateinactive

/
create or replace view V_DELIVERYNOTEAPPENDIX_NAF
 (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
, LANGUAGECODE, DEP_NUMBER, DEP_DESCRIPTION, FREEOFCHARGEREASON_ID, PRICEFACTOR, STATUS_ID, PRICESUM)
as select 1 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, (select prd.code from product prd where pnl.product_id = prd.product_id ))  customcode,
       nvl(pnl.customdescription,
            (select product_desc.description
              from   product_desc
              where  product_desc.product_id = pnl.product_id
              and    product_desc.language_id = languages.language_id)) customdesc,
        (select sz.code from sizedefinition sz where pnl.sizedefinition_id = sz.sizedefinition_id) sizecode,
       pnl.deliveredamount, pnl.packingnoteline_id,
       (select sum(packingnotecontainer.grossweight - packingnotecontainer.tareweight)
         from   packingnotecontainer
         where  pn.packingnote_id = packingnotecontainer.packingnote_id
         group  by pn.packingnote_id) weight,
       (select max(packingnotecontainer.weightdecimals)
         from   packingnotecontainer
         where  pn.packingnote_id = packingnotecontainer.packingnote_id) weightdecimals,
       (select max(l.price)
         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 = '*'))) price,
       (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    (ilp.sizedefinition_link_id = pnl.sizedefinition_id or
               ilp.sizedefinition_link_id =
               (select sizedefinition.sizedefinition_id
                  from   sizedefinition
                  where  sizedefinition.code = '*'))) discountpercentage,       -- total, to be calculated in the report!
       currency.code currencycode, currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals, 0 pnnotininvoice, pn.remark,
       (select ss.value from systemsetting ss where plant.plant_id = ss.plant_id and ss.name = 'WEIGHTUNIT') weightunit,
       languages.code languagecode, 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, pn.status_id
, (select sum(vdeln.WeightPrice) from  v_deliverynoteappendix_aux vdeln where vdeln.packingnote_id=pn.packingnote_id and vdeln.CUSTOMERNUMBER=coalesce(ih.deltocustomernumber, ih.billtocustomernumber )) pricesum
from   invoiceheader ih, packingnoteline pnl, packingnote pn, distributionpoint cons, department dep,
       currency, status statuspn, status statusih,
       businessunit processbu, plant, languages
where  ih.invoiceheader_id = pnl.invoiceheader_id
and    ih.documenttype = 1
and    ih.status_id = statusih.status_id
and    statusih.statustype = 'IN'
and    pnl.packingnote_id = pn.packingnote_id
and    pn.status_id = statuspn.status_id
and    statuspn.statustype = 'PN'
and    statuspn.code = '30'
and    pn.distributionpoint_id = cons.distributionpoint_id
and    cons.department_id = dep.department_id
and    ih.currency_id = currency.currency_id
and    pn.processbusinessunit_id = processbu.businessunit_id
and    processbu.plant_id = plant.plant_id
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(packingnotecontainer.grossweight - packingnotecontainer.tareweight)
         from   packingnotecontainer
         where  pn.packingnote_id = packingnotecontainer.packingnote_id
         group  by pn.packingnote_id) weight,
       pnc.weightdecimals,
       0 price,
       0 discountpercentage,       -- total, to be calculated in the report!
       currency.code currencycode, currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals, 0 pnnotininvoice, pn.remark,
       (select ss.value from systemsetting ss where plant.plant_id = ss.plant_id and ss.name = 'WEIGHTUNIT') weightunit,
       languages.code languagecode, dep.departmentnumber dep_number,
       dep.description dep_description, pn.freeofchargereason_id,
       1 pricefactor, pn.status_id
, (select sum(vdeln.WeightPrice) from  v_deliverynoteappendix_aux vdeln where vdeln.packingnote_id=pn.packingnote_id and vdeln.CUSTOMERNUMBER=coalesce(ih.deltocustomernumber, ih.billtocustomernumber )) pricesum
from   invoiceheader ih, packingnote pn, packingnotecontainer pnc, distributionpoint cons, department dep,
       currency, status statuspn, status statusih,
       businessunit processbu, plant, languages
where  ih.invoiceheader_id = pnc.invoiceheader_id
and    pnc.packingnote_id = pn.packingnote_id
and    ih.documenttype = 1
and    ih.status_id = statusih.status_id
and    statusih.statustype = 'IN'
and    pn.status_id = statuspn.status_id
and    statuspn.statustype = 'PN'
and    statuspn.code = '30'
and    pn.distributionpoint_id = cons.distributionpoint_id
and    cons.department_id = dep.department_id
and    ih.currency_id = currency.currency_id
and    pn.processbusinessunit_id = processbu.businessunit_id
and    processbu.plant_id = plant.plant_id
and not exists (select 1 from packingnoteline pnl where pnl.packingnote_id = pn.packingnote_id)

/
create or replace view V_DELIVERYNOTELINE_HCH
 (PACKINGNOTENUMBER, PRODUCTCODE, PRODUCTDESCRIPTION, PRODUCTGROUPDESCRIPTION, PGCUSTOMDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, 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, LASTSOILCOUNT, SHORTAGE)
as select packingnote.notenumber packingnotenumber, product.code productcode,
       (select description
         from   product_desc p
         where  p.product_id = packingnoteline.product_id and p.language_id = languages.language_id)
productdescription,
       (select description
         from   productgroup_desc a
         where  a.productgroup_id = product.productgroup_id and a.language_id = languages.language_id)
productgroupdescription,
       (select pgpc.customdescritpion
         from   productgrouppercustomer pgpc, distributionpoint dp, department dep
         where  pgpc.productgroup_id = product.productgroup_id AND pgpc.customer_id = dep.customer_id
                AND dep.department_id = dp.department_id AND dp.distributionpoint_id = packingnote.distributionpoint_id)
pgcustomdescription,
       packingnoteline.customcode, packingnoteline.customdescription, sizedefinition.code,
       (select description
         from   sizedefinition_desc s
         where  s.sizedefinition_id = packingnoteline.sizedefinition_id and
                s.language_id = languages.language_id) sizedescription,
       (select description
         from   finishingmethod_desc f
         where  f.finishingmethod_id = packingnoteline.finishingmethod_id and
                f.language_id = languages.language_id) finishingmethoddescription,
       packingnoteline.packingsequence, packingnoteline.standardamount,
       packingnoteline.variationamount, packingnoteline.deliveredamount,
       packingnoteline.tobedeliveredamount, packingnoteline.remarkforpackinginstructions,
       packingnoteline.systemuser_id, packingnoteline.timestamp, languages.code,
       product.typeofmerchandise,
       (select r.code
         from   reasoncode r
         where  r.reasoncode_id = packingnoteline.freeofchargereason_id) freeofchargereason,
       (select description
         from   reasoncode_desc rd
         where  rd.reasoncode_id = packingnoteline.freeofchargereason_id and
                rd.language_id = languages.language_id) freeofchargereason_desc,
       packingnoteline.nochargefirstissue, packingnoteline.nochargeactiveseason,
       packingnoteline.deliveredcogqty, packingnoteline.origin line_origin, packingnoteline.price,
       packingnoteline.amount, packingnoteline.taxgroupcode,
       (select rg.code
         from   registrationunit rg
         where  rg.registrationunit_id = product.registrationunit_id) regunit,
       (case
          when packingnote.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 = packingnoteline.product_id and
                   pal.sizedefinition_id = packingnoteline.sizedefinition_id and
                   pal.finishingmethod_id = packingnoteline.finishingmethod_id and
                   pa.notenumber = packingnote.correctednotenumber)
        end) old_qty, packingnoteline.pricecog
, (select max(psz.sequencenumber) from productsize psz where psz.product_id = product.product_id and psz.sizedefinition_id = sizedefinition.sizedefinition_id) sequencenumber
, (select code from finishingmethod f
   where  f.finishingmethod_id = packingnoteline.finishingmethod_id) finishingmethodcode
, coalesce(( select sum(amount)
             from   v_deliveryvariations vdv
             where  vdv.packingnotenumber = packingnote.notenumber
                and vdv.productcode = product.code
                and vdv.finishingmethodcode = finishingmethodcode
                and vdv.languagecode = languages.code
                and vdv.origin = 1), 0) LASTSOILCOUNT
, coalesce(( select sum(amount)
             from   v_deliveryvariations vdv
             where  vdv.packingnotenumber = packingnote.notenumber
                and vdv.productcode = product.code
                and vdv.finishingmethodcode = finishingmethodcode
                and vdv.languagecode = languages.code
                and vdv.origin = 5), 0) SHORTAGE
From   packingnoteline, packingnote, product, sizedefinition, languages
where  packingnoteline.packingnote_id = packingnote.packingnote_id and
       packingnoteline.product_id = product.product_id and
       packingnoteline.sizedefinition_id = sizedefinition.sizedefinition_id

/
create or replace view V_DELIVERYNOTE_BUB
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERSTREET2, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, CUSTOMERCOUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION
, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, 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, WOREFNUMBER, TOTALWEIGHT)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME,
ADDRESS.STREET CUSTOMERSTREET, ADDRESS.STREET2 CUSTOMERSTREET2,  ADDRESS.ZIPCODE CUSTOMERZIP, ADDRESS.CITY CUSTOMERCITY, ADDRESS.STATE CUSTOMERSTATE,
C1.CODE CUSTCOUNTRY, C1.DESCRIPTION CUSTCOUNTRY_DESC, ADDRESS.COUNTY CUSTOMERCOUNTY,
DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
PACKINGNOTE.SEQUENCENUMBER,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, --CAST(
PACKINGNOTE.REMARK --AS VARCHAR2(60) ) REMARK
, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL, --ORDER 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
cast (SS.VALUE as varchar2(60)) WEIGHTUNIT,
cast (SS1.VALUE as varchar2(1)) PRINTDELNOTEPERCONTAINER,
cast (SS2.VALUE as varchar2(1)) CONTAINERRECORDINGACTIVE,
cast (SS3.VALUE as varchar2(1)) PRINTDELNOTEZEROLINES,
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(60)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
      ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
coalesce((SELECT min(PNC.PACKINGNOTE_ID) FROM PACKINGNOTECONTAINER PNC
   LEFT OUTER JOIN CONTAINER C ON C.CONTAINER_ID = PNC.CONTAINER_ID
   LEFT OUTER JOIN CONTAINERTYPE CT ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   LEFT OUTER JOIN WEIGHINGCATEGORY W ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID),0) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC
, coalesce((select max(ds.packingnote_id)
                 from   deliveryscan ds
                 where  ds.packingnote_id = packingnote.packingnote_id),
                 (select max(o.packingnote_id)
                   from   outofcirculationhistory o
                   where  o.packingnote_id = packingnote.packingnote_id), 0) numberofpossiblelineswithscans
, PACKINGNOTE.YEAR YEAR
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.REFERENCENUMBER
, INVOICEBU.INTERNALVATNUMBER
, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE
, ROUTE.PUTUPREPORTPERCUSTOMER
, customer.signaturerequired
, dsig.personidentification personidentification
, dsig.signature signature
, (select rc.drivingdate from routecontrol rc where rc.routecontrol_id = stop.routecontrol_id) signaturedate
, to_char(stop.departuretime,'fmhhfm:MI:AM') signaturetime
, to_char(stop.departuretime,'fmhh24fm:MI') signaturetime24
, packingnote.distributionpoint_id
, packingnote.processbusinessunit_id
, DELIVERYPOINT. SIGNATUREBARCODE
, cast ((SELECT SS.VALUE FROM SYSTEMSETTING SS WHERE SS.PLANT_ID=PLANT.PLANT_ID AND SS.NAME ='CONTAINERTYPEUNQBRCLABEL')  as varchar2(60)) containertypedescription
, (select max(wo.referencenumber) from deliveryscan ds, issuehistory ih, workorder wo
where ds.uniqueitem_link_id = ih.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 ih.workorder_id = wo.workorder_id
and ds.packingnote_id = packingnote.packingnote_id
and wo.deliverfrom=2
) worefnumber
, (select sum(vk.grossweight - vk.tareweight - vk.soilportion) from v_deliverynote_knt vk
   where vk.packingnote_id = PACKINGNOTE.PACKINGNOTE_ID and vk.LANGUAGECODE = LANGUAGES.Code
         /*and cast (SS1.VALUE as varchar2(1)) = 'Y' and vk.sequencenumber =*/ ) TotalWeight
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,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        PACKINGNOTE
          LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
          LEFT OUTER JOIN ROUTE ON (PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID)
          LEFT OUTER JOIN STOP ON (PACKINGNOTE.STOP_ID = STOP.STOP_ID)
          left outer join deliverysignature dsig on (dsig.stop_id = packingnote.stop_id and dsig.stop_id=packingnote.deliverysignature_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 STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20 or (packingnote.origin = 14 and status.code = 40))
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID

/
create or replace view V_DELIVERYNOTE_STI
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION, PLANTCODE, PLANTNAME
, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, 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, NAME, MOBILENO)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
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,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL, --ORDER 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
lpad(SS.VALUE, 3) WEIGHTUNIT, lpad(SS1.VALUE, 3) PRINTDELNOTEPERCONTAINER
, lpad(SS2.VALUE, 3) CONTAINERRECORDINGACTIVE, lpad(SS3.VALUE, 3) PRINTDELNOTEZEROLINES
, 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(255)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
	    ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
coalesce((SELECT min(PNC.PACKINGNOTE_ID) FROM PACKINGNOTECONTAINER PNC
   LEFT OUTER JOIN CONTAINER C ON C.CONTAINER_ID = PNC.CONTAINER_ID
   LEFT OUTER JOIN CONTAINERTYPE CT ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   LEFT OUTER JOIN WEIGHINGCATEGORY W ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID),0) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC
, coalesce((SELECT min(vds.packingnote_id) FROM  v_deliveryscan_all vds where vds.packingnote_id= PACKINGNOTE.PACKINGNOTE_ID),0)NUMBEROFPOSSIBLELINESWITHSCANS
, PACKINGNOTE.YEAR YEAR
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.REFERENCENUMBER
--, 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
, INVOICEBU.INTERNALVATNUMBER
, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE
, ROUTE.PUTUPREPORTPERCUSTOMER
, customer.signaturerequired
, dsig.personidentification personidentification
, dsig.signature signature
, (select rc.drivingdate from routecontrol rc where rc.routecontrol_id = stop.routecontrol_id) signaturedate
, to_char(stop.departuretime,'fmhhfm:MI:AM') signaturetime
, to_char(stop.departuretime,'fmhh24fm:MI') signaturetime24
, packingnote.distributionpoint_id
, packingnote.processbusinessunit_id
, driver.name name, driver.mobileno
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,
--       LEFT OUTER JOIN CUSTOMERBILLINGINFO CBI
--             LEFT OUTER JOIN BANKINSTITUTION LBANK
--             ON CBI.LAUNDRYBANKINSTITUTION_ID = LBANK.BANKINSTITUTION_ID
--        ON CUSTOMER.DEBTOR_ID = CBI.CUSTOMER_ID,
        ADDRESS, DEPARTMENT, DISTRIBUTIONPOINT, PLANT, ADDRESS PLANTADDRESS,
        BUSINESSUNIT PROCESSBU,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        PACKINGNOTE
          LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
          LEFT OUTER JOIN ROUTE ON (PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID)
          LEFT OUTER JOIN STOP ON (PACKINGNOTE.STOP_ID = STOP.STOP_ID)
          left outer join deliverysignature dsig on (dsig.stop_id = packingnote.stop_id and dsig.stop_id=packingnote.deliverysignature_id)
          left outer join employee driver on (route.driver_id = driver.employee_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 STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20 or (packingnote.origin = 14 and status.code = 40))
	AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID

/
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, QTYTOBERETURNED, OUTSTANDINGQTY, TOOLESSMUCH, LANGUAGECODE)
as select
  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
, coalesce(d.qtyToBeReturned,0) qtyToBeReturned
, COALESCE((dx.OutStandingQty), 0)  OutStandingQty
, ( coalesce(d.maxinventory,0) + coalesce(d.qtyToBeReturned,0)
   /*+ coalesce((select count(*)
    from uniqueitemnonpool uinp, uniqueitemflag uif, automaticflag afl
    where uinp.uniqueitem_id=uif.uniqueitem_id and uif.flag_id=afl.flag_id
       and d.wearerinventory_id = uinp.wearerinventory_id
       and d.weareremployment_id = uinp.weareremployment_id
       and afl.event='Flag for return to stock due to manual decrease of max inv') ,0) */ )
    - ( coalesce(d.circinventory,0) + COALESCE(dx.OutStandingQty, 0))
         TooLessMuch
, d.languageCode
from
    v_deviatedcircinv d
        left outer 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_DEVIATEDCIRCINV_SUM_NIX
 (CUSTOMERNUMBER, CUSTOMERNAME, CITY, DEPARTMENTNUMBER, DEPARTMENTDESC, WEARERNUMBER, WEARERNAME, WEARERDATEINACTIVE, WEARERINVENTORYDATEINACTIVE, SEQUENCENUMBER, FUNCTIONCODE, SEARCHNAME, PRODUCTCODE, SIZECODE, PRODUCTDESC, DEFAULTBUSINESSUNIT_ID, MAXINVENTORY, CIRCINVENTORY, QTYTOBERETURNED, OUTSTANDINGQTY, TOOLESSMUCH, LANGUAGECODE, ROUTENUMBER)
as select
  d.customernumber, d.customerName, d.city, d.departmentnumber, d.departmentdesc
, d.wearernumber, d.wearerName, d.wearerdateinactive, d.wearerINVENTORYdateinactive
, d.sequencenumber, d.functionCode, d.searchname
, d.productCode, d.sizeCode, d.productdesc, d.defaultbusinessunit_id
, d.maxinventory, d.circinventory
, coalesce(d.qtyToBeReturned,0)
    + coalesce((select count(*)
    from uniqueitemnonpool uinp, uniqueitemflag uif, automaticflag afl
    where uinp.uniqueitem_id=uif.uniqueitem_id and uif.flag_id=afl.flag_id
       and d.wearerinventory_id = uinp.wearerinventory_id
       and d.weareremployment_id = uinp.weareremployment_id
       and afl.event='Return to stock because of decrease max inventory') ,0) qtyToBeReturned
, COALESCE((dx.OutStandingQty), 0)  OutStandingQty
, ( coalesce(d.maxinventory,0) + coalesce(d.qtyToBeReturned,0)
   + coalesce((select count(*)
    from uniqueitemnonpool uinp, uniqueitemflag uif, automaticflag afl
    where uinp.uniqueitem_id=uif.uniqueitem_id and uif.flag_id=afl.flag_id
       and d.wearerinventory_id = uinp.wearerinventory_id
       and d.weareremployment_id = uinp.weareremployment_id
       and afl.event='Return to stock because of decrease max inventory') ,0) )
    - ( coalesce(d.circinventory,0) + COALESCE(dx.OutStandingQty, 0))
         TooLessMuch
, d.languageCode
, d.routenumber
from
    v_deviatedcircinv_nix d
        left outer 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, CUSTOMERNAME, WEARERNUMBER, WEARERNAME, ROWCODE, LOCATIONCODE, EMBLEMNR, EMBLEMDESCRIPTION, EMBLEMTYPE, SIZESHAPE, FABRIC, EMBLEM_FONT, BACKGROUND, TEXT, BORDER, QUANTITYREQUESTED
, LANGUAGECODE, EMBLEMTEMPLATELINE_DESC)
as select supplier.suppliernumber, supplier.name suppliername, addresssuplier.street supplierstreet,
       addresssuplier.zipcode supplierzip, addresssuplier.city suppliercity,
       supplier.phone supplierphone, supplier.fax supplierfax,
       coalesce(v_sk.businessunitcode, v_sk2.businessunitcode) businessunitcode,
       coalesce(v_sk.businessunitdesc, v_sk2.businessunitdesc) businessunitdesc,
       coalesce(v_sk.plantstreet, v_sk2.plantstreet) plantstreet,
       coalesce(v_sk.plantzip, v_sk2.plantzip) plantzip,
       coalesce(v_sk.plantcity, v_sk2.plantcity) plantcity,
       coalesce(v_sk.plantphone, v_sk2.plantphone) plantphone,
       coalesce(v_sk.plantfax, v_sk2.plantfax) plantfax,
       coalesce(v_sk.plantcode, v_sk2.plantcode) plantcode,
       coalesce(v_sk.stockroomcode, v_sk2.stockroomcode) stockroomcode,
       coalesce(v_sk.stockroomdesc, v_sk2.stockroomdesc) stockroomdesc, route.routenumber,
       day.daynumber,
       (select day_desc.description
         from   day_desc
         where  day_desc.day_id = day.day_id
         and    day_desc.language_id = l.language_id) daydesc, w.emblemname nameonlabel,
       wo.workordernumber, wo.neededdate requestdate,
       coalesce(c.customernumber, c2.customernumber) customernumber,
       coalesce(c.name, c2.name) customername, w.wearernumber, w.fullname wearername, v_sk.rowcode,
       v_sk.locationcode, coalesce(p.code, empt.code) emblemnr,
       coalesce((select product_desc.description
                 from   product_desc
                 where  product_desc.product_id = p.product_id
                 and    product_desc.language_id = l.language_id), empl.description,
                 (txt.code || ' ' || fabric2.code)) emblemdescription, empl.emblemtype,
       s.code sizeshape, coalesce(fabric.code, fabric2.code) fabric,
       coalesce(emblemfont.description, ef.description) emblem_font,
       coalesce(c1.code, color.code) background, coalesce(text.code, txt.code) text,
       coalesce(border.code, c2.code) border, woem.qtyrequested quantityrequested,
       l.code languagecode, empl.description emblemtemplateline_desc
from   workorder wo
join   workorderline wol
on     wol.workorder_id = wo.workorder_id
join   workorderlineemblem woem
on     woem.workorderline_id = wol.workorderline_id
left   outer join(emblemtemplateline empl
join   emblemtemplate empt
on     empt.emblemtemplate_id = empl.emblemtemplate_id
join   sizedefinition s
on     s.sizedefinition_id = empl.sizedefinition_id
join   fabric fabric2
on     fabric2.fabric_id = empl.fabric_id
left   outer join emblemfont ef
on     ef.emblemfont_id = empl.emblemfont_id
left   outer join color
on     color.color_id = empl.bkgcolor_id
left   outer join color c2
on     c2.color_id = empl.bordercolor_id
left   outer join placement
on     placement.placement_id = empl.placement_id
left   outer join color txt
on     empl.textcolor_id = txt.color_id) on empl.emblemtemplateline_id = woem.emblemtemplateline_id
left   outer join(product p
join   fabric
on     fabric.fabric_id = p.fabric_id
join   color c1
on     c1.color_id = p.color_id
join  (supplier
join   address addresssuplier
on     supplier.address_id = addresssuplier.address_id) on supplier.supplier_id = p.supplier_id
join  (emblemproduct emp
left   outer join color text
on     text.color_id = emp.textcolor_id
left   outer join color border
on     border.color_id = emp.bordercolor_id
left   outer join emblemfont
on     emblemfont.emblemfont_id = emp.emblemfont_id) on emp.product_id = p.product_id) on p.product_id = coalesce(woem.product_id, empl.product_id)
left   outer join(route
join   day
on     day.day_id = route.drivingday_id) on wo.route_id = route.route_id
left   outer join v_emblempicklist_stock v_sk
on     (v_sk.product_id = p.product_id and v_sk.sizedefinition_id = empl.sizedefinition_id)
left   outer join v_emblempicklist_stock_userdef v_sk2
on     v_sk2.stockroom_id = wo.processingstockroom_id
left   outer join(distributionpoint dp
join   department t
on     t.department_id = dp.department_id
join   customer c2
on     c2.customer_id = t.customer_id) on dp.distributionpoint_id = wo.distributionpoint_link_id
left   outer join(weareremployment we
join   wearer w
on     w.wearer_id = we.wearer_id
join   customer c
on     c.customer_id = w.customer_id) on we.weareremployment_id = wo.weareremployment_link_id, languages l

/
create or replace view V_EMBLEMPICKLIST_LST
 (BUSINESSUNITCODE, BUSINESSUNITDESC, PLANTSTREET, PLANTZIP, PLANTCITY, PLANTPHONE, PLANTFAX, PLANTCODE, STOCKROOMCODE, STOCKROOMDESC, NAMEONLABEL, WORKORDERNUMBER, REQUESTDATE, ROWCODE, LOCATIONCODE, EMBLEMNR, EMBLEMDESCRIPTION, EMBLEMTYPE, SIZESHAPE, FABRIC, EMBLEM_FONT, BACKGROUND, TEXT, BORDER, QUANTITYREQUESTED, LANGUAGECODE, EMBLEMTEMPLATELINE_DESC)
as select
  V_sk.BusinessunitCode, V_sk.BusinessunitDesc, V_sk.PlantStreet, V_sk.PlantZip
, V_sk.PlantCity, V_sk.PlantPhone, V_sk.PlantFax, V_sk.PlantCode
, V_sk.StockroomCode, V_sk.StockroomDesc, w.emblemname NameOnLabel
, wok.workordernumber, wok.neededdate requestdate
, V_sk.rowcode, V_sk.locationcode, V_wemb.EmblemNr, V_wemb.EmblemDescription, V_wemb.EmblemType
, V_wemb.SizeShape, V_wemb.fabric, V_wemb.emblem_font
, V_wemb.Background, V_wemb.Text, V_wemb.Border
, V_wemb.Quantity QuantityRequested
, languages.code LanguageCode
, V_wemb.emblemtemplateline_desc
from
  v_Workorderemblem V_wemb
     left outer join v_emblempicklist_Stock V_sk
          on V_wemb.product_id = V_sk.product_id
             and V_wemb.sizedefinition_id = V_sk.sizedefinition_id
     join product prd on prd.code = V_wemb.EmblemNr and prd.recordpassivestock is not null
, workorderline wokli
, workorder wok, weareremployment we, wearer w, languages
where
    V_wemb.workorderline_id = wokli.workorderline_id
and V_wemb.workorder_id = wok.workorder_id
and V_wemb.LanguageCode = languages.code
        and wok.weareremployment_link_id = we.weareremployment_id
    and we.wearer_id = w.wearer_id
--and v_sk.stockroom_id = wok.processingstockroom_id
union ALL
select
  V_sk.BusinessunitCode, V_sk.BusinessunitDesc, V_sk.PlantStreet, V_sk.PlantZip
, V_sk.PlantCity, V_sk.PlantPhone, V_sk.PlantFax, V_sk.PlantCode
, V_sk.StockroomCode, V_sk.StockroomDesc,  '' NameOnLabel
, wok.workordernumber, wok.neededdate requestdate
, V_sk.rowcode, V_sk.locationcode, V_wemb.EmblemNr, V_wemb.EmblemDescription, V_wemb.EmblemType
, V_wemb.SizeShape, V_wemb.fabric, V_wemb.emblem_font
, V_wemb.Background, V_wemb.Text, V_wemb.Border
, V_wemb.Quantity QuantityRequested
, languages.code LanguageCode
, V_wemb.emblemtemplateline_desc
from
  v_Workorderemblem V_wemb
     left outer join v_emblempicklist_Stock V_sk
          on V_wemb.product_id = V_sk.product_id
             and V_wemb.sizedefinition_id = V_sk.sizedefinition_id
     join product prd on prd.code = V_wemb.EmblemNr and prd.recordpassivestock is not null
, workorderline wokli
, workorder wok
, languages
where
    V_wemb.workorderline_id = wokli.workorderline_id
and V_wemb.workorder_id = wok.workorder_id
and V_wemb.LanguageCode = languages.code
and wok.weareremployment_link_id is null
--and v_sk.stockroom_id = wok.processingstockroom_id
union ALL
select
  V_sk.BusinessunitCode, V_sk.BusinessunitDesc, V_sk.PlantStreet, V_sk.PlantZip
, V_sk.PlantCity, V_sk.PlantPhone, V_sk.PlantFax, V_sk.PlantCode
, V_sk.StockroomCode, V_sk.StockroomDesc, w.emblemname NameOnLabel
, wok.workordernumber, wok.neededdate requestdate
, null rowcode,  null locationcode, V_wemb.EmblemNr, V_wemb.EmblemDescription, V_wemb.EmblemType
, V_wemb.SizeShape, V_wemb.fabric, V_wemb.emblem_font
, V_wemb.Background, V_wemb.Text, V_wemb.Border
, V_wemb.Quantity QuantityRequested
, languages.code LanguageCode
, V_wemb.emblemtemplateline_desc
from
  v_Workorderemblem V_wemb
, v_emblempicklist_Stock_Userdef V_sk
, workorderline wokli
, workorder wok, weareremployment we, wearer w, languages
where
    V_wemb.workorderline_id = wokli.workorderline_id
and V_wemb.workorder_id = wok.workorder_id
--and V_sk.stockroom_id = wok.processingstockroom_id
and V_wemb.LanguageCode = languages.code
    and wok.weareremployment_link_id = we.weareremployment_id
    and we.wearer_id = w.wearer_id
and V_wemb.product_id is null
and V_wemb.sizedefinition_id is null
/
create or replace view V_GARMENTHISTORY_SMG
 (YEAR, WEEK, DEPARTMENTNUMBER, DEPARTMENTDESC, WEARERNUMBER, WEARERNAME, PRODUCTCODE, PRODUCTDESC, SIZECODE, QUANTITY, SALESPRICE, INVOICEHEADER_ID, LANGUAGECODE, LANGUAGE_ID, DISCOUNTPERCENTAGE, AMOUNT, FINMETHODCODE)
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
,      case when ( select uil.uniqueitem_id
                   from   uniqueitem_link uil
                   where  uil.uniqueitem_link_id = a.uniqueitem_link_id ) is null
            then ( select vpf.finmethodcode
                   from   v_ProdID_Finmethodcode_SMG vpf
                   where  vpf.product_id = p.product_id )
            else ( select fm.code
                   from   finishingmethod fm
                   where  fm.finishingmethod_id =
                     ( select ui.finishingmethod_id
                       from   uniqueitem ui
                       where  ui.uniqueitem_id =
                         ( select uil.uniqueitem_id
                           from uniqueitem_link uil
                           where  uil.uniqueitem_link_id = a.uniqueitem_link_id
                         )
                     )
                 )
       end finmethodcode
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
   and a.amount <> 0

/
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_INVOICEADDITION_BNL
 (INVOICEHEADER_ID, INVOICENUMBER, INVOICEDATE, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, RENTPERIOD, CODE, DESCRIPTION, WEARERNUMBER, WEARERNAME, YEAR, WEEK, INVOICEQTYCOLUMN, QUANTITY, PRICE, AMOUNT, NEXTPERIODNOWEEKS, NEXTPERIODSTARTDATE, INVOICELINETYPE, INVOICELINESUBTYPE, SEQUENCENUMBER, WEAREREMPLOYMENT_LINK_ID, NO_OF_WEEKS, MINYEARWEEK, INVOICELINE_ID)
as select
  ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate
, ih.deltocustomernumber, ih.deltocustomername, dell.rentperiod
, il.code, il.description
, welk.wearernumber, welk.wearername
, iladd.year, iladd.week, ilp.invoiceqtycolumn, iladd.quantity
, il.price, il.amount, ih.nextperiodnoweeks, ih.nextperiodstartdate
, t.type invoicelinetype, il.invoicelinesubtype, ILADD.sequencenumber
, ILADD.weareremployment_link_id, ILADD.NO_OF_WEEKS, ILADD.minyearweek, il.invoiceline_id
from
  invoiceheader ih, customer_link dell_culk
                      left outer join customer dell on dell_culk.Customer_Id = dell.customer_id
, invoiceline il, invoicelineproduct ilp
, V_INVOICEADDITION_AUX_BNL iladd
    left outer join weareremployment_link welk on iladd.weareremployment_link_id = welk.weareremployment_link_id
, invoicelinetype t
where
   ih.documenttype = 1
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 il.invoicelinetype_id = t.invoicelinetype_id

/
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_INVOICECLIENTLINE_BDM
 (CHANGESPERWEEK, MAXINV, LINENUMBER, COSTCENTER_ID, CIRCINV, SQQTY, BILLINGMETHOD, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, DESCRIPTION, TYPEOFMERCH, INCR, DECR, STOCKLINEN, SPCVINVOICELINETYPE, AMOUNT, ILAMOUNT, PRICE, BILLEDQTY, INVOICELINESUBTYPE, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, SIZECODE, FINISHINGMETHODCODE, PERCENTAGE, INVOICELINE_ID, LANGUAGECODE, INVOICEHEADER_ID, OVERAMOUNT, REGISTRATIONUNITDESCRIPTION, SUPRESSPRINTING, PRICEFACTOR, COSTCENTER_DESC, CONTRACTCOEFFICIENT
, PONUMBER)
as select  v.changesperweek, v.maxinv, a.linenumber, cc.costcenter_id, sum(v.circinv) circinv, sum(v.numberemploymentscharge) sqqty, b.billingmethod,
(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
, case when a.invoicelinetype_id = 12 and a.invoicelinesubtype = 11--Stockroom Handling & Label/Emblem charge  + Label Charges
then case when a.code = 'Etiquette code' then 'Etiquette de code barre'
  when a.code = 'Etiquette nom' then 'Etiquette de nom'
  else a.description end
else a.description end description
, (select p.typeofmerchandise from product p where p.code=a.code) typeofmerch,
         nvl((select sum(q.quantity)
              from   rentalqtyadjustment q, productlistperdistribpoint plpd, distributionpoint dp,
                     department t
              where  q.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
              and    plpd.distributionpoint_id = dp.distributionpoint_id
              and    dp.department_id = t.department_id
              and    t.customer_id = f.deltocustomer_link_id
              and    b.product_link_id = plpd.product_id
              and    b.sizedefinition_link_id = plpd.sizedefinition_id
              and    b.finishingmethod_id = plpd.finishingmethod_id
              and    q.adjustmentdate >= f.startdate
              and    q.adjustmentdate <= f.enddate
                and dp.costcenter_id=cc.costcenter_id
              and    q.quantity > 0), 0) incr,
                nvl((select sum(q.quantity)
              from   rentalqtyadjustment q, productlistperdistribpoint plpd, distributionpoint dp,
                     department t
              where  q.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
              and    plpd.distributionpoint_id = dp.distributionpoint_id
              and    dp.department_id = t.department_id
              and    t.customer_id = f.deltocustomer_link_id
              and    b.product_link_id = plpd.product_id
              and    b.sizedefinition_link_id = plpd.sizedefinition_id
              and    b.finishingmethod_id = plpd.finishingmethod_id
              and dp.costcenter_id=cc.costcenter_id
              and    q.adjustmentdate >= f.startdate
              and    q.adjustmentdate <= f.enddate
              and    q.quantity < 0), 0) decr,
                nvl((select sum(q.quantity)
              from   rentalqtyadjustment q, productlistperdistribpoint plpd, distributionpoint dp,
                     department t
              where  q.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
              and    plpd.distributionpoint_id = dp.distributionpoint_id
              and    dp.department_id = t.department_id
              and    t.customer_id = f.deltocustomer_link_id
              and    b.product_link_id = plpd.product_id
              and    b.sizedefinition_link_id = plpd.sizedefinition_id
              and    b.finishingmethod_id = plpd.finishingmethod_id
              and dp.costcenter_id=cc.costcenter_id
              and   q.adjustmentdate<f.invoicedate), 0) stocklinen,
( iltc.invoicelinetype_id ) spcvinvoicelinetype, coalesce(ccil.amount, a.amount) amount,
a.amount ilamount,
a.price, coalesce(ccil.quantity,a.billedqty) billedqty, a.invoicelinesubtype,
b.productgroupcode, b.productgroupdescription
, nvl(v.sizecode,b.sizecode) sizecode, b.finishingmethodcode
, c.percentage, a.invoiceline_id, LANGUAGES.CODE LANGUAGECODE,
a.invoiceheader_id, c.overamount,
 ( 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,
case (SELECT pilt.suppressprinting
         from plantinvoicelinetype pilt, businessunit bu
         where f.invoicebusinessunit_id = bu.businessunit_id
               and bu.plant_id = pilt.plant_id
               and pilt.invoicelinetype_id = a.invoicelinetype_id)
  when 0 then 0
  when 1 then 1
  when 2 then 2
  else e.supressprinting
end supressprinting, --502161
 b.pricefactor, cc.description costcenter_desc, a.contractcoefficient, cc.ponumber
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)
left outer join costcenterinvoiceline ccil inner join costcenter cc on ccil.costcenter_link_id=cc.costcenter_id  on ccil.invoiceline_id=a.invoiceline_id
left outer join v_circinv_bdm v on v.invoiceheader_id=a.invoiceheader_id and v.invoiceline_id=a.invoiceline_id and v.costcenter_id=cc.costcenter_id
left outer join specialcharge sc join invoicelinetypecharge iltc on iltc.specialcharge_id=sc.specialcharge_id on
( sc.code=a.code and a.invoicelinetype_id=16 and iltc.invoicelinetype_id in (select il.invoicelinetype_id from invoiceline il where il.invoiceheader_id=a.invoiceheader_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)
AND A.INVOICELINETYPE_ID <> 18
group by ccil.amount, ccil.quantity, v.changesperweek, v.maxinv, a.linenumber, cc.costcenter_id, a.code, a.description, iltc.invoicelinetype_id, a.amount,
a.price, a.billedqty, a.invoicelinesubtype, b.billingmethod,b.productgroupcode, b.productgroupdescription,f.invoicedate,
v.sizecode,b.sizecode, b.finishingmethodcode, c.percentage, a.invoiceline_id, LANGUAGES.CODE, a.invoiceheader_id, c.overamount,
e.type, e.supressprinting, b.pricefactor, cc.description,  a.invoicelinetype_id, languages.language_id, f.deltocustomer_link_id,
b.product_link_id ,b.sizedefinition_link_id, b.finishingmethod_id, f.startdate, f.enddate, f.invoicebusinessunit_id, a.contractcoefficient, cc.ponumber

/
create or replace view V_INVOICEDAMOUNTCOMPARISON_LLG
 (INVOICEDATE, BUSINESSUNITCODE, BUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, DELTOCUSTOMERNUMBER, DELTOCUSTNAME, MARKETSEGMENTCODE, INVOICELINETYPE, INVOICELINESUBTYPE, PRODUCTCODE, INVOICELINECODE, INVOICELINEDESC, SIZECODE, PRODUCTGROUPCODE, ACTIVITYCODE, AMOUNT, BILLEDQTY, INVOICEAMOUNTDECIMALS, REPORTPARAM_ID, INVOICELINE_ID, STATUSCODE, TOTALWEEKLYCHARGE, VAT)
as select ih.invoicedate, bu.code businessunitcode, bu.description businessunitdesc,
  bcu.customernumber billtocustomernumber, bcu.name billtocustomername,
  dcu.customernumber deltocustomernumber, dcu.name deltocustname,
  ms.code marketsegmentcode,
  (CASE WHEN ilt.type = 1 AND il.invoicelinesubtype = 41
        then 1.41
      WHEN ilt.type = 1 AND il.invoicelinesubtype = 42
        then 1.42
      ELSE ilt.TYPE
END)  invoicelinetype, il.invoicelinesubtype,
  pr.code productcode,
  il.code invoicelinecode, il.description invoicelinedesc, ilp.sizecode,
  prg.code productgroupcode,
  ac.code activitycode,
  il.amount, il.billedqty,
cr.invoiceamountdecimals,
rp.reportparam_id, il.invoiceline_id
, st.code statuscode
,(select sum(v.minimumturnaround/100 * v.totalincirc * v.Rent_Price) from v_invoicedamntcompar_plpc_llg v where v.customer_id = ih.billtocustomer_link_id) totalweeklycharge
,(select tg.taxrate from taxgroup tg where tg.code = il.taxgroupcode)/100 VAT
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 <> '3'
  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_INVOICEHEADER_HUE
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE
, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE, DEFAULT_BU_CODE, ADJUSTMENT_REASONCODE, SPLITUPCODE
, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE
, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, DEP_STREET, DEP_STREET2, DEP_ZIPCODE, DEP_CITY, DEP_STATE, DEP_COUNTY, DEP_PHONE, DEP_FAXNO, DEP_CODE, DEP_DESC)
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, a.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,
       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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
--       (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,
       rc.code Adjustment_ReasonCode
--, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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
       , (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
--       , F_SDAYS(a.invoicenumber, 30, 0) days30, F_SDAYS(a.invoicenumber, 60, 30) days60
--       , F_SDAYS(a.invoicenumber, 999, 60) days60PLUS
       , (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
       , Y.DEP_STREET, Y.DEP_STREET2, Y.DEP_ZIPCODE, Y.DEP_CITY, Y.DEP_STATE
       , Y.DEP_COUNTY, Y.DEP_PHONE, Y.DEP_FAXNO, Y.DEP_CODE, Y.DEP_DESC
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'),
      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 V_INVOICEHEADER_HUE_2 y ON a.invoiceheader_id = Y.invoiceheader_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)
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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

/
create or replace view V_INVOICEHEADER_LTS
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, HOUSENUMBER, HOUSENUMBEREXT, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS
, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL
, PLANTNAME_PROC, PLANTPHONE_PROC, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUST_TAXABLE, M_SORT_US_ASC
, M_SORT_US_DESC, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE, DEFAULT_BU_CODE, ADJUSTMENT_REASONCODE, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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
, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER
, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, COLLECTIONRESPEMPLOYEE, CONSOLIDATED_INVOICE_LAYOUT, DELTO_CONTACTPERSONNAME, CUSTOMER_LANGUAGECODE, BILLTOLEGALNAME, CLIENT_LINK_ID, IHCLIENTNUMBER, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, IHCCLIENTTYPE, CLIENTINVOICETYPE, IHCCLIENTCONTACTPERS, IHCCLIENTCP_STREET, IHCCLIENTCP_ZIP, IHCCLIENTCP_CITY, IHCCLIENT_GENDER, IHC_BILLTO_PAYMENTTERM_DESC, CLIENT_PAYMENTTYPE, CAPPEDCLIENTINVOICE, EXCESSINVFORMLAYOUTCODE
, NROFTAXES, TAXESONINVOICE, TAXESOVERAMOUNT, COUNTTAXLINES)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       a.invoicenumber, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, a.billtocustomername, (select cc.extraname1 from customer cc where cc.customer_id = a.billtocustomer_link_id) extraname1, (select cc.extraname2 from customer cc where cc.customer_id = a.billtocustomer_link_id)extraname2,
       a.deltocustomernumber, a.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,
       0 housenumber, --send 0 so it will not appear double on the invoice
       a.housenumberext,
       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, cu.invoicefrequency_id invoicefrequencynumber,
       b.code currencycode, b.description currencydesc,
       s.statustype, s.code statuscode, s.factorydescription statusfactorydescription,
       p2.code plantcode, p2.name plantname, x.street plantstreet,x.street2 plantstreet2, x.zipcode plantzipcode,
       x.city plantcity, x.state plantstate, x.county plantcounty, p2.phoneno plantphone,
       p2.faxno plantfax, p2.website plantwebsite, p2.email plantemail,
       p.name plantname_proc, p.phoneno plantphone_proc,
       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,
       ihextr.billtocountrydescription, ihextr.deltocountrydescription,
       ihextr.deltocustvatnumber,
       ihextr.customermarkinggarment, ihextr.taxable, ihextr.siccode, ihextr.invoicecopies,
       cu.taxable cust_taxable
, 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
       , ihextr.attachinvoicecopies, ihextr.paymenttermsdescription paymentterms_desc,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       rc.code Adjustment_ReasonCode
       , a.splitupcode, a.splitupdescription,
       ihs.personidentification, ihs.signature
       , 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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,
       a.nextperiodstartweek, a.nextperiodendweek,
       ihextr.paymenttype, ihextr.discountdays, ihextr.paymentdiscount, ihextr.discountdays2, ihextr.paymentdiscount2
       , cast(SS1.VALUE as numeric) WEIGHTDECIMALSMANUALINPUT
       , (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
       , (select empl.name from customerbillinginfo cbi, employee empl
          where cbi.customer_id = a.billtocustomer_link_id
                and empl.employee_id = cbi.collectionresponsible_id) collectionRespEmployee
        , null consolidated_invoice_layout
        , (select MIN(cp.name) from contactperson cp
           where cp.customer_id = a.deltocustomer_link_id
                 and cp.contactpersonnumber = (select min(cpp.contactpersonnumber)
                                               from contactperson cpp
                                               where cpp.customer_id = a.deltocustomer_link_id)) delto_contactpersonname
        , lg.code customer_languagecode
        , (select bc.legalname from customer bc where a.billtocustomer_link_id = bc.customer_id) BillToLegalName
        , ihc.client_link_id, ihc.clientnumber ihclientnumber, ihc.name ihclientname--501528
        , ihc.sendinvoiceto, ihc.roomnumber ihcroomnumber, ihc.clienttype ihcclienttype--501528
        , ihc.clientinvoicetype--502813
        , ccp.name ihcclientcontactpers
        , adr.street ihcclientcp_street
        , adr.zipcode ihcclientcp_zip
        , adr.city ihcclientcp_city
        , cl.gender ihcclient_gender
        , (select ptd.description
           from customerbillinginfo cbif, paymentterms_desc ptd
           where cbif.customer_id = a.billtocustomer_link_id
                 and cbif.paymentterms_id = ptd.paymentterms_id
                 and ptd.language_id = lg.language_id
           ) ihc_billto_paymentterm_desc
        ,  (select cbif.paymenttype from clientbillinginfo cbif where cbif.client_id = cl.client_id) client_paymenttype
        , (select cri.cappedclientinvoice from customerresidentialsettings cri where cri.customer_id = a.deltocustomer_link_id) cappedclientinvoice
        , (select fl.code from customerresidentialsettings cri, formlayout fl where cri.customer_id = a.deltocustomer_link_id and cri.excessamountinvoicelayout_id = fl.formlayout_id) excessinvformlayoutcode
        , (select count(distinct case when vtax.taxrate is null then 0 else vtax.taxrate end + case when vtax.percentage is null or vtax.percentage<0 then 0 else  vtax.percentage end ) from v_invoicetax_lts vtax where vtax.invoiceheader_id = a.invoiceheader_id) nroftaxes
        , case
          when (select max(cast(lpad(replace(pcv.version, '.', ''), 3) as numeric)) from product_component_version pcv) >= 112
          then case when cu.taxable = 'Y' then (select listagg(vtax1.taxrate,' ') within group (order by vtax1.taxrate)
               from (select distinct v.taxrate, v.invoiceheader_id
                 from v_invoicetax_lts v
                 order by  v.taxrate desc ) vtax1
                 where vtax1.invoiceheader_id = a.invoiceheader_id)
               else '0' end
          else 'OnlyFromOracleVersion11Release2'
          end taxesoninvoice
        , case
          when (select max(cast(lpad(replace(pcv.version, '.', ''), 3) as numeric)) from product_component_version pcv) >= 112
          then (select listagg(REPLACE(to_char(vtax2.amount),',','.'),' ') within group (order by vtax2.taxrate)
               from (select v.taxrate, v.invoiceheader_id, sum(v.amount) amount
                 from v_invoicetax_lts v
                 group by v.taxrate, v.invoiceheader_id
                 order by v.taxrate desc ) vtax2
                 where vtax2.invoiceheader_id = a.invoiceheader_id)
          else 'OnlyFromOracleVersion11Release2'
          end taxesoveramount
        , (select count(1) from v_invoicetax_lts v where v.invoiceheader_id = a.invoiceheader_id) countTaxLines
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
             inner join client_link clk
                   inner join client cl
                         left outer join clientcontactperson ccp
                              inner join address adr
                              on ccp.address_id = adr.address_id
                         on (cl.client_id = ccp.client_id and ccp.invoicecontactperson = 'Y')
                   on (clk.client_id = cl.client_id)
             on (ihc.client_link_id = clk.client_link_id)
        ON (a.invoiceheader_id = ihc.invoiceheader_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),
      customer cu, languages lg, plant p2
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 p2.address_id = x.address_id and p2.code = '07'--use p.code in other environments and fixed code '07' at LTS
      and p.country_id = country.country_id
      and a.invoiceheader_id = ihextr.invoiceheader_id
      and a.deltocustomer_link_id = cu.customer_id
      and cu.language_id = lg.language_id
      and (( a.parentinvoiceheader_id is not null and a.invoiceheader_id <> a.parentinvoiceheader_id
            and (select substr(iexcons.formlayoutcode,1,1)
             from invoiceheaderextrainfo iexcons
            where iexcons.invoiceheader_id = a.parentinvoiceheader_id) in ('1', '2') -- not in ('2', '3')
           )or
           (a.parentinvoiceheader_id = a.invoiceheader_id and substr(ihextr.formlayoutcode,1,1) in ('1', '2')) -- not in ('2', '3'))
           or a.parentinvoiceheader_id is null
          )

/
create or replace view V_INVOICELINE2_SMG
 (INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, DESCRIPTION, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, SUBJECTTOMINIMUM, PERCENTAGE, LANGUAGECODE, INVOICEHEADER_ID, OVERAMOUNT, INVOICELINE_SEQUENCENUMBER, SUPRESSPRINTING, PRODGRCODE, INVLINEWITPRODUCT, CURRENCYCODE)
as select f.invoicenumber,
       a.linenumber,
       a.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,
       a.description,
       a.extend,
       a.amount,
       a.discountpercentage,
       a.price,
       a.billedqty,
       a.subjecttominimum,
       c.percentage,
       LANGUAGES.CODE LANGUAGECODE,
       a.invoiceheader_id,
       c.overamount,
       (SELECT pilt.sequencenumber
          from plantinvoicelinetype pilt
         where pilt.plant_id =bu.plant_id
           and pilt.invoicelinetype_id = a.invoicelinetype_id) InvoiceLine_SequenceNumber,
       (SELECT pilt.suppressprinting
          from plantinvoicelinetype pilt--, businessunit bu, invoiceheader h
         where pilt.plant_id =bu.plant_id
           and pilt.invoicelinetype_id = a.invoicelinetype_id) supressprinting --502161
     , '' Prodgrcode, coalesce((select min(v.invoiceline_id) from v_invoiceline1_smg v where v.invoiceheader_id = a.invoiceheader_id), 0) invlinewitproduct
     , ( select cu.code from currency cu, invoiceheader ih where a.invoiceheader_id=ih.invoiceheader_id and ih.currency_id=cu.currency_id) currencycode
   from invoiceline a
   LEFT OUTER JOIN invoicelinevarious c ON (a.invoiceline_id = c.invoiceline_id)
   ,invoiceheader f, businessunit bu, LANGUAGES
 where a.invoiceheader_id = f.invoiceheader_id
   and f.invoicebusinessunit_id = bu.businessunit_id
   and not exists( select b.invoiceline_id from invoicelineproduct b where a.invoiceline_id = b.invoiceline_id)
   and f.documenttype in (1,3)

/
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_ISSUEHISTORY_SMG
 (YEAR, WEEK, DEPARTMENTNUMBER, DEPARTMENTDESC, WEARERNUMBER, WEARERNAME, PRODUCTCODE, PRODUCTDESC, SIZEDEFINITIONCODE, SIZEDEFINITIONDESC, QUANTITY, PREPCHARGE, INVOICEHEADER_ID, LANGUAGECODE, LANGUAGE_ID, FINMETHODCODE)
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
,      case when ( select uil.uniqueitem_id
                   from   uniqueitem_link uil
                   where  uil.uniqueitem_link_id = a.uniqueitem_link_id ) is null
            then ( select vpf.finmethodcode
                   from   v_ProdID_Finmethodcode_SMG vpf
                   where  vpf.product_id = p.product_id )
            else ( select fm.code
                   from   finishingmethod fm
                   where  fm.finishingmethod_id =
                     ( select ui.finishingmethod_id
                       from   uniqueitem ui
                       where  ui.uniqueitem_id =
                         ( select uil.uniqueitem_id
                           from uniqueitem_link uil
                           where  uil.uniqueitem_link_id = a.uniqueitem_link_id
                         )
                     )
                 )
       end finmethodcode
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_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, DATEACTIVE, DATEINACTIVE, PHONENO, CITY, SEARCHNAME_CUST, SEARCHNAME, PAYMENTMETHOD, COMPETITORCODE, LOSTREASONCODE, LOSTREASONDESC, LASTAMOUNT, AVGAMOUNT, BUSINESSUNITCODE, DIVISIONCODE, REGIONCODE, MARKETSEGMENTCODE, SALESAREACODE, CHAINCODE, DEPOTCODE, NO_OF_PRODUCTS, LANGUAGECODE, REPORTPARAM_ID, ROUTESTOPDATEINACTIVE)
as select distinct (case when rp.number_value2 = 0 then 1 else r.routenumber end) routenumber,
  cu.customer_id, cu.customernumber, cu.name customername, cu.dateactive, cu.dateinactive,
  cu.phoneno, ad.city, cu.searchname searchname_cust,
  '' searchname,
  cu.paymentmethod,  co.code competitorcode,
  '' lostreasoncode, '' 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(*)
  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, --contractspercustomer cpc,
  competitor co, --gainlostreason gr,employee em ,
  routestop rs, route r,
  depot dp,chain ch ,
  address ad,
  businessunit buc, division di, region re,
  marketsegment ms, salesarea sa,
  languages l, reportparam rp
where dp.depot_id(+) = r.depot_id
  and rs.route_id = r.route_id(+)
  and cu.customer_id = rs.customer_id(+)
  and ch.chain_id(+) = cu.chain_id
  and cu.visitaddress_id = ad.address_id
  and cu.defaultbusinessunit_id = buc.businessunit_id
  and buc.division_id = di.division_id
  and buc.region_id = re.region_id
  and cu.marketsegment_id = ms.marketsegment_id
  and cu.salesarea_id = sa.salesarea_id
  and ((co.code between rp.string_value5 and rp.string_value6) or co.code is null or rp.string_value5 is null)
  and  exists (select ca.customer_id
    from customeractivities ca, activity ac, businessunit bu, businessunitsperusergroup bug
    where cu.customer_id = ca.customer_id
      and ca.invoicebusinessunit_id = bu.businessunit_id
      and bu.businessunit_id = bug.businessunit_id
      and ca.activity_id = ac.activity_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)
  and not exists (select * from contractspercustomer cpc where cpc.customer_id = cu.customer_id )
union all
select distinct (case when rp.number_value2 = 0 then 1 else r.routenumber end) routenumber,
  cu.customer_id, cu.customernumber, cu.name customername, cu.dateactive, cu.dateinactive,
  cu.phoneno, ad.city, cu.searchname searchname_cust,
  em.searchname, cu.paymentmethod,
  co.code competitorcode,
  gr.code lostreasoncode,
  (select grd.description from gainlostreason_desc grd where grd.gainlostreason_id = gr.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(*)
  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, contractspercustomer cpc,
  competitor co, gainlostreason gr,employee em , routestop rs, route r,
  depot dp,chain ch ,
  address ad,
  businessunit buc, division di, region re,
  marketsegment ms, salesarea sa,
  languages l, reportparam rp
where cpc.customer_id = cu.customer_id
  and cpc.dateactive = (select max(cpc2.dateactive) from contractspercustomer cpc2 where cpc2.customer_id = cu.customer_id)
  and co.competitor_id(+) = cpc.lostcompetitor_id
  and em.employee_id(+) = cpc.salesemployee_id
  and  gr.gainlostreason_id(+) = cpc.lostreason_id
  and  dp.depot_id(+) = r.depot_id
  and rs.route_id = r.route_id(+)
  and cu.customer_id = rs.customer_id(+)
  and ch.chain_id(+) = cu.chain_id
  and cu.visitaddress_id = ad.address_id
  and cu.defaultbusinessunit_id = buc.businessunit_id
  and buc.division_id = di.division_id
  and buc.region_id = re.region_id
  and cu.marketsegment_id = ms.marketsegment_id
  and cu.salesarea_id = sa.salesarea_id
  and ((co.code between rp.string_value5 and rp.string_value6) or co.code is null or rp.string_value5 is null)
  and ((gr.code between rp.string_value7 and rp.string_value8) or gr.code is null or rp.string_value7 is null)
  and  exists (select ca.customer_id
    from customeractivities ca, activity ac, businessunit bu, businessunitsperusergroup bug
    where cu.customer_id = ca.customer_id
      and ca.invoicebusinessunit_id = bu.businessunit_id
      and bu.businessunit_id = bug.businessunit_id
      and ca.activity_id = ac.activity_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_LOSTBUSINESS_SGS
 (ROUTENUMBER, CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, DATEACTIVE, DATEINACTIVE, PHONENO, CITY, SEARCHNAME_CUST, PAYMENTMETHOD, COMPETITORCODE, LOSTREASONCODE, LOSTREASONDESC, LASTAMOUNT, BUSINESSUNITCODE, DIVISIONCODE, REGIONCODE, MARKETSEGMENTCODE, SALESAREACODE, CHAINCODE, DEPOTCODE, NO_OF_PRODUCTS, LANGUAGECODE, REPORTPARAM_ID, ROUTESTOPDATEINACTIVE, SEARCHNAME, SERVICEEMPLOYEENUMBER, AVGAMOUNT)
as select distinct (case when rp.number_value2 = 0 then 1 else r.routenumber end) routenumber,
  cu.customer_id, cu.customernumber, cu.name customername, cu.dateactive, cu.dateinactive,
  cu.phoneno, ad.city, cu.searchname searchname_cust,
  cu.paymentmethod,  '' competitorcode,
  '' lostreasoncode,
  '' lostreasondesc, F_GETINVOICEAMOUNT(cu.customer_id,1) lastamount,
  buc.code businessunitcode, di.code divisioncode, re.code regioncode,
  ms.code marketsegmentcode, sa.code salesareacode,
  ch.code chaincode, dp.code depotcode,
  (select count(*)
  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,
  (select em.name
          from employee em
         where cu.serviceemployee_id = em.employee_id) searchname,
         cast((select em.employeenumber
          from employee em
         where cu.serviceemployee_id = em.employee_id) as varchar(8)) serviceemployeenumber,
        (case p.typeofmerchandise
          when 1 then
            (select sum(rqa.quantity *
            pack_price.Rent_Price(cu.customer_id,
                             plpc.product_id,
                             plpc.sizedefinition_id,
                             plpc.finishingmethod_id,
                             rqa.adjustmentdate))
              from rentalqtyadjustment rqa, productlistperdistribpoint plpd
              where rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
              and plpd.product_id = plpc.product_id
              and plpd.sizedefinition_id = plpc.sizedefinition_id
              and plpd.finishingmethod_id = plpc.finishingmethod_id
              and rqa.sampleitem = 'N'
              and rqa.adjustmentdate <= rp.date_value2
              )
           when 2 then
                       case plpc.billingmethod
                         when 1 then (select sum(wi.changesperweek *
                            pack_price.Rent_Price(cu.customer_id,
                             plpc.product_id,
                             plpc.sizedefinition_id,
                             plpc.finishingmethod_id,
                             rp.date_value2,
                             wi.changesperweek))
                             from wearerinventory wi, weareremployment we, wearer w
                             where wi.product_id= plpc.product_id
                             and wi.sizedefinition_id = plpc.sizedefinition_id
                             and wi.finishingmethod_id = plpc.finishingmethod_id
                             and wi.weareremployment_id = we.weareremployment_id
                             and we.wearer_id = w.wearer_id
                             and w.customer_id = cu.customer_id
                             and wi.dateactive <= rp.date_value2
                             and wi.dateinactive >= rp.date_value1)
                         when 3 then (select sum(wi.circinventory *
                           pack_price.Rent_Price(cu.customer_id,
                             plpc.product_id,
                             plpc.sizedefinition_id,
                             plpc.finishingmethod_id,
                             rp.date_value2))
                             from wearerinventory wi, weareremployment we, wearer w
                             where wi.product_id= plpc.product_id
                             and wi.sizedefinition_id = plpc.sizedefinition_id
                             and wi.finishingmethod_id = plpc.finishingmethod_id
                             and wi.weareremployment_id = we.weareremployment_id
                             and we.wearer_id = w.wearer_id
                             and w.customer_id = cu.customer_id
                             and wi.dateactive <= rp.date_value2
                             and wi.dateinactive >= rp.date_value1
                               )
                         else 0  END
           else 0 END ) avgamount
from
  customer cu,
  routestop rs, route r,
  depot dp,chain ch ,
  address ad,
  businessunit buc, division di, region re,
  marketsegment ms, salesarea sa,
  languages l, reportparam rp,
  productlistpercustomer plpc, product p
where dp.depot_id(+) = r.depot_id
  and rs.route_id = r.route_id(+)
  and cu.customer_id = rs.customer_id(+)
  and ch.chain_id(+) = cu.chain_id
  and cu.visitaddress_id = ad.address_id
  and cu.defaultbusinessunit_id = buc.businessunit_id
  and buc.division_id = di.division_id
  and buc.region_id = re.region_id
  and cu.marketsegment_id = ms.marketsegment_id
  and cu.salesarea_id = sa.salesarea_id
  and  exists (select ca.customer_id
    from customeractivities ca, activity ac, businessunit bu, businessunitsperusergroup bug
    where cu.customer_id = ca.customer_id
      and ca.invoicebusinessunit_id = bu.businessunit_id
      and bu.businessunit_id = bug.businessunit_id
      and ca.activity_id = ac.activity_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)
  and not exists (select * from contractspercustomer cpc where cpc.customer_id = cu.customer_id )
  and cu.customer_id = plpc.customer_id
  and plpc.product_id = p.product_id
  and plpc.dateactive <= rp.date_value2
  and plpc.dateinactive >= rp.date_value1
union all
select distinct (case when rp.number_value2 = 0 then 1 else r.routenumber end) routenumber,
  cu.customer_id, cu.customernumber, cu.name customername, cu.dateactive, cu.dateinactive,
  cu.phoneno, ad.city, cu.searchname searchname_cust,
   cu.paymentmethod,
  co.code competitorcode,
  gr.code lostreasoncode,
  (select grd.description from gainlostreason_desc grd where grd.gainlostreason_id = gr.gainlostreason_id
    and grd.language_id = l.language_id) lostreasondesc,
  F_GETINVOICEAMOUNT(cu.customer_id,1) lastamount,
  buc.code businessunitcode, di.code divisioncode, re.code regioncode,
  ms.code marketsegmentcode, sa.code salesareacode,
  ch.code chaincode, dp.code depotcode,
  (select count(*)
  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,
  (select em.name
          from employee em
         where cu.serviceemployee_id = em.employee_id) searchname,
         cast((select em.employeenumber
          from employee em
         where cu.serviceemployee_id = em.employee_id) as varchar(8)) serviceemployeenumber,
         (case p.typeofmerchandise
          when 1 then
            (select sum(rqa.quantity *
            pack_price.Rent_Price(cu.customer_id,
                             plpc.product_id,
                             plpc.sizedefinition_id,
                             plpc.finishingmethod_id,
                             rqa.adjustmentdate))
              from rentalqtyadjustment rqa, productlistperdistribpoint plpd
              where rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
              and plpd.product_id = plpc.product_id
              and plpd.sizedefinition_id = plpc.sizedefinition_id
              and plpd.finishingmethod_id = plpc.finishingmethod_id
              and rqa.sampleitem = 'N'
              and rqa.adjustmentdate <= rp.date_value2
              )
           when 2 then
                       case plpc.billingmethod
                         when 1 then (select sum(wi.changesperweek *
                            pack_price.Rent_Price(cu.customer_id,
                             plpc.product_id,
                             plpc.sizedefinition_id,
                             plpc.finishingmethod_id,
                             rp.date_value2,
                             wi.changesperweek))
                             from wearerinventory wi, weareremployment we, wearer w
                             where wi.product_id= plpc.product_id
                             and wi.sizedefinition_id = plpc.sizedefinition_id
                             and wi.finishingmethod_id = plpc.finishingmethod_id
                             and wi.weareremployment_id = we.weareremployment_id
                             and we.wearer_id = w.wearer_id
                             and w.customer_id = cu.customer_id
                             and wi.dateactive <= rp.date_value2
                             and wi.dateinactive >= rp.date_value1)
                         when 3 then (select sum(wi.circinventory *
                           pack_price.Rent_Price(cu.customer_id,
                             plpc.product_id,
                             plpc.sizedefinition_id,
                             plpc.finishingmethod_id,
                             rp.date_value2))
                             from wearerinventory wi, weareremployment we, wearer w
                             where wi.product_id= plpc.product_id
                             and wi.sizedefinition_id = plpc.sizedefinition_id
                             and wi.finishingmethod_id = plpc.finishingmethod_id
                             and wi.weareremployment_id = we.weareremployment_id
                             and we.wearer_id = w.wearer_id
                             and w.customer_id = cu.customer_id
                             and wi.dateactive <= rp.date_value2
                             and wi.dateinactive >= rp.date_value1
                               )
                         else 0  END
           else 0 END ) avgamount
from
  customer cu, contractspercustomer cpc,
  competitor co, gainlostreason gr,employee em , routestop rs, route r,
  depot dp,chain ch ,
  address ad,
  businessunit buc, division di, region re,
  marketsegment ms, salesarea sa,
  languages l, reportparam rp,
  productlistpercustomer plpc, product p
where cpc.customer_id = cu.customer_id
  and cpc.dateactive = (select max(cpc2.dateactive) from contractspercustomer cpc2 where cpc2.customer_id = cu.customer_id)
  and co.competitor_id(+) = cpc.lostcompetitor_id
  and em.employee_id(+) = cpc.salesemployee_id
  and  gr.gainlostreason_id(+) = cpc.lostreason_id
  and  dp.depot_id(+) = r.depot_id
  and rs.route_id = r.route_id(+)
  and cu.customer_id = rs.customer_id(+)
  and ch.chain_id(+) = cu.chain_id
  and cu.visitaddress_id = ad.address_id
  and cu.defaultbusinessunit_id = buc.businessunit_id
  and buc.division_id = di.division_id
  and buc.region_id = re.region_id
  and cu.marketsegment_id = ms.marketsegment_id
  and cu.salesarea_id = sa.salesarea_id
  and ((co.code between rp.string_value5 and rp.string_value6) or co.code is null or rp.string_value5 is null)
  and ((gr.code between rp.string_value7 and rp.string_value8) or gr.code is null or rp.string_value7 is null)
  and  exists (select ca.customer_id
    from customeractivities ca, activity ac, businessunit bu, businessunitsperusergroup bug
    where cu.customer_id = ca.customer_id
      and ca.invoicebusinessunit_id = bu.businessunit_id
      and bu.businessunit_id = bug.businessunit_id
      and ca.activity_id = ac.activity_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)
  and cu.customer_id = plpc.customer_id
  and plpc.product_id = p.product_id
  and plpc.dateactive <= rp.date_value2
  and plpc.dateinactive >= rp.date_value1

/
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_NEWSTOCKVALUATION
 (REPORTPARAM_ID, PLANTCODE, BUSINESSUNITCODE, BUSINESSUNITDESC, STOCKROOMCODE, STOCKROOMDESC, PRODUCTGROUPCODE, PRODUCTGROUPDESC, PRODUCTCODE, PRODUCTDESC, SIZECODE, STOCKQTY, CUSTOMER_ID, CUSTOMEROWNED, PRICE, LANGUAGECODE)
as select rp.reportparam_id, pl.code plantcode, bu.code businessunitcode, bu.description businessunitdesc,
  sr.code stockroomcode, sr.name stockroomdesc,
  pg.code productgroupcode,
  (select pgd.description from productgroup_desc pgd
     where pgd.productgroup_id = pg.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,
  s.code 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, s.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,
  productgroup pg, product p, sizedefinition s, businessunit bu, languages lg, reportparam rp, plant pl
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 sdi.sizedefinition_id = s.sizedefinition_id
  and p.productgroup_id = pg.productgroup_id
  and srg.qualitygrade_id = q.qualitygrade_id
  and q.newgarment = 'Y'
  and bu.plant_id = pl.plant_id

/
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 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,
/*  (select max(pan.deliverydate)
   from packingnote pan, deliveryvariations dev, status s
   where dev.packingnote_id = pan.packingnote_id
     and dev.distributionpoint_id = v.distributionpoint_id
--     and dev.product_id = plpd.product_id
--     and dev.sizedefinition_id = plpd.sizedefinition_id
--     and dev.finishingmethod_id = plpd.finishingmethod_id
     and ((rp.number_value1 = 1 and dev.origin in (3,6))
       or (rp.number_value1 = 0))
     and pan.status_id = s.status_id and s.code = '30' --processed
     )*/ GETCURRENTDATE() lastdeliverydate,
  v.reportparam_id, l.code languagecode
from contactperson cp, contactpersonfunction cpf,
  v_notreceivedcustomerorders_d v
    left outer join (contactperson cpde
      left join contactpersonfunction cpfde
      on cpde.contactpersonfunction_id = cpfde.contactpersonfunction_id)
    on v.contactperson_id = cpde.contactperson_id,
  reportparam rp, languages l, v_notreceivedcustomerorders_c cu
where v.reportparam_id = rp.reportparam_id
  and v.customer_id = cp.customer_id
  and cp.contactpersonfunction_id = cpf.contactpersonfunction_id
  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)
  and v.isfordelivery = 1
  and v.customer_id = cu.customer_id
  and cu.existsdv = 0
  and cu.reportparam_id = rp.reportparam_id

/
create or replace view V_NOTSCANNEDITEMS
 (CUSTOMERNUMBER, CUSTOMERNAME, WEARERNUMBER, WEARERNAME, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, CUSTOMERLANGUAGEID, BUSINESSUNIT_ID, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDEFINITIONCODE, SIZEDEFINITIONDESCRIPTION, PRIMARYID, LASTSCANDATE, ISSUEDATE, STATUSCODE, STATUSDESCRIPTION, STAYNUMBER, STAYDESCRIPTION, LANGUAGELANGUAGEID, LANGUAGECODE, FINISHINGMETHODCODE, FINISHINGMETHODDESCRIPTION, FLAGCODE, BANK, LOCKER
, REPORTPARAM_ID, RESIDUALVALUE, CHAIN_CODE)
as select vl.customernumber, vl.customerName, vl.wearernumber, vl.wearerName, vl.departmentnumber
, vl.departmentDescription, vl.distributionpointnumber, vl.distributionpointDescription
, vl.customerLanguageID, vl.businessunit_id
, 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
from v_notscanneditems_line vl, v_notscanneditems_aux vx,  v_notscanneditems_outer vo
 where
    vl.uniqueitem_id = vx.uniqueitem_id
and vx.uniqueitem_id = vo.uniqueitem_id
    and vx.languageLanguageID = vo.languageLanguageID
and vo.uniqueitem_id = vl.uniqueitem_id
and vl.routefilter = 1

/
create or replace view V_NOTSCANNEDITEMSRV
 (CUSTOMERNUMBER, CUSTOMERNAME, WEARERNUMBER, WEARERNAME, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, CUSTOMERLANGUAGEID, BUSINESSUNIT_ID, BU_CODE, BU_DESC, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDEFINITIONCODE, SIZEDEFINITIONDESCRIPTION, PRIMARYID, LASTSCANDATE, ISSUEDATE, STATUSCODE, STATUSDESCRIPTION, STAYNUMBER, STAYDESCRIPTION, LANGUAGELANGUAGEID, LANGUAGECODE, WASHESTOTAL, FINISHINGMETHODCODE, FINISHINGMETHODDESCRIPTION
, BANK, LOCKER, REPORTPARAM_ID, RESIDUALVALUE, RVPERCENTAGE, SIZESEQUENCENR, CHAIN_CODE)
as select distinct vx.customernumber, vx.customerName, vx.wearernumber, vx.wearerName, vx.departmentnumber
, vx.departmentDescription, vx.distributionpointnumber, vx.distributionpointDescription
, vx.customerLanguageID, vx.businessunit_id, vx.BU_code, vx.BU_desc
, 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, vx.washestotal
, vo.finishingmethodCode, vo.finishingmethodDescription--, vo.flagCode
, vx.bank, vx.locker, vx.reportparam_id
, vx.residualvalue,vx.rvpercentage, vx.SizeSequenceNr,
vx.chain_code
from  v_notscanneditems_auxRV vx,  v_notscanneditems_outerRV vo
 where vx.languageLanguageID = vo.languageLanguageID
and vo.uniqueitem_id = vx.uniqueitem_id
and vo.reportparam_id = vx.reportparam_id

/
create or replace view V_NOTSCANNEDITEMS_CBD
 (CUSTOMERNUMBER, CUSTOMERNAME, WEARERNUMBER, WEARERNAME, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, CUSTOMERLANGUAGEID, BUSINESSUNIT_ID, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDEFINITIONCODE, SIZEDEFINITIONDESCRIPTION, PRIMARYID, LASTSCANDATE, ISSUEDATE, STATUSCODE, STATUSDESCRIPTION, STAYNUMBER, STAYDESCRIPTION, LANGUAGELANGUAGEID, LANGUAGECODE, FINISHINGMETHODCODE, FINISHINGMETHODDESCRIPTION, FLAGCODE, BANK, LOCKER
, REPORTPARAM_ID, SECONDARYID)
as select vl.customernumber, vl.customerName, vl.wearernumber, vl.wearerName, vl.departmentnumber
, vl.departmentDescription, vl.distributionpointnumber, vl.distributionpointDescription
, vl.customerLanguageID, vl.businessunit_id
, 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, Vx.Secondaryid
from v_notscanneditems_line vl, v_notscanneditems_aux_cbd vx,  v_notscanneditems_outer vo
 where
    vl.uniqueitem_id = vx.uniqueitem_id
and vx.uniqueitem_id = vo.uniqueitem_id
    and vx.languageLanguageID = vo.languageLanguageID
and vo.uniqueitem_id = vl.uniqueitem_id
and vl.routefilter = 1

/
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_ORDERFORM_ANG
 (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, ROUTENUMBER, DELIVERYDATE)
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, a.routenumber, a.DeliveryDate
from V_ORDERFORM_AUX_ANG 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, a.routenumber, a.DeliveryDate

/
create or replace view V_ORDERFORM_BUB
 (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, COLOUR)
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, a.colour
from V_ORDERFORM_AUX_BUB 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, a.colour

/
create or replace view V_ORDERFORM_CBD
 (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, PRODUCTGROUP_CODE, CUSTDELIVDAYS, SERVICEEMPLOYEE_ID
, PLANT_ID, EMPLOYEENAME, EMPLOYEEPHONENO, EMPLOYEEFAXNO, PLANT_PHONENO, PLANT_FAXNO)
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
, a.productgroup_code, a.CustDelivDays, a.serviceemployee_id, a.plant_id,
EMPLOYEE.NAME EMPLOYEENAME, EMPLOYEE.phoneno EMPLOYEEPHONENO, EMPLOYEE.faxno EMPLOYEEFAXNO,
plant.phoneno PLANT_PHONENO, plant.faxno PLANT_FAXNO
from V_ORDERFORM_AUX_CBD a
      LEFT OUTER JOIN EMPLOYEE ON (a.serviceemployee_id  = EMPLOYEE.EMPLOYEE_ID and a.PLANT_ID = EMPLOYEE.PLANT_ID), plant
where a.plant_id = plant.plant_id  and
( 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.productgroup_code
, a.orderingmethod, a.copy_number, a.sequencenumber, a.packingsequence, a.STREET, a.STREET2,a.deliverypoint_id, a.CustDelivDays,
a.serviceemployee_id, a.plant_id, EMPLOYEE.NAME, EMPLOYEE.phoneno, EMPLOYEE.faxno, plant.phoneno , plant.faxno

/
create or replace view V_ORDERFORM_ECL
 (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, LEGACYCUSTOMERNUMBER, COLORDESC)
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, a.legacycustomernumber, a.colordesc
from V_ORDERFORM_AUX_ECL 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, a.legacycustomernumber, a.colordesc

/
create or replace view V_ORDERFORM_LLG
 (REPORTPARAM_ID, COPY_NUMBER, CUSTOMERNUMBER, SEARCHNAME, CUSTOMERNAME, ADDRESS, ZIPCODE, CITY, DEPARTMENTNUMBER, DEPARTMENTNAME, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTNUMBERNAME, SIZEDEFINITIONCODE, SIZEDEFINITIONDESC, FINISHINGMETHODCODE, FINISHINGMETHODDESC, PRODUCTCODE, PRODUCTDESC, CUSTOMCODE, CUSTOMDESCRIPTION, CUSTOMER_ID, ORDERINGMETHOD, STREET, STREET2, SEQUENCENUMBER, PACKINGSEQUENCE, DELIVERYPOINT_ID, BUCODE, BUNAME, SOILCOUNTMETHOD)
as select A.REPORTPARAM_ID, a.copy_number, a.CUSTOMERNUMBER, a.searchname, 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.STREET, a.STREET2
, a.sequencenumber, a.packingsequence, a.deliverypoint_id, a.bucode, a.buname
, a.soilcountmethod
from V_ORDERFORM_AUX_LLG a
where a.DepActive='Y' or a.DistribActive='Y'
group by A.REPORTPARAM_ID, a.CUSTOMERNUMBER, a.searchname, 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, a.bucode, a.buname, a.soilcountmethod

/
create or replace view V_ORDERFORM_RRA
 (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, ROUTENUMBER, ROUTELISTINSTRUCTIONS)
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(a.amount) amount, sum(a.deliveries) deliveries
, a.orderingmethod, a.routenumber, a.routelistinstructions
from V_ORDERFORM_AUX_RRA 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.routenumber, a.routelistinstructions

/
create or replace view V_ORDERFORM_SHL
 (REPORTPARAM_ID, COPY_NUMBER, CUSTOMERNUMBER, CUSTOMERNAME, ADDRESS, ZIPCODE, CITY, STATE, DEPARTMENTNUMBER, DEPARTMENTNAME, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTNUMBERNAME, SIZEDEFINITIONCODE, SIZEDEFINITIONDESC, FINISHINGMETHODCODE, FINISHINGMETHODDESC, PRODUCTCODE, PRODUCTDESC, CUSTOMCODE, CUSTOMDESCRIPTION, CUSTOMER_ID, AMOUNT, ORDERINGMETHOD)
as select A.REPORTPARAM_ID, a.copy_number, a.CUSTOMERNUMBER, a.CUSTOMERNAME, a.ADDRESS, a.ZIPCODE, a.CITY, a.State,
  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(a.amount) amount--, sum(a.deliveries) deliveries
, a.orderingmethod
from V_ORDERFORM_AUX_shl 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.State, 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

/
create or replace view V_ORDERFORM_SMG
 (REPORTPARAM_ID, COPY_NUMBER, CUSTOMERNUMBER, CUSTNR, CUSTOMERNAME, ZIPCODE, CITY, DEPARTMENTNUMBER, DEPARTMENTNAME, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTNUMBERNAME, PRODUCTCODE, PRODUCTDESC, CUSTOMCODE, CUSTOMDESCRIPTION, CUSTOMER_ID, ORDERINGMETHOD, STREET, STREET2, CPL, PACKINGSEQUENCE, ROUTENRDESC, DELIVERYPOINT_ID, INTERNALPROCBU)
as select A.REPORTPARAM_ID, a.copy_number, a.CUSTOMERNUMBER,a.custnr,
 a.CUSTOMERNAME, a.ZIPCODE, a.CITY, a.DEPARTMENTNUMBER, a.DEPARTMENTNAME,
  a.DISTRIBUTIONPOINTNUMBER, a.DISTRIBUTIONPOINTNUMBERNAME, a.PRODUCTCODE, a.PRODUCTDESC, a.CUSTOMCODE, a.CUSTOMDESCRIPTION,
  a.CUSTOMER_ID,  a.orderingmethod,a.STREET, a.STREET2, a.cpl cpl
, a.packingsequence, a.RouteNRDesc, a.deliverypoint_id, a.internalprocbu
from V_ORDERFORM_AUX_smg a
group by A.REPORTPARAM_ID, a.CUSTOMERNUMBER,a.custnr, a.CUSTOMERNAME,  a.ZIPCODE, a.CITY, a.DEPARTMENTNUMBER, a.DEPARTMENTNAME,
  a.DISTRIBUTIONPOINTNUMBER, a.DISTRIBUTIONPOINTNUMBERNAME, a.PRODUCTCODE, a.PRODUCTDESC, a.CUSTOMCODE, a.CUSTOMDESCRIPTION,
  a.CUSTOMER_ID,a.orderingmethod, a.copy_number, a.packingsequence,a.STREET, a.STREET2,a.cpl, a.RouteNRDesc, a.deliverypoint_id,a.internalprocbu

/
create or replace view V_ORDERFORM_STK
 (REPORTPARAM_ID, COPY_NUMBER, CUSTOMERNUMBER, CUSTOMERNAME, SICCODE, ADDRESS, ZIPCODE, CITY, DEPARTMENTNUMBER, DEPARTMENTNAME, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTNUMBERNAME, SIZEDEFINITIONCODE, SIZEDEFINITIONDESC, FINISHINGMETHODCODE, FINISHINGMETHODDESC, PRODUCTCODE, PRODUCTDESC, CUSTOMCODE, CUSTOMDESCRIPTION, CUSTOMER_ID, AMOUNT, DELIVERIES, ORDERINGMETHOD, SEQUENCENUMBER, PACKINGSEQUENCE)
as select A.REPORTPARAM_ID, a.copy_number, a.CUSTOMERNUMBER, a.CUSTOMERNAME, a.siccode  --, NHI for STK 29-07-2010
, 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.sequencenumber, a.packingsequence
from V_ORDERFORM_AUX_STK a
where a.DepActive='Y' or a.DistribActive='Y'
group by A.REPORTPARAM_ID, a.CUSTOMERNUMBER, a.CUSTOMERNAME, a.siccode  --, NHI for STK 29-07-2010
, 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

/
create or replace view V_ORDERFORM_VOS
 (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, SEQUENCENUMBER, PACKINGSEQUENCE)
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.sequencenumber
,        a.packingsequence
from     v_orderform_aux_vos 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

/
create or replace view V_OUTOFCIRCULATIONHISTORY_SMG
 (OUTOFCIRCYEAR, OUTOFCIRCWEEK, DEPARTMENTNUMBER, DEPARTMENTDESC, WEARERNUMBER, WEARERNAME, PRODUCTCODE, PRODUCTDESC, REASONCODE, REASONDESC, RAGREASONCODE, RAGREASONDESC, INCIRCDATE, OUTOFCIRCDATE, TOBECHARGEDPERCENTAGE, RESIDUALVALUE, INVOICEHEADER_ID, CHARGETYPE, STATUS, INVOICECATEGORY, LANGUAGECODE, LANGUAGE_ID, BASEVALUE, SIZECODE, FINMETHODCODE)
as select a.outofcircyear
,      a.outofcircweek
,      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
,      b.code reasoncode
,      ( select description
         from   reasoncode_desc x
         where  x.reasoncode_id = a.reasoncode_id
            and x.language_id = languages.language_id ) reasondesc
,      c.code ragreasoncode
,      ( select 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
,      a.invoiceheader_id
,      a.chargetype
,      a.status
,      b.invoicecategory
,      languages.code languagecode
,      languages.language_id
,      residualvalue basevalue -- 20015217
,      ( select sdl.code
         from   sizedefinition_link sdl
         where  sdl.sizedefinition_link_id = a.sizedefinition_link_id) sizecode -- 20015217
,      ( select vpf.finmethodcode
         from   V_ProdID_Finmethodcode_SMG vpf
         where  vpf.product_id = p.product_id ) finmethodcode -- 20015217
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_PACKINGNOTELINE_REV
 (PACKINGNOTEID, PRODUCTGROUPCODE, PRODUCTCODE, PRODUCTDESCRIPTION, ACTIVITYCODE, ACTIVITYDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, FINISHINGMETHODCODE, PACKINGSEQUENCE, PACKINGAMOUNT, THEORETICALWEIGHT, STANDARDAMOUNT, VARIATIONAMOUNT, DELIVEREDAMOUNT, TOBEDELIVEREDAMOUNT, NODELIVERYAMOUNT, PRICE, DISCOUNT, LOCATION, REMARKFORPACKINGINSTRUCTIONS, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE, BULKPUTUP
, PUTUPTYPE, PACKINGNOTELINE_ID, PACKINGAMOUNTPSZ, BUNDLEQTY, PRODUCT_ID, ISPACK, PRICECOG, SEQUENCENUMBER, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, PACKPROD_CODE, PACKPROD_PROD_DESC, PACKPROD_AMOUNT, DELIVERYSCHEME_CODE, TOBEDELIVEREDQTY)
as select --correct index to be used + INDEX(packingnoteline, XIF29PACKINGNOTELINE) --
  packingnoteline.packingnote_id packingnoteid,
  productgroup.code,
  product.code productcode,
  (select description from product_desc p where p.product_id = packingnoteline.product_id
     and p.language_id = languages.language_id)  productdescription,
  activity.code activitycode,
  (select description from activity_desc ad where ad.activity_id = activity.activity_id
     and ad.language_id = languages.language_id)  activitydescription,
  packingnoteline.customcode,
  packingnoteline.customdescription,
  sizedefinition.code sizecode,
  (select description from sizedefinition_desc s where s.sizedefinition_id = packingnoteline.sizedefinition_id
     and s.language_id = languages.language_id)  sizedescription,
  (select description from finishingmethod_desc f where f.finishingmethod_id = packingnoteline.finishingmethod_id
     and f.language_id = languages.language_id)  finishingmethoddescription,
  finishingmethod.code finishingmethodcode,
  packingnoteline.packingsequence, product.packingamount,
  case
   when psz.theoreticalweight = 0 then product.theoreticalweight
   else psz.theoreticalweight
   end  theoreticalweight,
  packingnoteline.standardamount, packingnoteline.variationamount,
  packingnoteline.deliveredamount, packingnoteline.tobedeliveredamount,
  packingnoteline.nodeliveryamount nodeliveryamount,
  (case when packingnoteline.price is null then 0 else packingnoteline.price end) price, packingnoteline.discount, packingnoteline.location,
  packingnoteline.remarkforpackinginstructions, packingnoteline.systemuser_id, packingnoteline.timestamp,
  languages.code languagecode,
  case when packingnoteline.putuptype = 2 then 'Y' else 'N' end bulkputup, packingnoteline.putuptype,
  packingnoteline.packingnoteline_id, psz.packingamount packingamountpsz,
  packingnoteline.bundleqty,
  product.product_id, product.pack ispack,
  coalesce(packingnoteline.pricecog, 0) pricecog
, psz.sequencenumber, packingnoteline.nochargeprevshortage, packingnoteline.nochargeprevrejected
, (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 = languages.language_id) Packprod_prod_desc
,  pc.amount Packprod_amount
, v.CODE DELIVERYSCHEME_CODE, v.TOBEDELIVEREDQTY
from packingnoteline
  left outer join packcontents pc on pc.pack_id = packingnoteline.product_id
  left outer join V_PACKINGNOTELNPERDELSCH V on v.PACKINGNOTELINE_ID = packingnoteline.packingnoteline_id
  , finishingmethod, product,productgroup, activity, sizedefinition, languages, productsize psz
where packingnoteline.product_id = product.product_id
  and packingnoteline.sizedefinition_id = sizedefinition.sizedefinition_id
  and productgroup.productgroup_id = product.productgroup_id
  and finishingmethod.finishingmethod_id = packingnoteline.finishingmethod_id
      and product.product_id = psz.product_id
          and psz.sizedefinition_id = sizedefinition.sizedefinition_id
  and productgroup.activity_id = activity.activity_id

/
create or replace view V_PACKINGNOTELINE_SMG
 (PACKINGNOTEID, PRODUCTGROUPCODE, PRODUCTCODE, PRODUCTDESCRIPTION, ACTIVITYCODE, ACTIVITYDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, FINISHINGMETHODCODE, PACKINGSEQUENCE, PACKINGAMOUNT, THEORETICALWEIGHT, STANDARDAMOUNT, VARIATIONAMOUNT, DELIVEREDAMOUNT, TOBEDELIVEREDAMOUNT, NODELIVERYAMOUNT, PRICE, DISCOUNT, LOCATION, REMARKFORPACKINGINSTRUCTIONS, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE, BULKPUTUP
, PUTUPTYPE, PACKINGNOTELINE_ID, PACKINGAMOUNTPSZ, BUNDLEQTY, PRODUCT_ID, ISPACK, PRICECOG, SEQUENCENUMBER, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, ORIGIN, COUNTVARIATIONS)
as SELECT PACKINGNOTELINE.PACKINGNOTE_ID,--PACKINGNOTE.PACKINGNOTE_ID,
  PRODUCTGROUP.CODE, --PACKINGNOTE.NOTENUMBER,
  PRODUCT.CODE PRODUCTCODE,
  (SELECT DESCRIPTION FROM PRODUCT_DESC P WHERE P.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
     AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  PRODUCTDESCRIPTION, -- PRODUCTDESCRIPTION
  ACTIVITY.CODE ACTIVITYCODE,
  (SELECT DESCRIPTION FROM ACTIVITY_DESC AD WHERE AD.ACTIVITY_ID = ACTIVITY.ACTIVITY_ID
     AND AD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  ACTIVITYDESCRIPTION,
  PACKINGNOTELINE.CUSTOMCODE,
  PACKINGNOTELINE.CUSTOMDESCRIPTION, -- PRODUCTCUSTOMDESCRIPTION
  SIZEDEFINITION.CODE SIZECODE,
  (SELECT DESCRIPTION FROM SIZEDEFINITION_DESC S WHERE S.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID
     AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  SIZEDESCRIPTION,
  (SELECT DESCRIPTION FROM FINISHINGMETHOD_DESC F WHERE F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
     AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  FINISHINGMETHODDESCRIPTION,
  FINISHINGMETHOD.CODE FINISHINGMETHODCODE,
  PACKINGNOTELINE.PACKINGSEQUENCE, PRODUCT.PACKINGAMOUNT,
  CASE
   WHEN PSZ.THEORETICALWEIGHT = 0 THEN PRODUCT.THEORETICALWEIGHT
   ELSE PSZ.THEORETICALWEIGHT
   END  THEORETICALWEIGHT,
--  PRODUCT.THEORETICALWEIGHT
  PACKINGNOTELINE.STANDARDAMOUNT, PACKINGNOTELINE.VARIATIONAMOUNT,
  PACKINGNOTELINE.DELIVEREDAMOUNT, PACKINGNOTELINE.TOBEDELIVEREDAMOUNT,
  PACKINGNOTELINE.NODELIVERYAMOUNT NODELIVERYAMOUNT,
  (CASE WHEN PACKINGNOTELINE.PRICE IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICE END) PRICE, PACKINGNOTELINE.DISCOUNT, PACKINGNOTELINE.LOCATION,
  PACKINGNOTELINE.REMARKFORPACKINGINSTRUCTIONS, PACKINGNOTELINE.SYSTEMUSER_ID, PACKINGNOTELINE.TIMESTAMP,
  LANGUAGES.CODE LANGUAGECODE,
  CASE WHEN PACKINGNOTELINE.PUTUPTYPE = 2 THEN 'Y' ELSE 'N' END BULKPUTUP, PACKINGNOTELINE.PUTUPTYPE,
  PACKINGNOTELINE.PACKINGNOTELINE_ID, PSZ.PACKINGAMOUNT PACKINGAMOUNTPSZ,
  PACKINGNOTELINE.BUNDLEQTY,
  PRODUCT.PRODUCT_ID, PRODUCT.PACK ISPACK,
  (CASE WHEN PACKINGNOTELINE.PRICECOG IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICECOG END) PRICECOG
  , PSZ.SEQUENCENUMBER, PACKINGNOTELINE.NOCHARGEPREVSHORTAGE, PACKINGNOTELINE.NOCHARGEPREVREJECTED
  , PACKINGNOTELINE.Origin
  , (select count(1) from v_packingnotevariation v where v.packingnoteline_id = packingnoteline.packingnoteline_id and v.packingnote_id = packingnoteline.packingnote_id) countvariations
FROM PACKINGNOTELINE , FINISHINGMETHOD ,
      --PACKINGNOTE,
      PRODUCT,PRODUCTGROUP, ACTIVITY,
      SIZEDEFINITION, LANGUAGES
      , PRODUCTSIZE PSZ
WHERE --PACKINGNOTELINE.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID
  --AND
   PACKINGNOTELINE.PRODUCT_ID = PRODUCT.PRODUCT_ID
  AND PACKINGNOTELINE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
  AND PRODUCTGROUP.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID
  AND FINISHINGMETHOD.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
      AND PRODUCT.PRODUCT_ID = PSZ.PRODUCT_ID
          AND PSZ.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
  AND PRODUCTGROUP.ACTIVITY_ID = ACTIVITY.ACTIVITY_ID

/
create or replace view V_PACKINGNOTE_ECL
 (PACKINGNOTEID, STATUSTYPE, DRIVINGDATE, DEPOTCODE, DEPOTDESCRIPTION, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERLEGALNAME, STREET, STREET2, CITY, STATE, ZIPCODE, COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, PACKINGDEPARTMENTCODE, PACKINGDEPARTMENTDESCRIPTION, TRANSPORTARTICLECODE, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENUMBER, EMPLOYEENAME
, PRODUCTIONDATE, DELIVERYDATE, STATUSCODE, STATUSDESCRIPTION, REMARK, PROCESSBUCODE, PROCESSBUDESCRIPTION, INVOICEBUCODE, INVOICEBUDESCRIPTION, ROUTENUMBER, ROUTEDESCRIPTION, LOADINGDOCK, CLEANRETURN, DEADLINE, DEADLINEASNUMERIC, CONSIGNMENTNOTENUMBER, SYSTEMUSER_ID, TIMESTAMP, CREATIONTIMESTAMP, ENDDATEFORUSE, DAYDESCRIPTION, WEEK, LANGUAGECODE, DRIVERNAME, DRIVERNUMBER, BULKPUTUPONPACKINGNOTE, YEAR, PACKINGNOTECOLUMNS, LASTDELIVERYDAY, STOPNUMBER, PUTUPREPORTPERCUSTOMER
, EXTRANAME1, LAYOUTCODE, WEIGHTUNIT, DAYCODE, STANDARDSBASEDON, TOTALWEIGHT, CUSTOMERRANK, DAYNUMBER)
as SELECT PACKINGNOTE.PACKINGNOTE_ID PACKINGNOTEID,STATUS.STATUSTYPE,  ROUTECONTROL.DRIVINGDATE, DEPOT.CODE DEPOTCODE, DEPOT.DESCRIPTION DEPOTDESCRIPTION,
 PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME CUSTOMERLEGALNAME,
 ADDRESS.STREET, ADDRESS.STREET2, ADDRESS.CITY, ADDRESS.STATE, ADDRESS.ZIPCODE, ADDRESS.COUNTY,
 DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
 DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
  DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
 PACKINGNOTE.SEQUENCENUMBER, PLANTDEPARTMENT.CODE PACKINGDEPARTMENTCODE, PLANTDEPARTMENT.DESCRIPTION PACKINGDEPARTMENTDESCRIPTION,
 TRANSPORTARTICLE.CODE TRANSPORTARTICLECODE,
 (SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
 PACKINGNOTE.OCCUPANCY, EMPLOYEE.EMPLOYEENUMBER, EMPLOYEE.NAME EMPLOYEENAME,
 PACKINGNOTE.PRODUCTIONDATE,
 PACKINGNOTE.DELIVERYDATE,
 STATUS.CODE STATUSCODE,
 (SELECT DESCRIPTION FROM STATUS_DESC S WHERE S.STATUS_ID = PACKINGNOTE.STATUS_ID AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) STATUSDESCRIPTION,
 PACKINGNOTE.PNREMARK REMARK, PROCESSBU.CODE PROCESSBUCODE, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
 INVOICEBU.CODE INVOICEBUCODE, INVOICEBU.DESCRIPTION INVOICEBUDESCRIPTION,
 ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION ROUTEDESCRIPTION,ROUTE.LOADINGDOCK,
 PACKINGNOTE.CLEANRETURN,
 PACKINGNOTE.DEADLINE,
 GETTIMEASNUMERIC(PACKINGNOTE.DEADLINE) DEADLINEASNUMERIC,
 CONSIGNMENTNOTE.CONSIGNMENTNOTENUMBER,
 PACKINGNOTE.SYSTEMUSER_ID, PACKINGNOTE.TIMESTAMP,PACKINGNOTE.CREATIONTIMESTAMP,
 PACKINGNOTE.ENDDATEFORUSE,
 (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,
  DRIVER.NAME DRIVERNAME,
  DRIVER.EMPLOYEENUMBER DRIVERNUMBER
  , CASE WHEN CUSTOMER.DELNOTEFORBULKPUTUPITEMS = 0 THEN  'N' ELSE 'Y' END BULKPUTUPONPACKINGNOTE,
  PACKINGNOTE.YEAR YEAR
  , (SELECT SS.VALUE FROM SYSTEMSETTING SS WHERE SS.PLANT_ID = PROCESSBU.PLANT_ID
            AND SS.NAME = 'PACKINGNOTECOLUMNS') PACKINGNOTECOLUMNS
  , (SELECT max( CDD.DAY_ID ) FROM CUSTOMERDELIVERYDAY CDD WHERE CUSTOMER.CUSTOMER_ID = CDD.CUSTOMER_ID) LastDeliveryDay,
        PACKINGNOTE.STOPNUMBER, ROUTE.PUTUPREPORTPERCUSTOMER,
		CUSTOMER.EXTRANAME1,
(select fly.code from formlayout fly where fly.formlayout_id = CUSTOMER.deliverynotelayout_id) layoutcode
  , (SELECT cast (SS.VALUE as varchar2(60)) FROM SYSTEMSETTING SS WHERE SS.PLANT_ID = PROCESSBU.PLANT_ID
            AND SS.NAME = 'WEIGHTUNIT') WEIGHTUNIT,
 (SELECT CODE FROM DAY_DESC WHERE DAY_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID AND DAY_DESC.DAY_ID = PACKINGNOTE.DAYNUMBER) DAYCODE
 , CUSTOMER.Standardsbasedon
, coalesce((select sum(l.THEORETICALWEIGHT) from V_PACKINGNOTELINE_ECL l
            where l.PACKINGNOTEID = packingnote.packingnote_id and l.LANGUAGECODE = languages.code),
               (select sum(vk.grossweight - vk.tareweight - vk.soilportion) from PACKINGNOTECONTAINER vk
                where vk.packingnote_id = PACKINGNOTE.PACKINGNOTE_ID)) TotalWeight
, coalesce((select cra.priority from customerranking cra --0 Standard, 1 At Risk 2 Priority
  where cra.customerranking_id = customer.customerranking_id), 0) CustomerRank--default Standard
, PACKINGNOTE.DAYNUMBER
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, PLANTDEPARTMENT,
       TRANSPORTARTICLE,STATUS, DELIVERYPOINT, ADDRESS,
       BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU,
       PACKINGNOTE
       LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
       LEFT OUTER JOIN ROUTECONTROL ON (PACKINGNOTE.ROUTECONTROL_ID = ROUTECONTROL.ROUTECONTROL_ID )
       LEFT OUTER JOIN CONSIGNMENTNOTE ON (PACKINGNOTE.CONSIGNMENTNOTE_ID = CONSIGNMENTNOTE.CONSIGNMENTNOTE_ID)
       LEFT OUTER JOIN ROUTE ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID
              LEFT OUTER JOIN DEPOT ON DEPOT.DEPOT_ID=ROUTE.DEPOT_ID
              LEFT OUTER JOIN EMPLOYEE DRIVER ON DRIVER.EMPLOYEE_ID=ROUTE.DRIVER_ID,
       LANGUAGES
 	WHERE
      PACKINGNOTE.TRANSPORTARTICLE_ID = TRANSPORTARTICLE.TRANSPORTARTICLE_ID
  AND PACKINGNOTE.STATUS_ID = STATUS.STATUS_ID
  AND STATUS.STATUSTYPE = 'PN'  --AND (STATUS.CODE='10' OR STATUS.CODE ='20' OR STATUS.CODE ='5')
  AND CAST(STATUS.CODE AS NUMERIC)<=20
  AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = ADDRESS.ADDRESS_ID
	AND PACKINGNOTE.PLANTDEPARTMENT_ID = PLANTDEPARTMENT.PLANTDEPARTMENT_ID
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
	AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  AND PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
	AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
	AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_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_PICKORDER_SMG
 (WORKORDER_ID, WORKORDERNUMBER, WOORIGIN, EXPECTEDCOMPLETEDATE, ORDERREMARK, DELIVERYDATE, EXTERNALPRINTTIMESTAMP, 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, ALLOWPHASEDELIVERY, OOSPRODUCT)
as select
wok.workorder_id, wok.workordernumber, wok.origin,wok.expectedcompletedate
, wok.remark OrderRemark, wok.neededdate DeliveryDate
, wok.externalprinttimestamp
, to_char(wok.externalprinttimestamp) pickorderdate
, to_char(wok.externalprinttimestamp,'fmhh24fm:MI') 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-wol.quantityphasein) qtyfullfilled
, (wol.quantityordered - wol.quantitycancelled - wol.quantityfilled) qtyopen
, wol.quantitypicked qtypicked
, wol.instructions wol_remark
, wol.workorderline_id workorderlineid
,(select b.code from businessunit  b where b.businessunit_id=f_getintprocbuid(wok.workorder_id)) intprocessbu_code
 , (select b.description from businessunit  b where b.businessunit_id=f_getintprocbuid(wok.workorder_id)) intprocessbu_desc
, (select b.code from businessunit  b where b.businessunit_id=f_getprocbuid(wok.workorder_id)) processbu_code
, (select b.description from businessunit  b where b.businessunit_id=f_getprocbuid(wok.workorder_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_getrowcodeloc_smg(wol.product_link_id,wol.sizedefinition_link_id,wol.requestedgrade_id,wok.processingstockroom_id,wol.codeuniquely, 'Y') rowcode
, f_getrowcodeloc_smg(wol.product_link_id, wol.sizedefinition_link_id, wol.requestedgrade_id, wok.processingstockroom_id, wol.codeuniquely, 'F') 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
,wok.allowphasedelivery
,(select coalesce( oosp.status,0)
                from  stockdefinitionperitem sdi,stockreservationpergrade srg
                left outer join outofserviceproduct oosp on srg.stockreservationpergrade_id=oosp.stockreservationpergrade_id
                where srg.stockdefinitionperitem_id=sdi.stockdefinitionperitem_id
                and sdi.stockroom_id=wok.processingstockroom_id
                and sdi.product_id=wol.product_link_id
                and sdi.sizedefinition_id=wol.sizedefinition_link_id
                and srg.qualitygrade_id=wol.requestedgrade_id
                and sdi.customer_id is null
                and (oosp.sequencenumber is null or oosp.sequencenumber=( select max(oosp1.sequencenumber) from outofserviceproduct oosp1
                where oosp1.stockreservationpergrade_id=srg.stockreservationpergrade_id)))OOSProduct
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 left outer join customerranking cr on cu.customerranking_id = cr.customerranking_id)
                         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
    and ( cr.ranking is null or  cr.ranking <> 'ITM' or wok.origin =6)
UNION
select
wok.workorder_id, wok.workordernumber, wok.origin,wok.expectedcompletedate
, wok.remark OrderRemark, wok.neededdate DeliveryDate
, wok.externalprinttimestamp
, to_char(wok.externalprinttimestamp) pickorderdate
, to_char(wok.externalprinttimestamp,'fmhh24fm:MI') 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-wol.quantityphasein) qtyfullfilled
, (wol.quantityordered - wol.quantitycancelled - wol.quantityfilled) qtyopen
, wol.quantitypicked qtypicked
, wol.instructions wol_remark
, wol.workorderline_id workorderlineid
,(select b.code from businessunit  b where b.businessunit_id=f_getintprocbuid(wok.workorder_id)) intprocessbu_code
 , (select b.description from businessunit  b where b.businessunit_id=f_getintprocbuid(wok.workorder_id)) intprocessbu_desc
, (select b.code from businessunit  b where b.businessunit_id=f_getprocbuid(wok.workorder_id)) processbu_code
, (select b.description from businessunit  b where b.businessunit_id=f_getprocbuid(wok.workorder_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_getrowcodeloc_smg(wol.product_link_id,wol.sizedefinition_link_id,wol.requestedgrade_id,wok.processingstockroom_id,wol.codeuniquely, 'Y') rowcode
, f_getrowcodeloc_smg(wol.product_link_id, wol.sizedefinition_link_id, wol.requestedgrade_id, wok.processingstockroom_id, wol.codeuniquely, 'F') 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
,wok.allowphasedelivery
,(select coalesce( oosp.status,0)
                from  stockdefinitionperitem sdi,stockreservationpergrade srg
                left outer join outofserviceproduct oosp on srg.stockreservationpergrade_id=oosp.stockreservationpergrade_id
                where srg.stockdefinitionperitem_id=sdi.stockdefinitionperitem_id
                and sdi.stockroom_id=wok.processingstockroom_id
                and sdi.product_id=wol.product_link_id
                and sdi.sizedefinition_id=wol.sizedefinition_link_id
                and srg.qualitygrade_id=wol.requestedgrade_id
                and sdi.customer_id is null
                and (oosp.sequencenumber is null or oosp.sequencenumber=( select max(oosp1.sequencenumber) from outofserviceproduct oosp1
                where oosp1.stockreservationpergrade_id=srg.stockreservationpergrade_id)))OOSProduct
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 left outer join customerranking cr on cus.customerranking_id = cr.customerranking_id)
   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
    and ( cr.ranking is null or  cr.ranking <> 'ITM' or wok.origin= 6 )

/
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_PRICESPERCUSTOMER_LLG
 (CUSTOMER_ID, DEFAULTBUSINESSUNIT_ID, DEFAULTINVOICEBUSINESSUNIT_ID, REPORTPARAM_ID, TIMESTAMP, DATE_VALUE1, CUSTOMERNUMBER, CUSTOMERNAME, CITY, CURRENCYCODE, DECIMALS, HEAVILYSOILED, LOAN, 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(cwp.customerwashprice_id) from customerwashprice cwp, productlistpercustomer plpc
           where plpc.productlistpercustomer_id = cwp.productlistpercustomer_id
           and plpc.customer_id = cu.customer_id
           and rp.date_value1 >= cwp.startdate
           and cwp.pricetype = 5) heavilysoiled
, ( select count(crp.customerrentprice_id) from customerrentprice crp, productlistpercustomer plpc
           where plpc.productlistpercustomer_id = crp.productlistpercustomer_id
           and plpc.customer_id = cu.customer_id
           and rp.date_value1 >= crp.startdate
           and crp.typeofrent = 10) loan
, ( 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_PRICESPERCUSTOMER_LTS
 (PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, PLANTNAME_PROC, PLANTPHONE_PROC, DEBTOR_ID, CUSTOMER_LANGUAGECODE, BILLTOLEGALNAME, BILLTOEXTRANAME1, HOUSENUMBER, BILLTOSTREET, BILLTOHOUSENUMBEREXT, BILLTOCITY, BILLTOZIPCODE, BILLTOCOUNTRY, CUSTOMERNUMBER, CUSTOMERNAME, CITY, DELTOSTREET, DELTOZIPCODE, CUSTOMER_ID, DEFAULTBUSINESSUNIT_ID, DEFAULTINVOICEBUSINESSUNIT_ID, REPORTPARAM_ID
, TIMESTAMP, DATE_VALUE1, CURRENCYCODE, DECIMALS, WASH, WEIGHT, REPAIR, INSURANCE, BUSINESSUNIT_ID, BU_CODE, BU_DESC)
as select
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,
p.name plantname_proc, p.phoneno plantphone_proc,
cu.debtor_id,
lg.code customer_languagecode,
(select bc.legalname from customer bc where bc.customer_id=cu.debtor_id) Billtolegalname,
(select bc.extraname1 from customer bc where bc.customer_id=cu.debtor_id) billtoextraname1,
0 housenumber,
(select a.street from customer bc,address a where bc.customer_id=cu.debtor_id and a.address_id=bc.mailaddress_id) billtostreet,
(select a.housenumberext from customer bc,address a where bc.customer_id=cu.debtor_id and a.address_id=bc.mailaddress_id) billtohousenumberext,
(select a.city from customer bc,address a where bc.customer_id=cu.debtor_id and a.address_id=bc.mailaddress_id) billtocity,
(select a.zipcode from customer bc,address a where bc.customer_id=cu.debtor_id and a.address_id=bc.mailaddress_id) billtozipcode,
(select co.description from customer bc,country co where bc.country_id=co.country_id and bc.customer_id=cu.debtor_id) billtocountry,
cu.customernumber,
cu.name customerName,
address.city,
address.street deltostreet,
address.zipcode deltozipcode,
  cu.customer_id, cu.defaultbusinessunit_id,cu.defaultinvoicebusinessunit_id, rp.reportparam_id, rp.timestamp, rp.date_value1
, 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,languages lg,
  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
where
    cu.visitaddress_id = address.address_id
and cu.currency_id = currency.currency_id
and cu.defaultbusinessunit_id = bu.businessunit_id
and p.plant_id=bu.plant_id
and p.address_id=x.address_id
and cu.language_id = lg.language_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))
                   and cu.active = 'Y'

/
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, GETCURRENTDATE()), 1, 15) LastWashPriceIncrease
       , substr(F_LastRentPriceIncrease(cu.customer_id, GETCURRENTDATE()), 1, 15) LastRentPriceIncrease
       , substr(F_LastWeightPriceIncrease(cu.customer_id, GETCURRENTDATE()), 1, 15) LastWeightPriceIncrease
       , cu.customer_id
       , pack_price.Weight_Price(cu.customer_id, pr.weighingcategory_id, 'Y', GETCURRENTDATE()) WeightPriceSoil
       , pack_price.Weight_Price(cu.customer_id, pr.weighingcategory_id, 'N', GETCURRENTDATE()) 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 <= GETCURRENTDATE())
         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 <= GETCURRENTDATE())
         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 <= GETCURRENTDATE())
         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, GETCURRENTDATE(), 1) WashPrice
       , pack_price.Replacement_Price(cu.customer_id, pr.product_id, plpc.sizedefinition_id,NULL, GETCURRENTDATE()) ReplacementPrice
       , pack_price.Sales_Price(cu.customer_id, pr.product_id, plpc.sizedefinition_id, GETCURRENTDATE()) 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, SUPPZIPCODE, SUPPCITY, SUPPPHONE, SUPPFAX, SUPPEMAIL, SUPPLIERTYPE, BUYERCODE, STOCKCODE, STOCKNAME, PLANTBUNAME, STOCKSTREET, STOCKZIPCODE, STOCKCITY, STOCKSTATECOUNTY, PLANTBUPHONE, PLANTBUFAX, PLANTBUEMAIL, PLANTCOMPANY_ID, PLANTCOMPANYCODE, PLANTCOMPANYNAME, PCYSTREET, PCYZIPCODE, PCYCITY, PCYSTATECOUNTY, POAYSTATECOUNTY, PLANTCOMPANYPHONE, PLANTCOMPANYFAX, PLANTCOMPANYEMAIL, PLANTCOMPANYVAT, PURCHASEORDERNUMBER, ORDERDATE, REQUESTEDDATE
, DISCOUNTPERCOVERALL, DISCOUNTPERCDAYS, DISCOUNTWITHINDAYS, PAYMENTTERMS, DELIVERYTERMS, PHREMARK, PHREMARK_NULL, SUPPSTATECOUNTY, 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)
as select
  supplier.suppliernumber suppNumber, supplier.name suppName, addressSup.Street SuppStreet
, addressSup.Zipcode SuppZipCode, addressSup.City SuppCity, supplier.phone SuppPhone
, supplier.fax Suppfax, supplier.email Suppemail, supplier.suppliertype suppliertype
, sksp.buyercode, sk.code stockCode, sk.name stockName, plantBU.name plantBUName, /*cast(*/CONCATENATEWITHBLANK(addressSK.Street, addressSK.Street2) /*as varchar2(60))*/ STOCKstreet
, addressSK.Zipcode STOCKzipcode, addressSK.City STOCKcity
, /*cast(*/CONCATENATEWITHBLANK3(addressSK.State,'/',addressSK.County)/* as varchar2(60))*/ STOCKStateCounty
, plantBU.phoneno plantBUPhone, plantBU.Faxno plantBUFax, plantBU.email plantBUEmail
, plantcompany.plantcompany_id, plantcompany.code plantcompanyCode, plantcompany.name plantcompanyName, addressPCY.Street PCYStreet
, addressPCY.Zipcode PCYZipCode, addressPCY.City PCYCity
, /*cast(*/CONCATENATEWITHBLANK3(addressPCY.State,'/',addressPCY.County) /*as varchar2(60))*/ PCYStateCounty
, /*cast(*/CONCATENATEWITHBLANK3(poai.state,'/',poai.county) /*as varchar2(255))*/ POAYStateCounty
, plantcompany.phone plantcompanyPhone, plantcompany.fax plantcompanyFax, plantcompany.email plantcompanyEmail, plantcompany.vatnumber plantcompanyVAT
, ph.purchaseordernumber, ph.orderdate,  ph.requesteddate
, supplier.discountpercoverall, supplier.discountpercdays, supplier.discountwithindays
, /*cast(*/supplier.paymentterms/* as varchar2(60)) paymentterms*/,/* cast(*/supplier.deliveryterms/* as varchar2(60))*/ deliveryterms
, ph.remark PHRemark,  case when ph.remark is null then 'Y' else 'N' end PHRemark_null,
 cast(CONCATENATEWITHBLANK3(addressSup.State,'/',addressSup.County) as varchar2(255)) SuppStateCounty
, product_link.code productLinkCode, pli.supplierproductcode, pli.suppliersizecode
, coalesce
  (( select splprd.supplierproductdescription from supplierproduct splprd
          where pli.supplierproductcode = splprd.supplierproductcode
             and pli.suppliersizecode = splprd.suppliersizecode
                 and supplier.supplier_id = splprd.supplier_id)
   ,( select product_desc.description from product_desc where product_desc.product_id = pli.product_link_id
            and product_desc.language_id = languages.language_id )) supplierProductDesc
, pli.uniqueitem, pli.quantityordered
, supplier.printPriceOnPO
, pli.purchaseprice, (pli.quantityordered * pli.purchaseprice) amount
, pli.remark PLIRemark, case when pli.remark is null then 'Y' else 'N' end PLIRemark_null
, currency.code currencyCode, currency.decimals pricedecimals, currency.invoiceamountdecimals amountdecimals
, ph.purchaseorderheader_id, pli.purchaseorderline_id
, status.code statusCode, ph.origin, ph.approvaldate, ph.approvaluser_id
, ( select status_desc.description from status_desc where status_desc.status_id = status.status_id
  and status_desc.language_id = languages.language_id ) statusDesc
, pli.quantityreceived, pli.quantitycancelled, pli.quantityconfirmed
, languages.code languageCode
, sizedefinition_link.code LaundrySizeCode
, /*cast(*/(select qg.Code from QualityGrade qg where pli.requestedgrade_id = qg.qualitygrade_id) /*as varchar2(60))*/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 = languages.code)
       then 'Y'
       else 'N'
   end) pocustomerlines,
      coalesce((select count(p.product_id) from product p where pli.product_link_id=p.product_id and p.typeofmerchandise=4),0) emblempo
from
  purchaseorderheader ph
    left outer join
         ( plantcompany join address addressPCY on plantcompany.address_id = addressPCY.Address_Id
         ) on ph.plantcompany_id = plantcompany.plantcompany_id
    left outer join stockroomsupplier sksp
          on ph.stockroom_id = sksp.stockroom_id and ph.supplier_id = sksp.supplier_id
    left outer join
         ( stockroom sk
                join ( businessunit bu join plant plantBU on bu.plant_id = plantBU.plant_id )
                  on sk.managedbybu_id = bu.businessunit_id
                join address addressSK on sk.deliveryaddress_id = addressSK.address_id
          ) on ph.stockroom_id = sk.stockroom_id
    left outer join
         ( purchaseorderline pli
                             join product_link on pli.product_link_id = product_link.product_link_id
                             join sizedefinition_link on pli.sizedefinition_link_id = sizedefinition_link.sizedefinition_link_id
         ) on ph.purchaseorderheader_id = pli.purchaseorderheader_id
    left outer join  purchaseorderaddressinfo poai on poai.purchaseorderheader_id=ph.purchaseorderheader_id
, status, supplier, address addressSup, currency, languages
where ph.supplier_id = supplier.supplier_id
and supplier.address_id = addressSup.address_id
and ph.status_id = status.status_id
and ph.currency_id = currency.currency_id

/
create or replace view V_PURCHASEORDER_ANF
 (SUPPNUMBER, SUPPNAME, SUPPSTREET, SUPPZIPCODE, SUPPCITY, SUPPPHONE, SUPPFAX, SUPPEMAIL, SUPPLIERTYPE, BUYERCODE, STOCKCODE, STOCKNAME, PLANTBUNAME, STOCKSTREET, STOCKZIPCODE, STOCKCITY, STOCKSTATECOUNTY, PLANTBUPHONE, PLANTBUFAX, PLANTBUEMAIL, PLANTCOMPANY_ID, PLANTCOMPANYCODE, PLANTCOMPANYNAME, PCYSTREET, PCYZIPCODE, PCYCITY, PCYSTATECOUNTY, POAYSTATECOUNTY, PLANTCOMPANYPHONE, PLANTCOMPANYFAX, PLANTCOMPANYEMAIL, PLANTCOMPANYVAT, PURCHASEORDERNUMBER, ORDERDATE, REQUESTEDDATE
, DISCOUNTPERCOVERALL, DISCOUNTPERCDAYS, DISCOUNTWITHINDAYS, PAYMENTTERMS, DELIVERYTERMS, PHREMARK, PHREMARK_NULL, SUPPSTATECOUNTY, 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, BILLTONAME, BILLTOSTREET, BILLTOZIP, BILLTOCITY, SHIPTONAME, SHIPTOSTREET, SHIPTOZIP, SHIPTOCITY, SENDINVOICETONAME, SENDINVOICETOSTREET, SENDINVOICETOZIP, SENDINVOICETOCITY, PREWASHBYSUPPLIER, INTERNALPO, RESPONSIBLEEMPLOYEE_MAIL, PLANTCOMPANYINFO, PLANTCOMPANYINFO2
, MODIFICATIONS)
as select supplier.suppliernumber suppNumber,
       supplier.name suppName,
       addressSup.Street SuppStreet,
       addressSup.Zipcode SuppZipCode,
       addressSup.City SuppCity,
       supplier.phone SuppPhone,
       supplier.fax Suppfax,
       supplier.email Suppemail,
       supplier.suppliertype suppliertype,
       sksp.buyercode,
       sk.code stockCode,
       sk.name stockName,
       plantBU.name plantBUName, /*cast(*/
       CONCATENATEWITHBLANK(addressSK.Street, addressSK.Street2) /*as varchar2(60))*/ STOCKstreet,
       addressSK.Zipcode STOCKzipcode,
       addressSK.City STOCKcity, /*cast(*/
       CONCATENATEWITHBLANK3(addressSK.State, '/', addressSK.County) /* as varchar2(60))*/ STOCKStateCounty,
       plantBU.phoneno plantBUPhone,
       plantBU.Faxno plantBUFax,
       plantBU.email plantBUEmail,
       plantcompany.plantcompany_id,
       plantcompany.code plantcompanyCode,
       plantcompany.name plantcompanyName,
       addressPCY.Street PCYStreet,
       addressPCY.Zipcode PCYZipCode,
       addressPCY.City PCYCity, /*cast(*/
       CONCATENATEWITHBLANK3(addressPCY.State, '/', addressPCY.County) /*as varchar2(60))*/ PCYStateCounty, /*cast(*/
       CONCATENATEWITHBLANK3(poai.state, '/', poai.county) /*as varchar2(255))*/ POAYStateCounty,
       plantcompany.phone plantcompanyPhone,
       plantcompany.fax plantcompanyFax,
       plantcompany.email plantcompanyEmail,
       plantcompany.vatnumber plantcompanyVAT,
       ph.purchaseordernumber,
       ph.orderdate,
       ph.requesteddate,
       supplier.discountpercoverall,
       supplier.discountpercdays,
       supplier.discountwithindays, /*cast(*/
       supplier.paymentterms /* as varchar2(60)) paymentterms*/, /* cast(*/
       supplier.deliveryterms /* as varchar2(60))*/ deliveryterms,
       ph.remark PHRemark,
       case
         when ph.remark is null then
          'Y'
         else
          'N'
       end PHRemark_null,
       cast(CONCATENATEWITHBLANK3(addressSup.State, '/', addressSup.County) as
            varchar2(255)) SuppStateCounty,
       product_link.code productLinkCode,
       coalesce(aggsuppprod.code,
                pli.supplierproductcode,
                product_link.code) supplierproductcode,
       coalesce((select sd.code
                  from sizedefinition sd
                 where sd.sizedefinition_id =
                       aggsuppprodsize.sizedefinition_id),
                pli.suppliersizecode,
                sizedefinition_link.code) suppliersizecode,
       coalesce(aggsuppprod.description,
                (select product_desc.description
                   from product_desc
                  where product_desc.product_id = pli.product_link_id
                    and product_desc.language_id = languages.language_id)) supplierProductDesc,
       pli.uniqueitem,
       pli.quantityordered,
       supplier.printPriceOnPO,
       pli.purchaseprice,
       (pli.quantityordered * pli.purchaseprice) amount,
       pli.remark PLIRemark,
       case
         when pli.remark is null then
          'Y'
         else
          'N'
       end PLIRemark_null,
       currency.code currencyCode,
       currency.decimals pricedecimals,
       currency.invoiceamountdecimals amountdecimals,
       ph.purchaseorderheader_id,
       pli.purchaseorderline_id,
       status.code statusCode,
       ph.origin,
       ph.approvaldate,
       ph.approvaluser_id,
       (select status_desc.description
          from status_desc
         where status_desc.status_id = status.status_id
           and status_desc.language_id = languages.language_id) statusDesc,
       pli.quantityreceived,
       pli.quantitycancelled,
       pli.quantityconfirmed,
       languages.code languageCode,
       sizedefinition_link.code LaundrySizeCode, /*cast(*/
       (select qg.Code
          from QualityGrade qg
         where pli.requestedgrade_id = qg.qualitygrade_id) /*as varchar2(60))*/ 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 = languages.code) then
          'Y'
         else
          'N'
       end) pocustomerlines,
       coalesce((select count(p.product_id)
                  from product p
                 where pli.product_link_id = p.product_id
                   and p.typeofmerchandise = 4),
                0) emblempo,
       v_billtocompany_address.name billtoname,
       v_billtocompany_address.street billtostreet,
       v_billtocompany_address.zipcode billtozip,
       v_billtocompany_address.city billtocity,
       v_shipto_address.name shiptoname,
       v_shipto_address.street shiptostreet,
       v_shipto_address.zipcode shiptozip,
       v_shipto_address.city shiptocity,
       v_sendinvoiceto_address.name sendInvoiceToName,
       v_sendinvoiceto_address.street sendInvoiceToStreet,
       v_sendinvoiceto_address.zipcode sendInvoiceToZip,
       v_sendinvoiceto_address.city sendInvoiceToCity,
       pli.prewashbysupplier,
       (select LISTAGG(wo_distinct.referencenumber, ',') WITHIN GROUP(ORDER BY wo_distinct.referencenumber)
          from (select distinct wo.referencenumber,
                                poh.purchaseorderheader_id
                  from workorder                 wo,
                       workorderline             wol,
                       backorderwol              bol,
                       backorderexecutionwol     boe,
                       backorderpurchaseorderwol bpl,
                       purchaseorderlinedetail   pold,
                       purchaseorderline         pol,
                       purchaseorderheader       poh
                 where wo.workorder_id = wol.workorder_id
                   and wol.workorderline_id = bol.workorderline_id
                   and bol.backorderwol_id = boe.backorderwol_id
                   and boe.backorderexecutionwol_id =
                       bpl.backorderexecutionwol_id
                   and bpl.purchaseorderlinedetail_id =
                       pold.purchaseorderlinedetail_id
                   and pold.purchaseorderline_id = pol.purchaseorderline_id
                   and pol.purchaseorderheader_id =
                       poh.purchaseorderheader_id
                   and wo.origin = 8) wo_distinct
         where wo_distinct.purchaseorderheader_id =
               ph.purchaseorderheader_id) internalPO,
       e.email responsibleemployee_mail,
       (select sk.name || ' --- ' || addressSK.Street || ' --- ' ||
               addressSK.Zipcode || ' ' || addressSK.City
          from dual) PlantCompanyInfo,
       (select 'TEL: ' || e.phoneno || ' --- TELECOPIE: ' || e.faxno ||
               ' --- ' || e.email
          from dual) PlantCompanyInfo2,
 (coalesce((select modi1.code from modification modi1 where modi1.modification_id = pli.modification1_id), '')
 || ' ' || coalesce((select modi2.code from modification modi2 where modi2.modification_id = pli.modification2_id), '')
 || ' ' || coalesce((select modi3.code from modification modi3 where modi3.modification_id = pli.modification3_id), '')) Modifications
from purchaseorderheader ph
  left outer join(plantcompany
  join address addressPCY
    on plantcompany.address_id = addressPCY.Address_Id) on ph.plantcompany_id = plantcompany.plantcompany_id
  left outer join stockroomsupplier sksp
    on ph.stockroom_id = sksp.stockroom_id
   and ph.supplier_id = sksp.supplier_id
  left outer join(stockroom sk
  join(businessunit bu
  join plant plantBU
    on bu.plant_id = plantBU.plant_id) on sk.managedbybu_id = bu.businessunit_id
  join address addressSK
    on sk.deliveryaddress_id = addressSK.address_id
  join employee e
    on sk.responsibleemployee_id = e.employee_id) on ph.stockroom_id = sk.stockroom_id
  left outer join(purchaseorderline pli
          join product_link
            on pli.product_link_id = product_link.product_link_id
          join sizedefinition_link
            on pli.sizedefinition_link_id = sizedefinition_link.sizedefinition_link_id
          left outer join(aggsupplierproductsize aggsuppprodsize
               join aggsupplierproduct aggsuppprod on aggsuppprod.aggsupplierproduct_id = aggsuppprodsize.aggsupplierproduct_id)
          on pli.aggsupplierproductsize_id = aggsuppprodsize.aggsupplierproductsize_id)
  on ph.purchaseorderheader_id = pli.purchaseorderheader_id
  left outer join purchaseorderaddressinfo poai
    on poai.purchaseorderheader_id = ph.purchaseorderheader_id
  join v_billtocompany_address
    on ph.purchaseorderheader_id = v_billtocompany_address.purchaseorderheader_id
  join v_shipto_address
    on ph.purchaseorderheader_id = v_shipto_address.purchaseorderheader_id
  join v_sendinvoiceto_address
    on ph.purchaseorderheader_id = v_sendinvoiceto_address.purchaseorderheader_id
 , status, supplier, address addressSup, currency, languages
 where ph.supplier_id = supplier.supplier_id
   and supplier.address_id = addressSup.address_id
   and ph.status_id = status.status_id
   and ph.currency_id = currency.currency_id

/
create or replace view V_PURCHASEORDER_CIW
 (SUPPNUMBER, SUPPNAME, SUPPSTREET, SUPPZIPCODE, SUPPCITY, SUPPPHONE, SUPPSTATECOUNTY, SUPPFAX, SUPPEMAIL, SUPPLIERTYPE, BUYERCODE, STOCKCODE, STOCKNAME, PLANTBUNAME, STOCKSTREET, STOCKZIPCODE, STOCKCITY, STOCKSTATECOUNTY, PLANTBUPHONE, PLANTBUFAX, PLANTBUEMAIL, PLANTCOMPANY_ID, PLANTCOMPANYCODE, PLANTCOMPANYNAME, PCYSTREET, PCYZIPCODE, PCYCITY, PCYSTATECOUNTY, PLANTCOMPANYPHONE, PLANTCOMPANYFAX, PLANTCOMPANYEMAIL, PLANTCOMPANYVAT, PURCHASEORDERNUMBER, ORDERDATE, REQUESTEDDATE
, DISCOUNTPERCOVERALL, DISCOUNTPERCDAYS, DISCOUNTWITHINDAYS, PAYMENTTERMS, DELIVERYTERMS, PHREMARK, PHREMARK_NULL, PRODUCTLINKCODE, SUPPLIERPRODUCTCODE, SUPPLIERSIZECODE, LAUNDRYPRODUCTDESC, 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, POSTOCKLINES, POCUSTOMERLINES, MODIFICATIONS, QTYORDEREDMODIFICATION, PLACEMENT, QUANTITYORDEREDSTOCK)
as select
  supplier.suppliernumber suppNumber, supplier.name suppName, addressSup.Street SuppStreet
, addressSup.Zipcode SuppZipCode, addressSup.City SuppCity, supplier.phone SuppPhone
, cast(CONCATENATEWITHBLANK3(addressSup.State,'/',addressSup.County) as varchar2(255)) SuppStateCounty
, supplier.fax Suppfax, supplier.email Suppemail, supplier.suppliertype suppliertype
, sksp.buyercode, sk.code stockCode, sk.name stockName, plantBU.name plantBUName, cast(CONCATENATEWITHBLANK(addressSK.Street, addressSK.Street2) as varchar2(255)) STOCKstreet
, addressSK.Zipcode STOCKzipcode, addressSK.City STOCKcity
, cast(CONCATENATEWITHBLANK3(addressSK.State,'/',addressSK.County) as varchar2(255)) STOCKStateCounty
, plantBU.phoneno plantBUPhone, plantBU.Faxno plantBUFax, plantBU.email plantBUEmail
, plantcompany.plantcompany_id, plantcompany.code plantcompanyCode, plantcompany.name plantcompanyName, addressPCY.Street PCYStreet
, addressPCY.Zipcode PCYZipCode, addressPCY.City PCYCity
, cast(CONCATENATEWITHBLANK3(addressPCY.State,'/',addressPCY.County) as varchar2(255)) PCYStateCounty
, plantcompany.phone plantcompanyPhone, plantcompany.fax plantcompanyFax, plantcompany.email plantcompanyEmail, plantcompany.vatnumber plantcompanyVAT
, ph.purchaseordernumber, ph.orderdate, ph.requesteddate
, supplier.discountpercoverall, supplier.discountpercdays, supplier.discountwithindays
, supplier.paymentterms, supplier.deliveryterms
, ph.remark PHRemark,  case when ph.remark is null then 'Y' else 'N' end PHRemark_null
, product_link.code productLinkCode, pli.supplierproductcode, pli.suppliersizecode
, ( select product_desc.longdescription from product_desc where product_desc.product_id = pli.product_link_id
            and product_desc.language_id = languages.language_id ) laundryProductDesc
, pli.uniqueitem, pli.quantityordered
, supplier.printPriceOnPO
, pli.purchaseprice, (pli.quantityordered * pli.purchaseprice) amount
, pli.remark PLIRemark, case when pli.remark is null then 'Y' else 'N' end PLIRemark_null
, currency.code currencyCode, currency.decimals pricedecimals, currency.invoiceamountdecimals amountdecimals
, ph.purchaseorderheader_id, pli.purchaseorderline_id
, status.code statusCode, ph.origin, ph.approvaldate, ph.approvaluser_id
, ( select status_desc.description from status_desc where status_desc.status_id = status.status_id
  and status_desc.language_id = languages.language_id ) statusDesc
, pli.quantityreceived, pli.quantitycancelled, pli.quantityconfirmed
, languages.code languageCode
, sizedefinition_link.code LaundrySizeCode
, (select qg.Code from QualityGrade qg where pli.requestedgrade_id = qg.qualitygrade_id) QualityGradeCode
, (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 = languages.code)
       then 'Y'
       else 'N'
   end) pocustomerlines, --CAST(
 Y.modifications --as varchar2(63))
 modifications, y.qtyorderedmodification, y.Placement, pli.quantityorderedstock
from
  purchaseorderheader ph
    left outer join
         ( plantcompany join address addressPCY on plantcompany.address_id = addressPCY.Address_Id
         ) on ph.plantcompany_id = plantcompany.plantcompany_id
    left outer join stockroomsupplier sksp
          on ph.stockroom_id = sksp.stockroom_id and ph.supplier_id = sksp.supplier_id
    left outer join
         ( stockroom sk
                join ( businessunit bu join plant plantBU on bu.plant_id = plantBU.plant_id )
                  on sk.managedbybu_id = bu.businessunit_id
                join address addressSK on sk.deliveryaddress_id = addressSK.address_id
          ) on ph.stockroom_id = sk.stockroom_id
    left outer join
         ( purchaseorderline pli
              join product_link on pli.product_link_id = product_link.product_link_id
              join sizedefinition_link on pli.sizedefinition_link_id = sizedefinition_link.sizedefinition_link_id
              left outer join (select x.purchaseorderline_id,
                               sum(x.qtyordered) qtyorderedmodification,
                               x.modifications, x.Placement
                               from (select wol.purchaseorderline_id, placement.code Placement,
                                       (wol.quantityordered -- wol.quantityfilled td25806 take out filled qty
                                            - wol.quantitycancelled) qtyordered,
                                       f_wol_modifications(wol.workorderline_id, cu.language_id) modifications
                                  from workorder wo, customer cu, workorderline wol
                                       left outer join workorderlineemblem wokem
                                            left outer join placement on placement.placement_id = wokem.placement_id
                                       on wokem.workorderline_id = wol.workorderline_id
                                  where wol.workorder_id = wo.workorder_id and wo.customer_link_id = cu.customer_id
                                       ) x
                                 group by x.purchaseorderline_id, x.modifications, x.Placement) Y on Y.purchaseorderline_id = pli.purchaseorderline_id
         ) on ph.purchaseorderheader_id = pli.purchaseorderheader_id
, status, supplier, address addressSup, currency, languages
where ph.supplier_id = supplier.supplier_id
and supplier.address_id = addressSup.address_id
and ph.status_id = status.status_id
and ph.currency_id = currency.currency_id

/
create or replace view V_PURCHASEORDER_DFD
 (SUPPNUMBER, SUPPNAME, SUPPSTREET, SUPPZIPCODE, SUPPCITY, SUPPPHONE, SUPPSTATECOUNTY, SUPPLIERCOUNTRY, SUPPFAX, SUPPEMAIL, SUPPLIERTYPE, BUYERCODE, STOCKCODE, STOCKNAME, PLANTBUNAME, STOCKSTREET, STOCKZIPCODE, STOCKCITY, STOCKSTATECOUNTY, PLANTBUPHONE, PLANTBUFAX, PLANTBUEMAIL, PLANTCOMPANY_ID, PLANTCOMPANYCODE, PLANTCOMPANYNAME, PCYSTREET, PCYZIPCODE, PCYCITY, PCYSTATECOUNTY, PLANTCOMPANYPHONE, PLANTCOMPANYFAX, PLANTCOMPANYEMAIL, PLANTCOMPANYVAT, PURCHASEORDERNUMBER, ORDERDATE
, REQUESTEDDATE, DISCOUNTPERCOVERALL, DISCOUNTPERCDAYS, DISCOUNTWITHINDAYS, PAYMENTTERMS, DELIVERYTERMS, PHREMARK, PHREMARK_NULL, 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, RESPONSIBLEEMPLOYEENAME, POSTOCKLINES, POCUSTOMERLINES)
as select
  supplier.suppliernumber suppNumber, supplier.name suppName, addressSup.Street SuppStreet
, addressSup.Zipcode SuppZipCode, addressSup.City SuppCity, supplier.phone SuppPhone
, cast(CONCATENATEWITHBLANK3(addressSup.State,'/',addressSup.County) as varchar2(255)) SuppStateCounty
, (select c.code from country c where c.country_id = supplier.country_id) supplierCountry
, supplier.fax Suppfax, supplier.email Suppemail, supplier.suppliertype suppliertype
, sksp.buyercode, sk.code stockCode, sk.name stockName, plantBU.name plantBUName, cast(CONCATENATEWITHBLANK(addressSK.Street, addressSK.Street2) as varchar2(255)) STOCKstreet
, addressSK.Zipcode STOCKzipcode, addressSK.City STOCKcity
, cast(CONCATENATEWITHBLANK3(addressSK.State,'/',addressSK.County) as varchar2(255)) STOCKStateCounty
, plantBU.phoneno plantBUPhone, plantBU.Faxno plantBUFax, plantBU.email plantBUEmail
, plantcompany.plantcompany_id, plantcompany.code plantcompanyCode, plantcompany.name plantcompanyName, addressPCY.Street PCYStreet
, addressPCY.Zipcode PCYZipCode, addressPCY.City PCYCity
, cast(CONCATENATEWITHBLANK3(addressPCY.State,'/',addressPCY.County) as varchar2(255)) PCYStateCounty
, plantcompany.phone plantcompanyPhone, plantcompany.fax plantcompanyFax, plantcompany.email plantcompanyEmail, plantcompany.vatnumber plantcompanyVAT
, ph.purchaseordernumber, ph.orderdate, ph.requesteddate
, supplier.discountpercoverall, supplier.discountpercdays, supplier.discountwithindays
, supplier.paymentterms, supplier.deliveryterms
, ph.remark PHRemark,  case when ph.remark is null then 'Y' else 'N' end PHRemark_null
, product_link.code productLinkCode, pli.supplierproductcode, pli.suppliersizecode
, coalesce
  (( select splprd.supplierproductdescription from supplierproduct splprd
          where pli.supplierproductcode = splprd.supplierproductcode
             and pli.suppliersizecode = splprd.suppliersizecode
                 and supplier.supplier_id = splprd.supplier_id)
   ,( select product_desc.description from product_desc where product_desc.product_id = pli.product_link_id
            and product_desc.language_id = languages.language_id )) supplierProductDesc
, pli.uniqueitem, pli.quantityordered
, supplier.printPriceOnPO
, pli.purchaseprice, (pli.quantityordered * pli.purchaseprice) amount
, pli.remark PLIRemark, case when pli.remark is null then 'Y' else 'N' end PLIRemark_null
, currency.code currencyCode, currency.decimals pricedecimals, currency.invoiceamountdecimals amountdecimals
, ph.purchaseorderheader_id, pli.purchaseorderline_id
, status.code statusCode, ph.origin, ph.approvaldate, ph.approvaluser_id
, ( select status_desc.description from status_desc where status_desc.status_id = status.status_id
  and status_desc.language_id = languages.language_id ) statusDesc
, pli.quantityreceived, pli.quantitycancelled, pli.quantityconfirmed
, languages.code languageCode
, sizedefinition_link.code LaundrySizeCode
, (select qg.Code from QualityGrade qg where pli.requestedgrade_id = qg.qualitygrade_id) QualityGradeCode
, poai.name addressiname, poai.street1 addressistreet1, poai.zipcode addressizipcode, poai.city addressicity
, (select em.name from employee em where em.employee_id = sk.responsibleemployee_id) responsibleemployeename
, (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 = languages.code)
       then 'Y'
       else 'N'
   end) pocustomerlines
from
  purchaseorderheader ph
    left outer join
         ( plantcompany join address addressPCY on plantcompany.address_id = addressPCY.Address_Id
         ) on ph.plantcompany_id = plantcompany.plantcompany_id
    left outer join stockroomsupplier sksp
          on ph.stockroom_id = sksp.stockroom_id and ph.supplier_id = sksp.supplier_id
    left outer join
         ( stockroom sk
                join ( businessunit bu join plant plantBU on bu.plant_id = plantBU.plant_id )
                  on sk.managedbybu_id = bu.businessunit_id
                join address addressSK on sk.deliveryaddress_id = addressSK.address_id
          ) on ph.stockroom_id = sk.stockroom_id
    left outer join
         ( purchaseorderline pli
                             join product_link on pli.product_link_id = product_link.product_link_id
                             join sizedefinition_link on pli.sizedefinition_link_id = sizedefinition_link.sizedefinition_link_id
         ) on ph.purchaseorderheader_id = pli.purchaseorderheader_id
    left outer join  purchaseorderaddressinfo poai on poai.purchaseorderheader_id=ph.purchaseorderheader_id
, status, supplier, address addressSup, currency, languages
where ph.supplier_id = supplier.supplier_id
and supplier.address_id = addressSup.address_id
and ph.status_id = status.status_id
and ph.currency_id = currency.currency_id

/
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_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 <= getcurrentdate() and cpc.dateinactive >= getcurrentdate()
) dateactive
, (select lr.code from contractspercustomer cpc, gainlostreason lr
where cpc.customer_id = cu.customer_id and cpc.dateactive <= getcurrentdate() and cpc.dateinactive >= getcurrentdate()
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 <= getcurrentdate() and cpc.dateinactive >= getcurrentdate()
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 <= getcurrentdate() and cpc.dateinactive >= getcurrentdate()
) dateactive
, (select lr.code from contractspercustomer cpc, gainlostreason lr
where cpc.customer_id = cu.customer_id and cpc.dateactive <= getcurrentdate() and cpc.dateinactive >= getcurrentdate()
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 <= getcurrentdate() and cpc.dateinactive >= getcurrentdate()
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, getcurrentdate()-14) < getdatediff(getcurrentdate(), 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, getcurrentdate()-14) < getdatediff(getcurrentdate(), 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, getcurrentdate()-14) < getdatediff(getcurrentdate(), 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, getcurrentdate()-14) < getdatediff(getcurrentdate(), 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, getcurrentdate()-14) < getdatediff(getcurrentdate(), 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, getcurrentdate()-14) < getdatediff(getcurrentdate(), 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 <= getcurrentdate() and cpc.dateinactive >= getcurrentdate()
) dateactive
, (select lr.code from contractspercustomer cpc, gainlostreason lr
where cpc.customer_id = cu.customer_id and cpc.dateactive <= getcurrentdate() and cpc.dateinactive >= getcurrentdate()
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 <= getcurrentdate() and cpc.dateinactive >= getcurrentdate()
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, getcurrentdate()-7) < getdatediff(getcurrentdate(), 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, getcurrentdate()-7) < getdatediff(getcurrentdate(), 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, getcurrentdate()-7) < getdatediff(getcurrentdate(), 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, getcurrentdate()-7) < getdatediff(getcurrentdate(), 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, getcurrentdate()-7) < getdatediff(getcurrentdate(), 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, getcurrentdate()-7) < getdatediff(getcurrentdate(), 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 <= getcurrentdate() and cpc.dateinactive >= getcurrentdate()
) dateactive
, (select lr.code from contractspercustomer cpc, gainlostreason lr
where cpc.customer_id = cu.customer_id and cpc.dateactive <= getcurrentdate() and cpc.dateinactive >= getcurrentdate()
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 <= getcurrentdate() and cpc.dateinactive >= getcurrentdate()
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, getcurrentdate()-28) < getdatediff(getcurrentdate(), 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, getcurrentdate()-28) < getdatediff(getcurrentdate(), 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, getcurrentdate()-28) < getdatediff(getcurrentdate(), 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, getcurrentdate()-28) < getdatediff(getcurrentdate(), 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, getcurrentdate()-28) < getdatediff(getcurrentdate(), 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, getcurrentdate()-28) < getdatediff(getcurrentdate(), 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 <= getcurrentdate() and cpc.dateinactive >= getcurrentdate()
) dateactive
, (select lr.code from contractspercustomer cpc, gainlostreason lr
where cpc.customer_id = cu.customer_id and cpc.dateactive <= getcurrentdate() and cpc.dateinactive >= getcurrentdate()
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 <= getcurrentdate() and cpc.dateinactive >= getcurrentdate()
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, getcurrentdate()-91) < getdatediff(getcurrentdate(), 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, getcurrentdate()-91) < getdatediff(getcurrentdate(), 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, getcurrentdate()-91) < getdatediff(getcurrentdate(), 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, getcurrentdate()-91) < getdatediff(getcurrentdate(), 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, getcurrentdate()-91) < getdatediff(getcurrentdate(), 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, getcurrentdate()-91) < getdatediff(getcurrentdate(), 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, 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, DATEINACTIVE, DEL_POINT_START_TIMECH, DEL_POINT_END_TIMECH, BREAKSTARTTIMECH
, BREAKENDTIMECH, ROUTE_START_TIMECH, ROUTE_START_TIMECH24, STARTTIMECH, SHOWONROUTELIST, CONTACTNOTES, CONTACTSTATUS, PLANT_ID, PLANTEMAIL)
as SELECT 1 linetype,
  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,insertspace_after_x_characters(to_char(P.CUSTOMERNUMBER),3) custnr,
  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, z.mobilephone, 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
  , n.breakstarttime breakstarttime, n.breakendtime breakendtime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
  , p.dateinactive
  , (SELECT to_char(HH.STARTTIME,'fmhhfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIMECH
  , (SELECT to_char(HH.ENDTIME,'fmhhfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIMECH
  , to_char(n.breakstarttime,'fmHH:MI:AM') breakstarttimeCH, to_char(n.breakendtime,'fmHH:MI:AM') breakendtimeCH
  , to_char(B.STARTTIME,'fmhhfm:MI:AM') ROUTE_START_TIMECH
  , to_char(B.STARTTIME,'fmhh24fm:MI') ROUTE_START_TIMECH24
  , to_char(A.STARTTIME,'fmhhfm:MI:AM') STARTTIMECH
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, a.plant_id
 ,cast((select GetSubstringOnLength(pl.email,0,40) from plant pl where pl.plant_id=a.plant_id)as varchar2(40)) plantemail
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 (V_PACKINGNOTELINEPERDELSCH_EXT 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)
    left outer join contact cont ON (cont.contact_id = coalesce(f_getcontactonroutelist(p.customer_id), -1)),
  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 --TNE ORDER 500713
  and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
UNION ALL          -- 2 --
SELECT 2 linetype,
  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,insertspace_after_x_characters(to_char(P.CUSTOMERNUMBER),3) custnr,
  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, z.mobilephone,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 breakstarttime, n.breakendtime breakendtime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
  , p.dateinactive
  , (SELECT to_char(HH.STARTTIME,'fmHHfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIMECH
  , (SELECT to_char(HH.ENDTIME,'fmHHfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIMECH
  , to_char(n.breakstarttime,'fmHHfm:MI:AM') breakstarttimeCH, to_char(n.breakendtime,'fmHH:MI:AM') breakendtimeCH
  , to_char(B.STARTTIME,'fmHHfm:MI:AM') ROUTE_START_TIMECH
  , to_char(B.STARTTIME,'fmHH24fm:MI') ROUTE_START_TIMECH24
  , to_char(A.STARTTIME,'fmHHfm:MI:AM') STARTTIMECH
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, a.plant_id
 ,cast((select GetSubstringOnLength(pl.email,0,40) from plant pl where pl.plant_id=a.plant_id)as varchar2(40)) plantemail
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)
    left outer join contact cont ON (cont.contact_id = coalesce(f_getcontactonroutelist(p.customer_id), -1)),
  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 linetype,
  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,insertspace_after_x_characters(to_char(P.CUSTOMERNUMBER),3) custnr,
  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,z.mobilephone, 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 breakstarttime, dp.breakendtime breakendtime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES ROUTESTOP_TRAVELMINUTES, E.SERVICEMINUTES ROUTESTOP_SERVICEMINUTES
  , p.dateinactive
  , (SELECT to_char(HH.STARTTIME,'fmHHfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = dp.DELIVERYPOINT_ID AND HH.DAY_ID = B.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 = B.DRIVINGDAY_ID) DEL_POINT_END_TIMECH
  , to_char(dp.breakstarttime,'fmHHfm:MI:AM') breakstarttimeCH, to_char(dp.breakendtime,'fmHH:MI:AM') breakendtimeCH
  , to_char(B.STARTTIME,'fmHHfm:MI:AM') ROUTE_START_TIMECH
  , to_char(B.STARTTIME,'fmHH24fm:MI') ROUTE_START_TIMECH24
  , to_char(A.STARTTIME,'fmHHfm:MI:AM') STARTTIMECH
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, a.plant_id
 ,cast((select GetSubstringOnLength(pl.email,0,40) from plant pl where pl.plant_id=a.plant_id)as varchar2(40)) plantemail
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-- order500701
    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)
    left outer join contact cont ON (cont.contact_id = coalesce(f_getcontactonroutelist(p.customer_id), -1)),
  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_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_ROUTELIST_DRYCLEANING_LLG
 (PACKINGNOTENUMBER, PRODUCTCODE, PRODUCTDESCRIPTION, SIZECODE, FINISHINGMETHODCODE, DELIVEREDAMOUNT, DV_REFERENCE, DV_ORIGIN, DV_REASONCODE, LANGUAGECODE)
as select pn.notenumber packingnotenumber, p.code productcode,
(select description from product_desc pd where p.product_id = pd.product_id and pd.language_id = languages.language_id) productdescription,
sd.code sizecode,
fm.code finishingmethodcode,
coalesce((select v.amount from v_routelist_ref_llg v where v.packingnote_id = pn.packingnote_id
          and v.product_id = pnl.product_id
          and v.sizedefinition_id = pnl.sizedefinition_id
          and v.finishingmethod_id = pnl.finishingmethod_id
          and v.languagecode = languages.code),sum(pnl.deliveredamount)) deliveredamount,
(select v.reference from v_routelist_ref_llg v where v.packingnote_id = pn.packingnote_id
          and v.product_id = pnl.product_id
          and v.sizedefinition_id = pnl.sizedefinition_id
          and v.finishingmethod_id = pnl.finishingmethod_id
          and v.languagecode = languages.code) dv_reference,
(select v.origin from v_routelist_ref_llg v where v.packingnote_id = pn.packingnote_id
          and v.product_id = pnl.product_id
          and v.sizedefinition_id = pnl.sizedefinition_id
          and v.finishingmethod_id = pnl.finishingmethod_id
          and v.languagecode = languages.code) dv_origin,
(select v.reasoncode from v_routelist_ref_llg v where v.packingnote_id = pn.packingnote_id
          and v.product_id = pnl.product_id
          and v.sizedefinition_id = pnl.sizedefinition_id
          and v.finishingmethod_id = pnl.finishingmethod_id
          and v.languagecode = languages.code) dv_reasoncode,
languages.code languagecode
from packingnote pn,
packingnoteline pnl,
product p,
sizedefinition sd,
finishingmethod fm,
productgroup pg,
languages
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 pg.productgroup_id = p.productgroup_id
and pg.code = '99'
group by pn.packingnote_id, pn.notenumber, pn.origin
, p.product_id, p.code, pnl.product_id
, pnl.sizedefinition_id, sd.code
, pnl.finishingmethod_id, fm.code
, languages.language_id,languages.code

/
create or replace view V_ROUTELIST_ECL
 (LINETYPE, DELIVEREDAMOUNT, ROUTESTOP_ID, DRIVINGYEAR, DRIVINGWEEK, NOTENUMBER, CUSTOMER_ID, SHOWSTOP, ROUTECONTROL_ID, STOP_DELIVERYPOINT_ID, PN_DELIVERYPOINT_ID, PLANTCODE, ROUTENUMBER, ROUTEDESCRIPTION, DRIVINGDATE, DRIVINGDAYDESCRIPTION, DRIVINGDAYNUMBER, DEPOTCODE, DEPOTDESCRIPTION, LOADINGDOCK, STARTTIME, DRIVERNAME, TRUCKCODE, TRUCKDESCRIPTION, 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, DATEINACTIVE, DEL_POINT_START_TIMECH
, DEL_POINT_END_TIMECH, BREAKSTARTTIMECH, BREAKENDTIMECH, ROUTE_START_TIMECH, ROUTE_START_TIMECH24, STARTTIMECH, SHOWONROUTELIST, CONTACTNOTES, CONTACTSTATUS, PLANT_ID, PLANTEMAIL, LEGACYCUSTOMERNUMBER, SERVICEEMPLOYEE)
as SELECT 1 linetype,
--coalesce((select sum(v.bagnumbercoli) from v_cagesbags_ecl v where v.route_id = b.route_id and v.stop_id = d.stop_id),0) totalbagsnumbercoli,
--coalesce((select sum(v.cagenumbercoli) from v_cagesbags_ecl v where v.route_id = b.route_id and v.stop_id = d.stop_id),0) totalcagesnumbercoli,
 g.deliveredamount * coalesce((select ps.theoreticalweight from productsize ps where ps.product_id=g.product_id and ps.sizedefinition_id=g.sizedefinition_id), I.Theoreticalweight,0) deliveredamount,
  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, getDayDescription(A.DRIVINGDATE) DrivingDayDescription, getDayNumber(A.DRIVINGDATE) DrivingDayNumber,
  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,insertspace_after_x_characters(to_char(P.CUSTOMERNUMBER),3) custnr,
  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, z.mobilephone, 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 w.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
  , n.breakstarttime breakstarttime, n.breakendtime breakendtime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
  , p.dateinactive
  , (SELECT to_char(HH.STARTTIME,'fmhhfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIMECH
  , (SELECT to_char(HH.ENDTIME,'fmhhfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIMECH
  , to_char(n.breakstarttime,'fmHH:MI:AM') breakstarttimeCH, to_char(n.breakendtime,'fmHH:MI:AM') breakendtimeCH
  , to_char(B.STARTTIME,'fmhhfm:MI:AM') ROUTE_START_TIMECH
  , to_char(B.STARTTIME,'fmhh24fm:MI') ROUTE_START_TIMECH24
  , to_char(A.STARTTIME,'fmhhfm:MI:AM') STARTTIMECH
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, a.plant_id
 , cast((select GetSubstringOnLength(pl.email,0,40) from plant pl where pl.plant_id = a.plant_id)as varchar2(40)) plantemail
 , p.legacycustomernumber, (select emp.name from employee emp where emp.employee_id = P.Serviceemployee_Id) Serviceemployee
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
    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 (V_PACKINGNOTELINEPERDELSCH_EXT 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)
    left outer join contact cont ON (cont.contact_id = coalesce(f_getcontactonroutelist(p.customer_id), -1)),
  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
  G.PACKINGNOTE_ID = F.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
UNION ALL          -- 2 --
SELECT 2 linetype,
--coalesce((select sum(v.bagnumbercoli) from v_cagesbags_ecl v where v.route_id = b.route_id and v.stop_id = d.stop_id),0) totalbagsnumbercoli,
--coalesce((select sum(v.cagenumbercoli) from v_cagesbags_ecl v where v.route_id = b.route_id and v.stop_id = d.stop_id),0) totalcagesnumbercoli,
0 deliveredamount,
  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, getDayDescription(A.DRIVINGDATE) DrivingDayDescription, getDayNumber(A.DRIVINGDATE) DrivingDayNumber,
  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,insertspace_after_x_characters(to_char(P.CUSTOMERNUMBER),3) custnr,
  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, z.mobilephone,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 w.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 breakstarttime, n.breakendtime breakendtime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
  , p.dateinactive
  , (SELECT to_char(HH.STARTTIME,'fmHHfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIMECH
  , (SELECT to_char(HH.ENDTIME,'fmHHfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIMECH
  , to_char(n.breakstarttime,'fmHHfm:MI:AM') breakstarttimeCH, to_char(n.breakendtime,'fmHH:MI:AM') breakendtimeCH
  , to_char(B.STARTTIME,'fmHHfm:MI:AM') ROUTE_START_TIMECH
  , to_char(B.STARTTIME,'fmHH24fm:MI') ROUTE_START_TIMECH24
  , to_char(A.STARTTIME,'fmHHfm:MI:AM') STARTTIMECH
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, a.plant_id
 , cast((select GetSubstringOnLength(pl.email,0,40) from plant pl where pl.plant_id=a.plant_id)as varchar2(40)) plantemail
 , p.legacycustomernumber, (select emp.name from employee emp where emp.employee_id = P.Serviceemployee_Id) Serviceemployee
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
    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)
    left outer join contact cont ON (cont.contact_id = coalesce(f_getcontactonroutelist(p.customer_id), -1)),
  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 linetype,
--coalesce((select sum(v.bagnumbercoli) from v_cagesbags_ecl v where v.route_id=b.route_id and v.stop_id = d.stop_id),0) totalbagsnumbercoli,
--coalesce((select sum(v.cagenumbercoli) from v_cagesbags_ecl v where v.route_id=b.route_id and v.stop_id = d.stop_id),0) totalcagesnumbercoli,
 0 deliveredamount,
  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, getDayDescription(A.DRIVINGDATE) DrivingDayDescription, getDayNumber(A.DRIVINGDATE) DrivingDayNumber,
  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,insertspace_after_x_characters(to_char(P.CUSTOMERNUMBER),3) custnr,
  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,z.mobilephone, 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 breakstarttime, dp.breakendtime breakendtime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES ROUTESTOP_TRAVELMINUTES, E.SERVICEMINUTES ROUTESTOP_SERVICEMINUTES
  , p.dateinactive
  , (SELECT to_char(HH.STARTTIME,'fmHHfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = dp.DELIVERYPOINT_ID AND HH.DAY_ID = B.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 = B.DRIVINGDAY_ID) DEL_POINT_END_TIMECH
  , to_char(dp.breakstarttime,'fmHHfm:MI:AM') breakstarttimeCH, to_char(dp.breakendtime,'fmHH:MI:AM') breakendtimeCH
  , to_char(B.STARTTIME,'fmHHfm:MI:AM') ROUTE_START_TIMECH
  , to_char(B.STARTTIME,'fmHH24fm:MI') ROUTE_START_TIMECH24
  , to_char(A.STARTTIME,'fmHHfm:MI:AM') STARTTIMECH
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, a.plant_id
 , cast((select GetSubstringOnLength(pl.email,0,40) from plant pl where pl.plant_id=a.plant_id)as varchar2(40)) plantemail
 , p.legacycustomernumber, (select emp.name from employee emp where emp.employee_id = P.Serviceemployee_Id) Serviceemployee
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)
    left outer join contact cont ON (cont.contact_id = coalesce(f_getcontactonroutelist(p.customer_id), -1)),
  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_ROUTELIST_EDE
 (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, 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, 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, NRCLDELNOTES)
as SELECT 1 linetype,
  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, e.stoptype, s.plant_id) showstop,
  A.ROUTECONTROL_ID, E.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,insertspace_after_x_characters(to_char(P.CUSTOMERNUMBER),3) custnr,
  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, z.mobilephone, 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(e.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
  , n.breakstarttime breakstarttime, n.breakendtime breakendtime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
  , p.dateinactive
  , (SELECT to_char(HH.STARTTIME,'fmhhfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIMECH
  , (SELECT to_char(HH.ENDTIME,'fmhhfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIMECH
  , to_char(n.breakstarttime,'fmHH:MI:AM') breakstarttimeCH, to_char(n.breakendtime,'fmHH:MI:AM') breakendtimeCH
  , to_char(B.STARTTIME,'fmhhfm:MI:AM') ROUTE_START_TIMECH
  , to_char(B.STARTTIME,'fmhh24fm:MI') ROUTE_START_TIMECH24
  , to_char(A.STARTTIME,'fmhhfm:MI:AM') STARTTIMECH
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, a.plant_id
 ,cast((select GetSubstringOnLength(pl.email,0,40) from plant pl where pl.plant_id=a.plant_id)as varchar2(40)) plantemail
 ,( select cri.routedescription
    from   CustomerRouteInfo cri
    where  cri.customer_id = p.customer_id) drivinginstructions
, ( select count(*)
    from   clientdeliverynote cdn
	where cdn.route_id = B.route_id
	  and cdn.stopnumber = D.stopnumber
	  and cdn.customer_link_id = P.customer_id ) NrClDelNotes
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 (ROUTESTOP E left outer join CONTACTPERSON Z ON E.CONTACTPERSON_ID = Z.CONTACTPERSON_ID)
      ON D.ROUTESTOP_ID = E.ROUTESTOP_ID,
  PACKINGNOTE F,
  PACKINGNOTELINE G    --left outer join (PACKINGNOTELINEPERDELSCHEME H
    left outer join (V_PACKINGNOTELINEPERDELSCH_EXT H
       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)
    left outer join contact cont ON (cont.contact_id = coalesce(f_getcontactonroutelist(p.customer_id), -1)),
  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 --TNE ORDER 500713
  and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
UNION ALL          -- 2 --
SELECT 2 linetype,
  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, e.stoptype, s.plant_id) showstop,
  A.ROUTECONTROL_ID, E.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,insertspace_after_x_characters(to_char(P.CUSTOMERNUMBER),3) custnr,
  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, z.mobilephone,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(e.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 breakstarttime, n.breakendtime breakendtime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
  , p.dateinactive
  , (SELECT to_char(HH.STARTTIME,'fmHHfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIMECH
  , (SELECT to_char(HH.ENDTIME,'fmHHfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIMECH
  , to_char(n.breakstarttime,'fmHHfm:MI:AM') breakstarttimeCH, to_char(n.breakendtime,'fmHH:MI:AM') breakendtimeCH
  , to_char(B.STARTTIME,'fmHHfm:MI:AM') ROUTE_START_TIMECH
  , to_char(B.STARTTIME,'fmHH24fm:MI') ROUTE_START_TIMECH24
  , to_char(A.STARTTIME,'fmHHfm:MI:AM') STARTTIMECH
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, a.plant_id
 ,cast((select GetSubstringOnLength(pl.email,0,40) from plant pl where pl.plant_id=a.plant_id)as varchar2(40)) plantemail
 ,( select cri.routedescription
    from   CustomerRouteInfo cri
    where  cri.customer_id = p.customer_id) drivinginstructions
, ( select count(*)
    from   clientdeliverynote cdn
	where cdn.route_id = B.route_id
	  and cdn.stopnumber = D.stopnumber
	  and cdn.customer_link_id = P.customer_id ) NrClDelNotes
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 (ROUTESTOP E left outer join CONTACTPERSON Z ON E.CONTACTPERSON_ID = Z.CONTACTPERSON_ID)
      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)
    left outer join contact cont ON (cont.contact_id = coalesce(f_getcontactonroutelist(p.customer_id), -1)),
  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 linetype,
  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, e.stoptype, s.plant_id) showstop,
  A.ROUTECONTROL_ID, E.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,insertspace_after_x_characters(to_char(P.CUSTOMERNUMBER),3) custnr,
  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,z.mobilephone, 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(e.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 breakstarttime, dp.breakendtime breakendtime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES ROUTESTOP_TRAVELMINUTES, E.SERVICEMINUTES ROUTESTOP_SERVICEMINUTES
  , p.dateinactive
  , (SELECT to_char(HH.STARTTIME,'fmHHfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = dp.DELIVERYPOINT_ID AND HH.DAY_ID = B.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 = B.DRIVINGDAY_ID) DEL_POINT_END_TIMECH
  , to_char(dp.breakstarttime,'fmHHfm:MI:AM') breakstarttimeCH, to_char(dp.breakendtime,'fmHH:MI:AM') breakendtimeCH
  , to_char(B.STARTTIME,'fmHHfm:MI:AM') ROUTE_START_TIMECH
  , to_char(B.STARTTIME,'fmHH24fm:MI') ROUTE_START_TIMECH24
  , to_char(A.STARTTIME,'fmHHfm:MI:AM') STARTTIMECH
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, a.plant_id
 ,cast((select GetSubstringOnLength(pl.email,0,40) from plant pl where pl.plant_id=a.plant_id)as varchar2(40)) plantemail
 ,( select cri.routedescription
    from   CustomerRouteInfo cri
    where  cri.customer_id = p.customer_id) drivinginstructions
, ( select count(*)
    from   clientdeliverynote cdn
	where cdn.route_id = B.route_id
	  and cdn.stopnumber = D.stopnumber
	  and cdn.customer_link_id = P.customer_id ) NrClDelNotes
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 ROUTESTOP E
      left outer join CONTACTPERSON Z ON E.CONTACTPERSON_ID = Z.CONTACTPERSON_ID
      left outer join DELIVERYPOINT DP LEFT OUTER JOIN ADDRESS T ON DP.DELIVERYADDRESS_ID = T.ADDRESS_ID
      ON E.DELIVERYPOINT_ID = DP.DELIVERYPOINT_ID
    ON D.ROUTESTOP_ID = E.ROUTESTOP_ID,
  CUSTOMER P
    left outer join customerlockermanagement clm ON (p.customer_id = clm.customer_id)
    left outer join contact cont ON (cont.contact_id = coalesce(f_getcontactonroutelist(p.customer_id), -1)),
  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_ROUTELIST_HOW
 (BLOCK, 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, 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, DATEINACTIVE, REMARKONPACKINGNOTE, REMARKONDELIVERYNOTE, DELIVERSTOPSTART, DELIVERYSTOPEND
, DELIVERSTOPSTARTWEEK, DELIVERYSTOPENDWEEK)
as SELECT 1 Block, 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,
--  X.NAME DRIVERNAME, Y.CODE TRUCKCODE, Y.DESCRIPTION TRUCKDESCRIPTION,
  (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,
  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,
 --- case when d.routestop_id is null then d.routelistinstructions else E.ROUTELISTINSTRUCTIONS end ROUTELISTINSTRUCTIONS,
 --501850
 d.routelistinstructions,
  Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE, z.mobilephone, 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,
  1 STRAIGHTEVENEXCHANGE,
  G.DELIVEREDAMOUNT QTYDELIVERED_PNL, P.DELNOTEFORBULKPUTUPITEMS
  , to_char((SELECT HH.STARTTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID), 'HH24:MI') DEL_POINT_START_TIME
  , to_char((SELECT HH.ENDTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID), 'HH24:MI') DEL_POINT_END_TIME
  , to_char(n.breakstarttime, 'HH24:MI') breakstarttime, to_char(n.breakendtime, 'HH24:MI') breakendtime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
  , p.dateinactive, M.Remarkonpackingnote, M.Remarkondeliverynote
  , (Select tst.startdate from productlistperdistribpoint plpd
  inner JOIN standarddeliveryline stdl on stdl.productlistperdistribpoint_id=plpd.productlistperdistribpoint_id
  Inner JOIN temporarydeliverystop tst on tst.standarddeliveryline_id=stdl.standarddeliveryline_id
  Where  plpd.distributionpoint_id=M.DISTRIBUTIONPOINT_ID and plpd.product_id=i.product_id
  and plpd.finishingmethod_id=R.finishingmethod_id and plpd.sizedefinition_id=j.sizedefinition_id
  and L.DELIVERYSCHEME_ID=stdl.deliveryscheme_id
  AND (A.DRIVINGDATE between tst.startdate and tst.enddate)group by tst.startdate)DeliverStopStart
 , (Select tst.enddate from productlistperdistribpoint plpd
  inner JOIN standarddeliveryline stdl on stdl.productlistperdistribpoint_id=plpd.productlistperdistribpoint_id
  Inner JOIN temporarydeliverystop tst on tst.standarddeliveryline_id=stdl.standarddeliveryline_id
  Where  plpd.distributionpoint_id=M.DISTRIBUTIONPOINT_ID and plpd.product_id=i.product_id
  and plpd.finishingmethod_id=R.finishingmethod_id and plpd.sizedefinition_id=j.sizedefinition_id
  and L.DELIVERYSCHEME_ID=stdl.deliveryscheme_id
  AND (A.DRIVINGDATE between tst.startdate and tst.enddate) group by tst.enddate) DeliveryStopEnd
, (Select tst.temporarystopstartweek from productlistperdistribpoint plpd
  inner JOIN standarddeliveryline stdl on stdl.productlistperdistribpoint_id=plpd.productlistperdistribpoint_id
  Inner JOIN temporarydeliverystop tst on tst.standarddeliveryline_id=stdl.standarddeliveryline_id
  Where  plpd.distributionpoint_id=M.DISTRIBUTIONPOINT_ID and plpd.product_id=i.product_id
  and plpd.finishingmethod_id=R.finishingmethod_id and plpd.sizedefinition_id=j.sizedefinition_id
  and L.DELIVERYSCHEME_ID=stdl.deliveryscheme_id
  AND (getisoweek(A.DRIVINGDATE) between tst.temporarystopstartweek and tst.temporarystopendweek)group by tst.temporarystopstartweek)DeliverStopStartWeek
 , (Select tst.temporarystopendweek from productlistperdistribpoint plpd
  inner JOIN standarddeliveryline stdl on stdl.productlistperdistribpoint_id=plpd.productlistperdistribpoint_id
  Inner JOIN temporarydeliverystop tst on tst.standarddeliveryline_id=stdl.standarddeliveryline_id
  Where  plpd.distributionpoint_id=M.DISTRIBUTIONPOINT_ID and plpd.product_id=i.product_id
  and plpd.finishingmethod_id=R.finishingmethod_id and plpd.sizedefinition_id=j.sizedefinition_id
  and L.DELIVERYSCHEME_ID=stdl.deliveryscheme_id
  AND (getisoweek(A.DRIVINGDATE) between tst.temporarystopstartweek and tst.temporarystopendweek)group by tst.temporarystopendweek) DeliveryStopEndWeek
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
  (d.status in (0, 3, 4) )
  AND P.COUNTRY_ID = W.COUNTRY_ID --TNE ORDER 500713
and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
UNION ALL -- 1 --            NON-STRAIGHT EVEN EXCHANGE ITEMS
SELECT 2 Block,
 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, Z.Mobilephone, 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
 , to_char((SELECT HH.STARTTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID), 'HH24:MI') DEL_POINT_START_TIME
  , to_char((SELECT HH.ENDTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID), 'HH24:MI') DEL_POINT_END_TIME
   , to_char(n.breakstarttime, 'HH24:MI') breakstarttime, to_char(n.breakendtime, 'HH24:MI') breakendtime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
  , p.dateinactive, M.Remarkonpackingnote, M.Remarkondeliverynote
  , (Select tst.startdate from productlistperdistribpoint plpd
  inner JOIN standarddeliveryline stdl on stdl.productlistperdistribpoint_id=plpd.productlistperdistribpoint_id
  Inner JOIN temporarydeliverystop tst on tst.standarddeliveryline_id=stdl.standarddeliveryline_id
  Where  plpd.distributionpoint_id=M.DISTRIBUTIONPOINT_ID and plpd.product_id=i.product_id
  and plpd.finishingmethod_id=R.finishingmethod_id and plpd.sizedefinition_id=j.sizedefinition_id
  and L.DELIVERYSCHEME_ID=stdl.deliveryscheme_id
  AND (A.DRIVINGDATE between tst.startdate and tst.enddate)group by tst.startdate)DeliverStopStart
 , (Select tst.enddate from productlistperdistribpoint plpd
  inner JOIN standarddeliveryline stdl on stdl.productlistperdistribpoint_id=plpd.productlistperdistribpoint_id
  Inner JOIN temporarydeliverystop tst on tst.standarddeliveryline_id=stdl.standarddeliveryline_id
  Where  plpd.distributionpoint_id=M.DISTRIBUTIONPOINT_ID and plpd.product_id=i.product_id
  and plpd.finishingmethod_id=R.finishingmethod_id and plpd.sizedefinition_id=j.sizedefinition_id
  and L.DELIVERYSCHEME_ID=stdl.deliveryscheme_id
  AND (A.DRIVINGDATE between tst.startdate and tst.enddate) group by tst.enddate) DeliveryStopEnd
, (Select tst.temporarystopstartweek from productlistperdistribpoint plpd
  inner JOIN standarddeliveryline stdl on stdl.productlistperdistribpoint_id=plpd.productlistperdistribpoint_id
  Inner JOIN temporarydeliverystop tst on tst.standarddeliveryline_id=stdl.standarddeliveryline_id
  Where  plpd.distributionpoint_id=M.DISTRIBUTIONPOINT_ID and plpd.product_id=i.product_id
  and plpd.finishingmethod_id=R.finishingmethod_id and plpd.sizedefinition_id=j.sizedefinition_id
  and L.DELIVERYSCHEME_ID=stdl.deliveryscheme_id
  AND (getisoweek(A.DRIVINGDATE) between tst.temporarystopstartweek and tst.temporarystopendweek)group by tst.temporarystopstartweek)DeliverStopStartWeek
 , (Select tst.temporarystopendweek from productlistperdistribpoint plpd
  inner JOIN standarddeliveryline stdl on stdl.productlistperdistribpoint_id=plpd.productlistperdistribpoint_id
  Inner JOIN temporarydeliverystop tst on tst.standarddeliveryline_id=stdl.standarddeliveryline_id
  Where  plpd.distributionpoint_id=M.DISTRIBUTIONPOINT_ID and plpd.product_id=i.product_id
  and plpd.finishingmethod_id=R.finishingmethod_id and plpd.sizedefinition_id=j.sizedefinition_id
  and L.DELIVERYSCHEME_ID=stdl.deliveryscheme_id
  AND (getisoweek(A.DRIVINGDATE) between tst.temporarystopstartweek and tst.temporarystopendweek)group by tst.temporarystopendweek) DeliveryStopEndWeek
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 (
   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---
UNION ALL          -- 2 --
SELECT 3 Block,
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,
--  X.NAME DRIVERNAME, Y.CODE TRUCKCODE, Y.DESCRIPTION TRUCKDESCRIPTION,
  (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,
  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,
---case when d.routestop_id is null then d.routelistinstructions else E.ROUTELISTINSTRUCTIONS end ROUTELISTINSTRUCTIONS,
---501850
d.routelistinstructions,
  Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE, z.mobilephone,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
 , to_char((SELECT HH.STARTTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID), 'HH24:MI') DEL_POINT_START_TIME
  , to_char((SELECT HH.ENDTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID), 'HH24:MI') DEL_POINT_END_TIME
  ,  to_char(n.breakstarttime, 'HH24:MI') breakstarttime, to_char(n.breakendtime, 'HH24:MI') breakendtime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
  , p.dateinactive, M.Remarkonpackingnote, M.Remarkondeliverynote
  , (Select tst.startdate from productlistperdistribpoint plpd
  inner JOIN standarddeliveryline stdl on stdl.productlistperdistribpoint_id=plpd.productlistperdistribpoint_id
  Inner JOIN temporarydeliverystop tst on tst.standarddeliveryline_id=stdl.standarddeliveryline_id
  Where  plpd.distributionpoint_id=M.DISTRIBUTIONPOINT_ID and plpd.product_id=i.product_id
  and plpd.finishingmethod_id=R.finishingmethod_id and plpd.sizedefinition_id=j.sizedefinition_id
  and L.DELIVERYSCHEME_ID=stdl.deliveryscheme_id
  AND (A.DRIVINGDATE between tst.startdate and tst.enddate)group by tst.startdate)DeliverStopStart
 , (Select tst.enddate from productlistperdistribpoint plpd
  inner JOIN standarddeliveryline stdl on stdl.productlistperdistribpoint_id=plpd.productlistperdistribpoint_id
  Inner JOIN temporarydeliverystop tst on tst.standarddeliveryline_id=stdl.standarddeliveryline_id
  Where  plpd.distributionpoint_id=M.DISTRIBUTIONPOINT_ID and plpd.product_id=i.product_id
  and plpd.finishingmethod_id=R.finishingmethod_id and plpd.sizedefinition_id=j.sizedefinition_id
  and L.DELIVERYSCHEME_ID=stdl.deliveryscheme_id
  AND (A.DRIVINGDATE between tst.startdate and tst.enddate) group by tst.enddate) DeliveryStopEnd
, (Select tst.temporarystopstartweek from productlistperdistribpoint plpd
  inner JOIN standarddeliveryline stdl on stdl.productlistperdistribpoint_id=plpd.productlistperdistribpoint_id
  Inner JOIN temporarydeliverystop tst on tst.standarddeliveryline_id=stdl.standarddeliveryline_id
  Where  plpd.distributionpoint_id=M.DISTRIBUTIONPOINT_ID and plpd.product_id=i.product_id
  and plpd.finishingmethod_id=R.finishingmethod_id and plpd.sizedefinition_id=j.sizedefinition_id
  and L.DELIVERYSCHEME_ID=stdl.deliveryscheme_id
  AND (getisoweek(A.DRIVINGDATE) between tst.temporarystopstartweek and tst.temporarystopendweek)group by tst.temporarystopstartweek)DeliverStopStartWeek
 , (Select tst.temporarystopendweek from productlistperdistribpoint plpd
  inner JOIN standarddeliveryline stdl on stdl.productlistperdistribpoint_id=plpd.productlistperdistribpoint_id
  Inner JOIN temporarydeliverystop tst on tst.standarddeliveryline_id=stdl.standarddeliveryline_id
  Where  plpd.distributionpoint_id=M.DISTRIBUTIONPOINT_ID and plpd.product_id=i.product_id
  and plpd.finishingmethod_id=R.finishingmethod_id and plpd.sizedefinition_id=j.sizedefinition_id
  and L.DELIVERYSCHEME_ID=stdl.deliveryscheme_id
  AND (getisoweek(A.DRIVINGDATE) between tst.temporarystopstartweek and tst.temporarystopendweek)group by tst.temporarystopendweek) DeliveryStopEndWeek
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
    (d.status in (0, 3, 4) )
  AND P.COUNTRY_ID = W.COUNTRY_ID
and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
UNION ALL             -- 3 --
SELECT 4 Block,
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,
--  X.NAME DRIVERNAME, Y.CODE TRUCKCODE, Y.DESCRIPTION TRUCKDESCRIPTION,
  (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,
  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,
---case when d.routestop_id is null then d.routelistinstructions else E.ROUTELISTINSTRUCTIONS end ROUTELISTINSTRUCTIONS,
---501850
d.routelistinstructions,
  Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE,z.mobilephone, 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
 , to_char((SELECT HH.STARTTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = DP.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID), 'HH24:MI') DEL_POINT_START_TIME
  , to_char((SELECT HH.ENDTIME FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = DP.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID), 'HH24:MI') DEL_POINT_END_TIME
             ,to_char(dp.breakstarttime, 'HH24:MI') breakstarttime, to_char(dp.breakendtime, 'HH24:MI') breakendtime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES ROUTESTOP_TRAVELMINUTES, E.SERVICEMINUTES ROUTESTOP_SERVICEMINUTES
  , p.dateinactive, M.Remarkonpackingnote, M.Remarkondeliverynote
  , null DeliverStopStart
 , null DeliveryStopEnd, null DeliveryStopStartWeek, null DeliveryStopEndWeek
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
    LEFT OUTER JOIN distributionpoint m on m.deliverypoint_id=dp.deliverypoint_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
  (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_ROUTELIST_LLG
 (LINETYPE, ROUTESTOP_ID, DRIVINGYEAR, DRIVINGWEEK, NOTENUMBER, CUSTOMER_ID, SHOWSTOP, ROUTECONTROL_ID, STOP_DELIVERYPOINT_ID, PN_DELIVERYPOINT_ID, PLANTCODE, ROUTENUMBER, ROUTEDESCRIPTION, DRIVINGDATE, DRIVERNAME, STOPNUMBER, CUSTOMERNUMBER, SEARCHNAME, 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, PRODUCTDESCRIPTION, DELIVERYSCHEMESTARTDATE, QTYDELIVERED, QTYEXPECTED, ENDCONTRACT, LANGUAGECODE, DETAIL, STATUS, CUSTOMERCOUNTRYID, COUNTRY, PLANTCOUNTRYID, TYPEOFMERCHADISE, ROUTE_ID, STOPTYPE, REPORTPARAM_ID, 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, DEL_POINT_START_TIMECH, DEL_POINT_END_TIMECH, BREAKSTARTTIMECH, BREAKENDTIMECH, ROUTE_START_TIMECH, ROUTE_START_TIMECH24, STARTTIMECH, SHOWONROUTELIST, CONTACTNOTES, CONTACTSTATUS, PLANT_ID, PLANTEMAIL, NOOFSTOPS, CUSTOMERDELIVERYSCHEMCODE
, DRIVINGDAY_DESC, PNTHEORETICALWEIGHT, BU_CODE)
as SELECT 1 linetype,
  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.SEARCHNAME, P.NAME CUSTOMERNAME,insertspace_after_x_characters(to_char(P.CUSTOMERNUMBER),3) custnr,
  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, z.mobilephone, 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
  , n.breakstarttime breakstarttime, n.breakendtime breakendtime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
  , p.dateinactive
  , (SELECT to_char(HH.STARTTIME,'fmhhfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIMECH
  , (SELECT to_char(HH.ENDTIME,'fmhhfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIMECH
  , to_char(n.breakstarttime,'fmHH:MI:AM') breakstarttimeCH, to_char(n.breakendtime,'fmHH:MI:AM') breakendtimeCH
  , to_char(B.STARTTIME,'fmhhfm:MI:AM') ROUTE_START_TIMECH
  , to_char(B.STARTTIME,'fmhh24fm:MI') ROUTE_START_TIMECH24
  , to_char(A.STARTTIME,'fmhhfm:MI:AM') STARTTIMECH
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, a.plant_id
 ,cast((select GetSubstringOnLength(pl.email,0,40) from plant pl where pl.plant_id=a.plant_id)as varchar2(40)) plantemail
 , (select count(*) from stop s where s.routecontrol_id = a.routecontrol_id and F_SHOW_ROUTESTOP_STD(s.stop_id, s.routestop_id, d.stoptype, s.plant_id) = 1) noofstops
 , (select min(d.code) from customerdeliveryscheme cds, deliveryscheme d where cds.customer_id = p.customer_id
      and cds.deliveryscheme_id = d.deliveryscheme_id and cds.active = 'Y') customerdeliveryschemcode
 , (SELECT substr(DD.DESCRIPTION, 1, 3) FROM DAY_DESC DD WHERE DD.DAY_ID = B.DRIVINGDAY_ID AND DD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) DRIVINGDAY_DESC
 , (select ps.theoreticalweight from productsize ps where ps.product_id = i.product_id and ps.sizedefinition_id = j.sizedefinition_id) pntheoreticalweight
 , (select bu.code from businessunit bu where bu.businessunit_id = p.defaultbusinessunit_id) bu_code
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 (V_PACKINGNOTELINEPERDELSCH_EXT 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)
    left outer join contact cont ON (cont.contact_id = coalesce(f_getcontactonroutelist(p.customer_id), -1)),
  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 --TNE ORDER 500713
  and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
UNION ALL          -- 2 --
SELECT 2 linetype,
  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.SEARCHNAME, P.NAME CUSTOMERNAME,insertspace_after_x_characters(to_char(P.CUSTOMERNUMBER),3) custnr,
  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, z.mobilephone,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 breakstarttime, n.breakendtime breakendtime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
  , p.dateinactive
  , (SELECT to_char(HH.STARTTIME,'fmHHfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIMECH
  , (SELECT to_char(HH.ENDTIME,'fmHHfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIMECH
  , to_char(n.breakstarttime,'fmHHfm:MI:AM') breakstarttimeCH, to_char(n.breakendtime,'fmHH:MI:AM') breakendtimeCH
  , to_char(B.STARTTIME,'fmHHfm:MI:AM') ROUTE_START_TIMECH
  , to_char(B.STARTTIME,'fmHH24fm:MI') ROUTE_START_TIMECH24
  , to_char(A.STARTTIME,'fmHHfm:MI:AM') STARTTIMECH
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, a.plant_id
 ,cast((select GetSubstringOnLength(pl.email,0,40) from plant pl where pl.plant_id=a.plant_id)as varchar2(40)) plantemail
 , (select count(*) from stop s where s.routecontrol_id = a.routecontrol_id and F_SHOW_ROUTESTOP_STD(s.stop_id, s.routestop_id, d.stoptype, s.plant_id) = 1) noofstops
  , (select min(d.code) from customerdeliveryscheme cds, deliveryscheme d where cds.customer_id = p.customer_id
      and cds.deliveryscheme_id = d.deliveryscheme_id and cds.active = 'Y') customerdeliveryschemcode
 , (SELECT substr(DD.DESCRIPTION, 1, 3) FROM DAY_DESC DD WHERE DD.DAY_ID = B.DRIVINGDAY_ID AND DD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) DRIVINGDAY_DESC
  , (select ps.theoreticalweight from productsize ps where ps.product_id = i.product_id and ps.sizedefinition_id = j.sizedefinition_id) pntheoreticalweight
  , (select bu.code from businessunit bu where bu.businessunit_id = p.defaultbusinessunit_id) bu_code
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)
    left outer join contact cont ON (cont.contact_id = coalesce(f_getcontactonroutelist(p.customer_id), -1)),
  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 linetype,
  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.SEARCHNAME, P.NAME CUSTOMERNAME,insertspace_after_x_characters(to_char(P.CUSTOMERNUMBER),3) custnr,
  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,z.mobilephone, 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 breakstarttime, dp.breakendtime breakendtime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES ROUTESTOP_TRAVELMINUTES, E.SERVICEMINUTES ROUTESTOP_SERVICEMINUTES
  , p.dateinactive
  , (SELECT to_char(HH.STARTTIME,'fmHHfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = dp.DELIVERYPOINT_ID AND HH.DAY_ID = B.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 = B.DRIVINGDAY_ID) DEL_POINT_END_TIMECH
  , to_char(dp.breakstarttime,'fmHHfm:MI:AM') breakstarttimeCH, to_char(dp.breakendtime,'fmHH:MI:AM') breakendtimeCH
  , to_char(B.STARTTIME,'fmHHfm:MI:AM') ROUTE_START_TIMECH
  , to_char(B.STARTTIME,'fmHH24fm:MI') ROUTE_START_TIMECH24
  , to_char(A.STARTTIME,'fmHHfm:MI:AM') STARTTIMECH
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, a.plant_id
 ,cast((select GetSubstringOnLength(pl.email,0,40) from plant pl where pl.plant_id=a.plant_id)as varchar2(40)) plantemail
 , (select count(*) from stop s where s.routecontrol_id = a.routecontrol_id and F_SHOW_ROUTESTOP_STD(s.stop_id, s.routestop_id, d.stoptype, s.plant_id) = 1) noofstops
  , (select min(d.code) from customerdeliveryscheme cds, deliveryscheme d where cds.customer_id = p.customer_id
      and cds.deliveryscheme_id = d.deliveryscheme_id and cds.active = 'Y') customerdeliveryschemcode
 , (SELECT substr(DD.DESCRIPTION, 1, 3) FROM DAY_DESC DD WHERE DD.DAY_ID = B.DRIVINGDAY_ID AND DD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) DRIVINGDAY_DESC
 , 0 pntheoreticalweight
 , (select bu.code from businessunit bu where bu.businessunit_id = p.defaultbusinessunit_id) bu_code
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)
    left outer join contact cont ON (cont.contact_id = coalesce(f_getcontactonroutelist(p.customer_id), -1)),
  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_ROUTELIST_PHS
 (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, 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 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,
--  X.NAME DRIVERNAME, Y.CODE TRUCKCODE, Y.DESCRIPTION TRUCKDESCRIPTION,
  (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,
  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,
 --- case when d.routestop_id is null then d.routelistinstructions else E.ROUTELISTINSTRUCTIONS end ROUTELISTINSTRUCTIONS,
 --501850
 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 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,
  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
  (d.status in (0, 3, 4) )
  AND P.COUNTRY_ID = W.COUNTRY_ID --TNE ORDER 500713
and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
UNION ALL          -- 2 --
SELECT 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,
--  X.NAME DRIVERNAME, Y.CODE TRUCKCODE, Y.DESCRIPTION TRUCKDESCRIPTION,
  (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,
  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,
---case when d.routestop_id is null then d.routelistinstructions else E.ROUTELISTINSTRUCTIONS end ROUTELISTINSTRUCTIONS,
---501850
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 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
    (d.status in (0, 3, 4) )
  AND P.COUNTRY_ID = W.COUNTRY_ID
and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
UNION ALL             -- 3 --
SELECT 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,
--  X.NAME DRIVERNAME, Y.CODE TRUCKCODE, Y.DESCRIPTION TRUCKDESCRIPTION,
  (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,
  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,
---case when d.routestop_id is null then d.routelistinstructions else E.ROUTELISTINSTRUCTIONS end ROUTELISTINSTRUCTIONS,
---501850
d.routelistinstructions,
  Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE, P.PHONENO CUSTOMERPHONE, D.STOP_ID,
  o.departmentnumber, m.distributionpointnumber, dp.code deliverypointcode,
  o.description departmentdesc, m.description 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 V_MOVEDOUTSTOPS V on D.STOP_ID = V.movedtostop_id-- order500701
    left outer join CONTACTPERSON Z ON D.CONTACTPERSON_ID = Z.CONTACTPERSON_ID
      inner join DELIVERYPOINT DP inner JOIN ADDRESS T ON DP.DELIVERYADDRESS_ID = T.ADDRESS_ID
                                  inner JOIN DISTRIBUTIONPOINT M
                                         inner JOIN DEPARTMENT O ON m.department_id=o.department_id
                                       ON DP.Deliverypoint_Id=m.deliverypoint_id
      ON D.DELIVERYPOINT_ID = DP.DELIVERYPOINT_ID
    inner 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
  (d.status in (0, 3, 4) )
  AND P.COUNTRY_ID = W.COUNTRY_ID
  and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
UNION ALL             -- 4 --
SELECT 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,
--  X.NAME DRIVERNAME, Y.CODE TRUCKCODE, Y.DESCRIPTION TRUCKDESCRIPTION,
  (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,
  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,
---case when d.routestop_id is null then d.routelistinstructions else E.ROUTELISTINSTRUCTIONS end ROUTELISTINSTRUCTIONS,
---501850
d.routelistinstructions,
  Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE, P.PHONENO CUSTOMERPHONE, D.STOP_ID,
  o.departmentnumber, -1 distributionpointnumber, dp.code deliverypointcode,
  o.description 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 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)
    LEFT OUTER JOIN DEPARTMENT O ON p.customer_id=o.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
  (d.status in (0, 3, 4) )
  AND P.COUNTRY_ID = W.COUNTRY_ID
  and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
  and not exists (select * from distributionpoint m where dp.deliverypoint_id=m.deliverypoint_id)

/
create or replace view V_ROUTELIST_REV
 (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, STOPNUMBER, CUSTOMERNUMBER, CUSTOMERNAME, 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, DATEINACTIVE, DEL_POINT_START_TIMECH, DEL_POINT_END_TIMECH, BREAKSTARTTIMECH, BREAKENDTIMECH
, BREAKSTARTTIMECH24, BREAKENDTIMECH24, ROUTE_START_TIMECH, ROUTE_START_TIMECH24, STARTTIMECH, SHOWONROUTELIST, CONTACTNOTES, CONTACTSTATUS, PLANT_ID, PAYMENTTERMTYPE, THEORETICALWEIGHT, NOOFMATS, NOOFCONTAINERS)
as SELECT 1.1 linetype,
  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,
  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, z.mobilephone, 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 L.Code from V_PACKINGNOTELINEPERDELSCH_EXT H join DeliveryScheme L on H.deliveryscheme_id=L.Deliveryscheme_Id where  h.deliveryscheme_id=pld.deliveryscheme_id and H.packingnoteline_id=G.Packingnoteline_Id ) DELIVERYSCHEMECODE,
  (SELECT description FROM PRODUCT_DESC W WHERE I.PRODUCT_ID = W.PRODUCT_ID AND W.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
 (select H.startdate from V_PACKINGNOTELINEPERDELSCH_EXT H where H.packingnoteline_id=G.Packingnoteline_Id and h.deliveryscheme_id=pld.deliveryscheme_id) DELIVERYSCHEMESTARTDATE,
  (select H.deliveredqty from V_PACKINGNOTELINEPERDELSCH_EXT H where H.packingnoteline_id=G.Packingnoteline_Id and h.deliveryscheme_id=pld.deliveryscheme_id) QTYDELIVERED,
--  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,
 case when exists (select 1 from V_PACKINGNOTELINEPERDELSCH_EXT H where G.Packingnoteline_Id=H.packingnoteline_id) then 1 else 0 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
  , n.breakstarttime breakstarttime, n.breakendtime breakendtime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
  , p.dateinactive
  , coalesce((SELECT to_char(HH.STARTTIME,'fmhh24fm:MI') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID)
            , (SELECT to_char(HH.STARTTIME,'fmhh24fm:MI') FROM deliverypointopeninghour HH, deliverypoint delpo
            WHERE HH.DELIVERYPOINT_ID = delpo.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID and delpo.code = '1' and delpo.customer_id = p.customer_id)) DEL_POINT_START_TIMECH
  , coalesce((SELECT to_char(HH.ENDTIME,'fmhh24fm:MI') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID)
            , (SELECT to_char(HH.ENDTIME,'fmhh24fm:MI') FROM deliverypointopeninghour HH, deliverypoint delpo
            WHERE HH.DELIVERYPOINT_ID = delpo.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID and delpo.code = '1' and delpo.customer_id = p.customer_id)) DEL_POINT_END_TIMECH
  , to_char(n.breakstarttime,'fmHH:MI:AM') breakstarttimeCH, to_char(n.breakendtime,'fmHH:MI:AM') breakendtimeCH
  , coalesce(to_char(n.breakstarttime,'fmHH24fm:MI'), (SELECT to_char(delpo.breakstarttime,'fmhh24fm:MI') FROM deliverypoint delpo
            WHERE delpo.code = '1' and delpo.customer_id = p.customer_id)) breakstarttimeCH24
  , coalesce(to_char(n.breakendtime,'fmHH24fm:MI'), (SELECT to_char(delpo.breakendtime,'fmhh24fm:MI') FROM deliverypoint delpo
            WHERE delpo.code = '1' and delpo.customer_id = p.customer_id)) breakendtimeCH24
  , to_char(B.STARTTIME,'fmhhfm:MI:AM') ROUTE_START_TIMECH
  , to_char(B.STARTTIME,'fmhh24fm:MI') ROUTE_START_TIMECH24
  , to_char(A.STARTTIME,'fmhhfm:MI:AM') STARTTIMECH
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, a.plant_id
  , (select pt.paymenttermtype from customerbillinginfo cb, paymentterms pt where p.customer_id = cb.customer_id and cb.paymentterms_id = pt.paymentterms_id) paymenttermtype
  , i.theoreticalweight
  , (select count(1) from productgroup pg, activity ac where pg.activity_id = ac.activity_id and i.productgroup_id = pg.productgroup_id and ac.code = '1') NoOfMats
  , (select count(1) from PACKINGNOTECONTAINER pnc
   left outer join CONTAINER C on C.CONTAINER_ID = PNC.CONTAINER_ID
   left outer join CONTAINERTYPE CT on CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   left outer join WEIGHINGCATEGORY W on W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 where pnc.packingnote_id = f.Packingnote_Id) noOfContainers
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 join packingnotelineperdelscheme pld on g.packingnoteline_id=pld.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)
    left outer join contact cont ON (cont.customer_link_id = p.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 --TNE ORDER 500713
  and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
union all
 SELECT 1.2 linetype,
  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,
  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, z.mobilephone, 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, null 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
  , n.breakstarttime breakstarttime, n.breakendtime breakendtime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
  , p.dateinactive
  , coalesce((SELECT to_char(HH.STARTTIME,'fmhh24fm:MI') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID)
            , (SELECT to_char(HH.STARTTIME,'fmhh24fm:MI') FROM deliverypointopeninghour HH, deliverypoint delpo
            WHERE HH.DELIVERYPOINT_ID = delpo.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID and delpo.code = '1' and delpo.customer_id = p.customer_id)) DEL_POINT_START_TIMECH
  , coalesce((SELECT to_char(HH.ENDTIME,'fmhh24fm:MI') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID)
            , (SELECT to_char(HH.ENDTIME,'fmhh24fm:MI') FROM deliverypointopeninghour HH, deliverypoint delpo
            WHERE HH.DELIVERYPOINT_ID = delpo.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID and delpo.code = '1' and delpo.customer_id = p.customer_id)) DEL_POINT_END_TIMECH
  , to_char(n.breakstarttime,'fmHH:MI:AM') breakstarttimeCH, to_char(n.breakendtime,'fmHH:MI:AM') breakendtimeCH
  , coalesce(to_char(n.breakstarttime,'fmHH24fm:MI'), (SELECT to_char(delpo.breakstarttime,'fmhh24fm:MI') FROM deliverypoint delpo
            WHERE delpo.code = '1' and delpo.customer_id = p.customer_id)) breakstarttimeCH24
  , coalesce(to_char(n.breakendtime,'fmHH24fm:MI'), (SELECT to_char(delpo.breakendtime,'fmhh24fm:MI') FROM deliverypoint delpo
            WHERE delpo.code = '1' and delpo.customer_id = p.customer_id)) breakendtimeCH24
  , to_char(B.STARTTIME,'fmhhfm:MI:AM') ROUTE_START_TIMECH
  , to_char(B.STARTTIME,'fmhh24fm:MI') ROUTE_START_TIMECH24
  , to_char(A.STARTTIME,'fmhhfm:MI:AM') STARTTIMECH
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, a.plant_id
  , (select pt.paymenttermtype from customerbillinginfo cb, paymentterms pt where p.customer_id = cb.customer_id and cb.paymentterms_id = pt.paymentterms_id) paymenttermtype
  , i.theoreticalweight
  , (select count(1) from productgroup pg, activity ac where pg.activity_id = ac.activity_id and i.productgroup_id = pg.productgroup_id and ac.code = '1') NoOfMats
  , (select count(1) from PACKINGNOTECONTAINER pnc
   left outer join CONTAINER C on C.CONTAINER_ID = PNC.CONTAINER_ID
   left outer join CONTAINERTYPE CT on CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   left outer join WEIGHINGCATEGORY W on W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 where pnc.packingnote_id = f.Packingnote_Id) noOfContainers
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 V_PACKINGNOTELINEPERDELSCH_EXT H
        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)
    left outer join contact cont ON (cont.customer_link_id = p.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 --TNE ORDER 500713
  and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
  and h.deliveryscheme_id is null
  union all
SELECT 2 linetype,
  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,
  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, z.mobilephone,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 breakstarttime, n.breakendtime breakendtime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
  , p.dateinactive
  , coalesce((SELECT to_char(HH.STARTTIME,'fmhh24fm:MI') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID)
            , (SELECT to_char(HH.STARTTIME,'fmhh24fm:MI') FROM deliverypointopeninghour HH, deliverypoint delpo
            WHERE HH.DELIVERYPOINT_ID = delpo.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID and delpo.code = '1' and delpo.customer_id = p.customer_id)) DEL_POINT_START_TIMECH
  , coalesce((SELECT to_char(HH.ENDTIME,'fmhh24fm:MI') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID)
            , (SELECT to_char(HH.STARTTIME,'fmhh24fm:MI') FROM deliverypointopeninghour HH, deliverypoint delpo
            WHERE HH.DELIVERYPOINT_ID = delpo.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID and delpo.code = '1' and delpo.customer_id = p.customer_id)) DEL_POINT_END_TIMECH
  , to_char(n.breakstarttime,'fmHHfm:MI:AM') breakstarttimeCH, to_char(n.breakendtime,'fmHH:MI:AM') breakendtimeCH
  , coalesce(to_char(n.breakstarttime,'fmHH24fm:MI'), (SELECT to_char(delpo.breakstarttime,'fmhh24fm:MI') FROM deliverypoint delpo
            WHERE delpo.code = '1' and delpo.customer_id = p.customer_id)) breakstarttimeCH24
  , coalesce(to_char(n.breakendtime,'fmHH24fm:MI'), (SELECT to_char(delpo.breakendtime,'fmhh24fm:MI') FROM deliverypoint delpo
            WHERE delpo.code = '1' and delpo.customer_id = p.customer_id)) breakendtimeCH24
  , to_char(B.STARTTIME,'fmHHfm:MI:AM') ROUTE_START_TIMECH
  , to_char(B.STARTTIME,'fmHH24fm:MI') ROUTE_START_TIMECH24
  , to_char(A.STARTTIME,'fmHHfm:MI:AM') STARTTIMECH
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, a.plant_id
  , (select pt.paymenttermtype from customerbillinginfo cb, paymentterms pt where p.customer_id = cb.customer_id and cb.paymentterms_id = pt.paymentterms_id) paymenttermtype
  , i.theoreticalweight
  , (select count(1) from productgroup pg, activity ac where pg.activity_id = ac.activity_id and i.productgroup_id = pg.productgroup_id and ac.code = '1') NoOfMats
  , 0 noOfContainers
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)
    left outer join contact cont ON (cont.customer_link_id = p.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 linetype,
  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,
  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,z.mobilephone, 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 breakstarttime, dp.breakendtime breakendtime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES ROUTESTOP_TRAVELMINUTES, E.SERVICEMINUTES ROUTESTOP_SERVICEMINUTES
  , p.dateinactive
  , coalesce((SELECT to_char(HH.STARTTIME,'fmhh24fm:MI') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = dp.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID)
            , (SELECT to_char(HH.STARTTIME,'fmhh24fm:MI') FROM deliverypointopeninghour HH, deliverypoint delpo
            WHERE HH.DELIVERYPOINT_ID = delpo.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID and delpo.code = '1' and delpo.customer_id = p.customer_id)) DEL_POINT_START_TIMECH
  , coalesce((SELECT to_char(HH.ENDTIME,'fmhh24fm:MI') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = dp.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID)
            , (SELECT to_char(HH.STARTTIME,'fmhh24fm:MI') FROM deliverypointopeninghour HH, deliverypoint delpo
            WHERE HH.DELIVERYPOINT_ID = delpo.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID and delpo.code = '1' and delpo.customer_id = p.customer_id)) DEL_POINT_END_TIMECH
  , to_char(dp.breakstarttime,'fmHHfm:MI:AM') breakstarttimeCH, to_char(dp.breakendtime,'fmHH:MI:AM') breakendtimeCH
  , coalesce(to_char(dp.breakstarttime,'fmHH24fm:MI'), (SELECT to_char(delpo.breakstarttime,'fmhh24fm:MI') FROM deliverypoint delpo
            WHERE delpo.code = '1' and delpo.customer_id = p.customer_id)) breakstarttimeCH24
  , coalesce(to_char(dp.breakendtime,'fmHH24fm:MI'), (SELECT to_char(delpo.breakendtime,'fmhh24fm:MI') FROM deliverypoint delpo
            WHERE delpo.code = '1' and delpo.customer_id = p.customer_id)) breakendtimeCH24
  , to_char(B.STARTTIME,'fmHHfm:MI:AM') ROUTE_START_TIMECH
  , to_char(B.STARTTIME,'fmHH24fm:MI') ROUTE_START_TIMECH24
  , to_char(A.STARTTIME,'fmHHfm:MI:AM') STARTTIMECH
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, a.plant_id
  , (select pt.paymenttermtype from customerbillinginfo cb, paymentterms pt where p.customer_id = cb.customer_id and cb.paymentterms_id = pt.paymentterms_id) paymenttermtype
  , 0 theoreticalweight
  , 0 NoOfMats
  , 0 noOfContainers
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)
    left outer join contact cont ON (cont.customer_link_id = p.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_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 b.INVOICEHEADER_ID, b.PARENTINVOICEHEADER_ID, b.INVOICENUMBER,
  b.isconsolidateinv,
  b.year, b.week, b.FREQUENCY,
  (select sum(
          case
            when ili.adjustedamount <> 0 then
              ili.adjustedamount
            else
              ili.amount
          end)
  from invoiceline ili where ili.invoiceheader_id=b.invoiceheader_id
  and  ili.processingbusinessunit_id=b.processingbusinessunit_id  and ili.extend='Y')paythisamount,
  (select sum(ili.amount) from invoiceline ili where ili.invoiceheader_id=b.invoiceheader_id
  and ili.invoicelinetype_id<>18 and ili.processingbusinessunit_id=b.processingbusinessunit_id
  and ili.extend='Y')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
, 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
    ( 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_SHORTAGES_NLI
 (BUSINESSUNITCODE, BUSINESSUNITDESC, CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESC, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESC, PRODUCTGROUPCODE, PRODUCTCODE, SIZEDEFINITIONCODE, FINISHINGMETHODCODE, PRODUCTDESC, YEAR, WEEK, DAYNUMBER, YEARWEEK, AMOUNTSHORTAGE, CUSTOMERLANGUAGECODE, LANGUAGECODE, DEFAULTBUSINESSUNIT_ID)
as SELECT
  BU.CODE BUSINESSUNITCODE, BU.DESCRIPTION BUSINESSUNITDESC, CULK.CUSTOMERNUMBER, CULK.NAME CUSTOMERNAME
, DELK.DEPARTMENTNUMBER, DELK.DESCRIPTION DEPARTMENTDESC, DILK.DISTRIBUTIONPOINTNUMBER, DILK.DESCRIPTION DISTRIBUTIONPOINTDESC
, PRODUCTGROUP.CODE PRODUCTGROUPCODE
, 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
, PN.YEAR, PN.WEEK, PN.DAYNUMBER, (PN.YEAR*100) + PN.WEEK YEARWEEK
, (PNL.TOBEDELIVEREDAMOUNT - PNL.DELIVEREDAMOUNT -
     COALESCE((SELECT SUM(DELIVERYVARIATIONS.AMOUNT) FROM DELIVERYVARIATIONS
         WHERE DELIVERYVARIATIONS.ORIGIN IN (4,5) AND
         DELIVERYVARIATIONS.PACKINGNOTE_ID = PN.PACKINGNOTE_ID AND
         DELIVERYVARIATIONS.PRODUCT_ID = PNL.PRODUCT_ID AND
         DELIVERYVARIATIONS.SIZEDEFINITION_ID = PNL.SIZEDEFINITION_ID AND
         DELIVERYVARIATIONS.FINISHINGMETHOD_ID = PNL.FINISHINGMETHOD_ID), 0)
  ) AMOUNTSHORTAGE
, CULK.LANGUAGECODE CUSTOMERLANGUAGECODE, LANGUAGES.CODE LANGUAGECODE
, DEFAULT_BU.BUSINESSUNIT_ID DEFAULTBUSINESSUNIT_ID
FROM
  PACKINGNOTE PN, PACKINGNOTELINE PNL, STATUS ST,
  CUSTOMER_LINK CULK, BUSINESSUNIT BU, DEPARTMENT_LINK DELK, DISTRIBUTIONPOINT_LINK DILK
, PRODUCT_LINK PRDLK
               LEFT OUTER JOIN PRODUCTGROUP ON PRDLK.PRODUCTGROUPCODE = PRODUCTGROUP.CODE
, SIZEDEFINITION_LINK SZLK, FINISHINGMETHOD FM
, LANGUAGES
, BUSINESSUNIT DEFAULT_BU
WHERE PN.PACKINGNOTE_ID = PNL.PACKINGNOTE_ID AND
      PN.PROCESSBUSINESSUNIT_ID = BU.BUSINESSUNIT_ID AND
      PN.STATUS_ID = ST.STATUS_ID AND ST.STATUSTYPE = 'PN' AND ST.CODE = '30' AND
      PN.DISTRIBUTIONPOINT_ID = DILK.DISTRIBUTIONPOINT_LINK_ID AND
      DILK.DEPARTMENT_LINK_ID = DELK.DEPARTMENT_LINK_ID AND
      DELK.CUSTOMER_LINK_ID = CULK.CUSTOMER_LINK_ID AND
      PNL.PRODUCT_ID = PRDLK.PRODUCT_LINK_ID AND
      PNL.SIZEDEFINITION_ID = SZLK.SIZEDEFINITION_LINK_ID AND
      PNL.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_SKISSUENEWGARMENTS
 (TRANSACTIONDATE, STOCKROOMCODE, STOCKROOMNAME, MANAGEDBYBU_ID, REASONCODE, FIRSTISSUE, INVENTORYTRIGGER, PRODUCTGROUPCODE, PRODUCTCODE, PRODUCTDESC, REASONDESC, ISSUEDNEW, PURCHASEAMOUNT, LANGUAGECODE, DEPOT_CODE, DEPOT_DESC, ROUTENUMBER, ROUTE_DESC)
as select
  GETDATEONLY(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 product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( select reasoncode_desc.description from reasoncode_desc where reasoncode_desc.reasoncode_id = rc.reasoncode_id
  and reasoncode_desc.language_id = languages.language_id ) reasonDesc
, ih.quantity issuedNew
, uif.purchaseprice purchaseAmount
, languages.code languageCode
, de.code Depot_code, de.description Depot_desc, r.routenumber, r.description Route_desc--, r.drivingday_id
from issuehistory ih
, qualitygrade qg, reasoncode rc
, product prd, productgroup prdgr
, uniqueitem ui, uniqueitemfixedinfo uif
, stockroom sk
--, stockreservationpergrade srg, stockdefinitionperitem sdi
--, purchaseorderstocktransaction pst, purchaseorderline pl
, languages
, businessunit bu
, customer cu , route r left outer join depot de on r.depot_id=de.depot_id
where
    ih.issuegrade_id = qg.qualitygrade_id
    and qg.newgarment = 'Y'
and ih.reasoncode_id = rc.reasoncode_id
    and rc.garmentreason = 'Y'
and ih.product_link_id = prd.product_id
    and prd.typeofmerchandise = 2
        and prd.productgroup_id = prdgr.productgroup_id
and ih.uniqueitem_link_id = ui.uniqueitem_id
    and ui.uniqueitem_id = uif.uniqueitem_id
and ih.stockroom_id = sk.stockroom_id
and bu.businessunit_id = ih.forbusinessunit_id
and ih.customer_link_id = cu.customer_id
and r.plant_id = bu.plant_id
and r.route_id in (select v.min_route_id from v_mincustomerroute v
                  where v.customer_id=cu.customer_id)
union all
select
  GETDATEONLY(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 product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( select reasoncode_desc.description from reasoncode_desc where reasoncode_desc.reasoncode_id = rc.reasoncode_id
  and reasoncode_desc.language_id = languages.language_id ) reasonDesc
, ih.quantity issuedNew
, uif.purchaseprice purchaseAmount
, languages.code languageCode
, null Depot_code, null Depot_desc, null routenumber, null Route_desc--, r.drivingday_id
from issuehistory ih
, qualitygrade qg, reasoncode rc
, product prd, productgroup prdgr
, uniqueitem ui, uniqueitemfixedinfo uif
, stockroom sk
--, stockreservationpergrade srg, stockdefinitionperitem sdi
--, purchaseorderstocktransaction pst, purchaseorderline pl
, languages
, businessunit bu
where
    ih.issuegrade_id = qg.qualitygrade_id
    and qg.newgarment = 'Y'
and ih.reasoncode_id = rc.reasoncode_id
    and rc.garmentreason = 'Y'
and ih.product_link_id = prd.product_id
    and prd.typeofmerchandise = 2
        and prd.productgroup_id = prdgr.productgroup_id
and ih.uniqueitem_link_id = ui.uniqueitem_id
    and ui.uniqueitem_id = uif.uniqueitem_id
and ih.stockroom_id = sk.stockroom_id
and bu.businessunit_id = ih.forbusinessunit_id
and ih.customer_link_id not in (select cu.customer_id from customer cu)
union all -- non uniqueitems
select
  GETDATEONLY(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 product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( select reasoncode_desc.description from reasoncode_desc where reasoncode_desc.reasoncode_id = rc.reasoncode_id
  and reasoncode_desc.language_id = languages.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
, languages.code languageCode
, null Depot_code, null Depot_desc, null routenumber, null Route_desc--, r.drivingday_id
from issuehistory ih
, qualitygrade qg, reasoncode rc
, product prd, productgroup prdgr
, stockroom sk
, languages
, businessunit bu
where
    ih.issuegrade_id = qg.qualitygrade_id
    and qg.newgarment = 'Y'
and ih.reasoncode_id = rc.reasoncode_id
    and rc.garmentreason = 'Y'
and ih.product_link_id = prd.product_id
    and prd.typeofmerchandise = 2
    and prd.productgroup_id = prdgr.productgroup_id
and ih.stockroom_id = sk.stockroom_id
and bu.businessunit_id = ih.forbusinessunit_id
and ih.uniqueitem_link_id is null

/
create or replace view V_SKISSUENEWGARMENTS_LTS
 (TRANSACTIONDATE, STOCKROOMCODE, STOCKROOMNAME, MANAGEDBYBU_ID, REASONCODE, FIRSTISSUE, INVENTORYTRIGGER, PRODUCTGROUPCODE, PRODUCTCODE, PRODUCTDESC, REASONDESC, ISSUEDNEW, PURCHASEAMOUNT, LANGUAGECODE, DEPOT_CODE, DEPOT_DESC, ROUTENUMBER, ROUTE_DESC)
as select
  GETDATEONLY(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 product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( select reasoncode_desc.description from reasoncode_desc where reasoncode_desc.reasoncode_id = rc.reasoncode_id
  and reasoncode_desc.language_id = languages.language_id ) reasonDesc
, ih.quantity issuedNew
, uif.purchaseprice purchaseAmount
, languages.code languageCode
, de.code Depot_code, de.description Depot_desc, r.routenumber, r.description Route_desc--, r.drivingday_id
from issuehistory ih
, qualitygrade qg, reasoncode rc
, product prd, productgroup prdgr
, uniqueitem ui, uniqueitemfixedinfo uif
, stockroom sk
--, stockreservationpergrade srg, stockdefinitionperitem sdi
--, purchaseorderstocktransaction pst, purchaseorderline pl
, languages
, businessunit bu
, customer cu , route r left outer join depot de on r.depot_id=de.depot_id
where
    ih.issuegrade_id = qg.qualitygrade_id
    --and qg.newgarment = 'Y'
and ih.reasoncode_id = rc.reasoncode_id
    and rc.garmentreason = 'Y'
and ih.product_link_id = prd.product_id
    and prd.typeofmerchandise = 2
        and prd.productgroup_id = prdgr.productgroup_id
and ih.uniqueitem_link_id = ui.uniqueitem_id
    and ui.uniqueitem_id = uif.uniqueitem_id
and ih.stockroom_id = sk.stockroom_id
and bu.businessunit_id = ih.forbusinessunit_id
and ih.customer_link_id = cu.customer_id
and r.plant_id = bu.plant_id
and r.route_id in (select v.min_route_id from v_mincustomerroute v
                  where v.customer_id=cu.customer_id)
union all
select
  GETDATEONLY(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 product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( select reasoncode_desc.description from reasoncode_desc where reasoncode_desc.reasoncode_id = rc.reasoncode_id
  and reasoncode_desc.language_id = languages.language_id ) reasonDesc
, ih.quantity issuedNew
, uif.purchaseprice purchaseAmount
, languages.code languageCode
, null Depot_code, null Depot_desc, null routenumber, null Route_desc--, r.drivingday_id
from issuehistory ih
, qualitygrade qg, reasoncode rc
, product prd, productgroup prdgr
, uniqueitem ui, uniqueitemfixedinfo uif
, stockroom sk
--, stockreservationpergrade srg, stockdefinitionperitem sdi
--, purchaseorderstocktransaction pst, purchaseorderline pl
, languages
, businessunit bu
where
    ih.issuegrade_id = qg.qualitygrade_id
    and qg.newgarment = 'Y'
and ih.reasoncode_id = rc.reasoncode_id
    and rc.garmentreason = 'Y'
and ih.product_link_id = prd.product_id
    and prd.typeofmerchandise = 2
        and prd.productgroup_id = prdgr.productgroup_id
and ih.uniqueitem_link_id = ui.uniqueitem_id
    and ui.uniqueitem_id = uif.uniqueitem_id
and ih.stockroom_id = sk.stockroom_id
and bu.businessunit_id = ih.forbusinessunit_id
and ih.customer_link_id not in (select cu.customer_id from customer cu)

/
create or replace view V_SKISSUENEWGARMENTS_SGS
 (TRANSACTIONDATE, STOCKROOMCODE, STOCKROOMNAME, MANAGEDBYBU_ID, REASONCODE, FIRSTISSUE, INVENTORYTRIGGER, PRODUCTGROUPCODE, PRODUCTCODE, PRODUCTDESC, REASONDESC, ISSUEDNEW, PURCHASEAMOUNT, LANGUAGECODE, DEPOT_CODE, DEPOT_DESC, ROUTENUMBER, ROUTE_DESC, NEWGARMENT)
as select
  GETDATEONLY(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 product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( select reasoncode_desc.description from reasoncode_desc where reasoncode_desc.reasoncode_id = rc.reasoncode_id
  and reasoncode_desc.language_id = languages.language_id ) reasonDesc
, ih.quantity issuedNew
, uif.purchaseprice purchaseAmount
, languages.code languageCode
, de.code Depot_code, de.description Depot_desc, r.routenumber, r.description Route_desc--, r.drivingday_id
, qg.newgarment
from issuehistory ih
, qualitygrade qg, reasoncode rc
, product prd, productgroup prdgr
, uniqueitem ui, uniqueitemfixedinfo uif
, stockroom sk
--, stockreservationpergrade srg, stockdefinitionperitem sdi
--, purchaseorderstocktransaction pst, purchaseorderline pl
, languages
, businessunit bu
, customer cu , route r left outer join depot de on r.depot_id=de.depot_id
where
    ih.issuegrade_id = qg.qualitygrade_id --and qg.newgarment = 'Y'
and ih.reasoncode_id = rc.reasoncode_id
    and rc.garmentreason = 'Y'
and ih.product_link_id = prd.product_id
    and prd.typeofmerchandise = 2
        and prd.productgroup_id = prdgr.productgroup_id
and ih.uniqueitem_link_id = ui.uniqueitem_id
    and ui.uniqueitem_id = uif.uniqueitem_id
and ih.stockroom_id = sk.stockroom_id
and bu.businessunit_id = ih.forbusinessunit_id
and ih.customer_link_id = cu.customer_id
and r.plant_id = bu.plant_id
and r.route_id in (select v.min_route_id from v_mincustomerroute v
                  where v.customer_id=cu.customer_id)
union all
select
  GETDATEONLY(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 product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( select reasoncode_desc.description from reasoncode_desc where reasoncode_desc.reasoncode_id = rc.reasoncode_id
  and reasoncode_desc.language_id = languages.language_id ) reasonDesc
, ih.quantity issuedNew
, uif.purchaseprice purchaseAmount
, languages.code languageCode
, null Depot_code, null Depot_desc, null routenumber, null Route_desc--, r.drivingday_id
, qg.newgarment
from issuehistory ih
, qualitygrade qg, reasoncode rc
, product prd, productgroup prdgr
, uniqueitem ui, uniqueitemfixedinfo uif
, stockroom sk
--, stockreservationpergrade srg, stockdefinitionperitem sdi
--, purchaseorderstocktransaction pst, purchaseorderline pl
, languages
, businessunit bu
where
    ih.issuegrade_id = qg.qualitygrade_id--    and qg.newgarment = 'Y'
and ih.reasoncode_id = rc.reasoncode_id
    and rc.garmentreason = 'Y'
and ih.product_link_id = prd.product_id
    and prd.typeofmerchandise = 2
        and prd.productgroup_id = prdgr.productgroup_id
and ih.uniqueitem_link_id = ui.uniqueitem_id
    and ui.uniqueitem_id = uif.uniqueitem_id
and ih.stockroom_id = sk.stockroom_id
and bu.businessunit_id = ih.forbusinessunit_id
and ih.customer_link_id not in (select cu.customer_id from customer cu)
union all -- non uniqueitems
select
  GETDATEONLY(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 product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDesc
, ( select reasoncode_desc.description from reasoncode_desc where reasoncode_desc.reasoncode_id = rc.reasoncode_id
  and reasoncode_desc.language_id = languages.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
, languages.code languageCode
, null Depot_code, null Depot_desc, null routenumber, null Route_desc--, r.drivingday_id
, qg.newgarment
from issuehistory ih
, qualitygrade qg, reasoncode rc
, product prd, productgroup prdgr
, stockroom sk
, languages
, businessunit bu
where
    ih.issuegrade_id = qg.qualitygrade_id--    and qg.newgarment = 'Y'
and ih.reasoncode_id = rc.reasoncode_id
    and rc.garmentreason = 'Y'
and ih.product_link_id = prd.product_id
    and prd.typeofmerchandise = 2
    and prd.productgroup_id = prdgr.productgroup_id
and ih.stockroom_id = sk.stockroom_id
and bu.businessunit_id = ih.forbusinessunit_id
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 a.routecontrol_id,
       rp.reportparam_id,
       c.customernumber,
       c.name customername,
       p.code product_code,
       (select description from product_link_desc pd where pd.product_link_id = a.product_id
           and pd.language_id = l.language_id) product_description,
       sd.code sizedefinition_code,
      (select description from sizedefinition_link_desc sd where sd.sizedefinition_link_id = a.sizedefinition_id
          and sd.language_id = l.language_id) sizedefinition_description,
       f.code fm,
       rc.drivingdate pickupdate,
       rc.drivingdate,
       a.soilticketnumber,
       a.currentqty,
       a.nullqty,
       a.missed,
       a.inventoryqty,
       b.pickupqty1,
       b.pickupqty2,
       b.pickupqty3,
       b.pickupqty4,
       b.pickupqty5,
       b.pickupqty6,
       b.pickupqty7,
       b.pickupqty8,
       b.pickupqty9,
       b.pickupqty10,
       b.pickupqty11,
       b.pickupqty12,
       b.pickupqty13,
       b.nr_of_columns,
       r.routenumber, r.route_id,
       a.stopnumber,
       l.code languagecode,
       (select min(plpc.billingmethod)
          from productlistpercustomer plpc
         where plpc.customer_id = a.customer_id
           and plpc.product_id = a.product_id
           and plpc.sizedefinition_id = a.sizedefinition_id
           and sysdate between plpc.dateactive and plpc.dateinactive) billingmethod
from  v_soilreasonability_curr a
      left outer join v_soilreasonability_hist b on a.reportparam_id = b.reportparam_id and
                                                    a.routecontrol_id = b.routecontrol_id and
                                                    a.customer_id = b.customer_id and
                                                    a.product_id = b.product_id and
                                                    a.sizedefinition_id = b.sizedefinition_id and
                                                    a.finishingmethod_id = b.finishingmethod_id,
      routecontrol rc,
      route r,
      customer c,
      product p,
      sizedefinition sd,
      finishingmethod f,
      languages l, reportparam rp
where a.routecontrol_id = rc.routecontrol_id
  and a.reportparam_id = rp.reportparam_id
  and rc.route_id = r.route_id
  and a.customer_id = c.customer_id
  and a.product_id = p.product_id
  and a.sizedefinition_id = sd.sizedefinition_id
  and a.finishingmethod_id = f.finishingmethod_id
  and r.route_id = rc.route_id
  and rp.number_value = rc.routecontrol_id
order by c.customernumber, p.code, sd.code, f.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_STATEMENTHEADER_AMM_CSV
 (STATEMENTDATE, STATEMENTNUMBER, 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
, BILLTOCUSTOMER_LINK_ID, 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, BILLTO_CHAIN, CUSTDELIVERYSCHEME, PLANTPHONENO, PLANTFAX, PLANTEMAIL, NETPAYMENTDAYS, COMPANYCODE, BILL_LANGUAGE_CODE
, PLANTCOMPANYADDRESS, PLANTCOMPANYSTREET, PLANTCOMPANYSTREET2, PLANTCOMPANYCITY, PLANTCOMPANYSTATE, PLANTCOMPANYZIP, PLANTCOMPANYNAME, PLANTCOMPANYPHONE, BILLTO_LEGACYNUMBER, PAYMENTHISTORY, FINANCECHARGE, PAYMENTTERMSCODE, STATEMENTPERDELIVERTO, PAYBYCUSTOMERNUMBER, PAYBYCUSTOMERNAME)
as SELECT A.INVOICEDATE STATEMENTDATE,
       A.INVOICENUMBER STATEMENTNUMBER,
       BU.CODE INVOICEBUSINESSUNITCODE,
       BU.DESCRIPTION INVOICEBUSINESSUNITDESC,
       A.BILLTOCUSTOMERNUMBER,
       A.BILLTOCUSTOMERNAME,
       A.DELTOCUSTOMERNUMBER,
       A.DELTOCUSTOMERNAME,
       A.STARTWEEK,
       A.ENDWEEK,
       A.STARTMONTH,
       A.ENDMONTH,
       A.STARTYEAR,
       A.ENDYEAR,
       BTCA.CITY,
       BTCA.COUNTY,
       BTCA.STATE,
       BTCA.ZIPCODE,
       BTCA.STREET2,
       BTCA.STREET,
       A.CONTACTPERSONNAME,
       A.CONTACTPERSONPHONE,
       A.EMAILSTATUS,
       A.EMAILADDRESS,
       A.REALCOLLECTIONTYPE,
       A.ORIGINALCOLLECTIONTYPE,
       A.EXPORTED,
       A.INVOICECOMMENTS STATEMENTCOMMENTS,
       A.PREBILLAMOUNT,
       A.INVOICEFREQUENCY_ID STATEMENTFREQUENCYNUMBER,
       CUR.CODE CURRENCYCODE,
       CUR.DESCRIPTION CURRENCYDESC,
       A.BILLTOCUSTOMER_LINK_ID,
       S.STATUSTYPE,
       S.CODE STATUSCODE,
       S.FACTORYDESCRIPTION STATUSFACTORYDESCRIPTION,
       IHU.COUNTYTAXRATE,
       IHU.CITYTAXRATE,
       IHU.STATESTAXRATE,
       P.CODE PLANTCODE,
       P.NAME PLANTNAME,
       PA.STREET PLANTSTREET,
       PA.STREET2 PLANTSTREET2,
       PA.ZIPCODE PLANTZIPCODE,
       PA.CITY PLANTCITY,
       PA.STATE PLANTSTATE,
       PA.COUNTY PLANTCOUNTY,
       A.PURCHASEORDER,
       A.ROUTENUMBER,
       A.SYSTEMUSER_ID,
       A.TIMESTAMP,
       A.INVOICEHEADER_ID STATEMENTHEADER_ID,
       F_GETARAGINGAMOUNT(A.BILLTOCUSTOMER_LINK_ID,
                          3,
                          0,
                          null,
                          null,
                          null,
                          null) DAYS0,
       F_GETARAGINGAMOUNT(A.BILLTOCUSTOMER_LINK_ID,
                          3,
                          1,
                          null,
                          null,
                          null,
                          null) DAYS30,
       F_GETARAGINGAMOUNT(A.BILLTOCUSTOMER_LINK_ID,
                          3,
                          2,
                          null,
                          null,
                          null,
                          null) DAYS60,
       F_GETARAGINGAMOUNT(A.BILLTOCUSTOMER_LINK_ID,
                          3,
                          3,
                          null,
                          null,
                          null,
                          null) DAYS90,
       F_GETARAGINGAMOUNT(A.BILLTOCUSTOMER_LINK_ID,
                          3,
                          4,
                          null,
                          null,
                          null,
                          null) DAYS120,
       F_PREVIOUSSTATEMENT(A.INVOICEDATE,
                           A.BILLTOCUSTOMERNUMBER,
                           A.DELTOCUSTOMERNUMBER) PREVIOUSBALANCE,
       (SELECT FL.CODE
          FROM CUSTOMERBILLINGINFO CBI, FORMLAYOUT FL
         WHERE FL.FORMLAYOUT_ID = CBI.STATEMENTLAYOUT_ID
           AND CBI.CUSTOMER_ID = A.BILLTOCUSTOMER_LINK_ID) STATEMENTLAYOUTCODE,
       (SELECT CODE FROM CHAIN WHERE CHAIN_ID = BTC.CHAIN_ID) BILLTO_CHAIN,
       CAST(FSGET_CUST_DELIVERY_DAYS(A.BILLTOCUSTOMER_LINK_ID) AS
            VARCHAR2(7)) CUSTDELIVERYSCHEME,
       P.PHONENO PLANTPHONENO,
       P.FAXNO PLANTFAX,
       P.EMAIL PLANTEMAIL,
       A.NETPAYMENTDAYS,
       (SELECT MAX(SS.VALUE)
          FROM SYSTEMSETTING SS
         WHERE P.PLANT_ID = SS.PLANT_ID
           AND SS.NAME = 'COMPANYCODE') COMPANYCODE,
       (SELECT CODE FROM LANGUAGES WHERE LANGUAGE_ID = BTC.LANGUAGE_ID) BILL_LANGUAGE_CODE,
       ' ' PLANTCOMPANYADDRESS,
(SELECT ad.street from Plantcompany pc, address ad where pc.plant_id = p.plant_id and pc.address_id = ad.address_id and pc.active = 'Y' and pc.code in (select min(pc2.code) from Plantcompany pc2 where pc2.plant_id = p.plant_id and pc2.active = 'Y')) PlantCompanyStreet,
(SELECT ad.street2 from Plantcompany pc, address ad where pc.plant_id = p.plant_id and pc.address_id = ad.address_id and pc.active = 'Y' and pc.code in (select min(pc2.code) from Plantcompany pc2 where pc2.plant_id = p.plant_id and pc2.active = 'Y')) PlantCompanyStreet2,
(SELECT ad.city from Plantcompany pc, address ad where pc.plant_id = p.plant_id and pc.address_id = ad.address_id and pc.active = 'Y' and pc.code in (select min(pc2.code) from Plantcompany pc2 where pc2.plant_id = p.plant_id and pc2.active = 'Y')) PlantCompanyCity,
(SELECT ad.state from Plantcompany pc, address ad where pc.plant_id = p.plant_id and pc.address_id = ad.address_id and pc.active = 'Y' and pc.code in (select min(pc2.code) from Plantcompany pc2 where pc2.plant_id = p.plant_id and pc2.active = 'Y')) PlantCompanyState,
(SELECT ad.zipcode from Plantcompany pc, address ad where pc.plant_id = p.plant_id and pc.address_id = ad.address_id and pc.active = 'Y' and pc.code in (select min(pc2.code) from Plantcompany pc2 where pc2.plant_id = p.plant_id and pc2.active = 'Y')) PlantCompanyZip,
(SELECT pc.name from Plantcompany pc where pc.plant_id = p.plant_id and pc.active = 'Y' and pc.code in (select min(pc2.code) from Plantcompany pc2 where pc2.plant_id = p.plant_id and pc2.active = 'Y')) PlantCompanyName,
(SELECT CASE WHEN p.code = 'B01' then '612-362-0311'
ELSE pc.phone END from Plantcompany pc where pc.plant_id = p.plant_id and pc.active = 'Y' and pc.code in (select min(pc2.code) from Plantcompany pc2 where pc2.plant_id = p.plant_id and pc2.active = 'Y')) PlantCompanyPhone,
       BTC.LEGACYCUSTOMERNUMBER as BILLTO_LEGACYNUMBER,
       (SELECT max(1)
          FROM V_STATEMENT_PAYMENTHISTORY_AMM V
         WHERE V.BILLTOCUSTOMER_LINK_ID = A.BILLTOCUSTOMER_LINK_ID
           AND V.ARTRANSACTIONDATE <= A.INVOICEDATE) PAYMENTHISTORY,
       (SELECT SUM(SML.AMOUNT)
          FROM STATEMENTLINE SML
         WHERE SML.INVOICEHEADER_ID=A.INVOICEHEADER_ID
           AND SML.INVOICELINETYPE_ID=13) FINANCECHARGE,
       (SELECT pt.code
          FROM customerbillinginfo cbi, paymentterms pt
         WHERE a.billtocustomer_link_id = cbi.customer_id
           AND cbi.paymentterms_id = pt.paymentterms_id) paymenttermsCode,
       CASE WHEN A.DELTOCUSTOMER_LINK_ID IS NOT NULL /* HVH 30/10/2008 Added Y/N to indicate statement is for del-to*/
        THEN 'Y'
        ELSE 'N'
       END STATEMENTPERDELIVERTO,
       pay.customernumber PAYBYCUSTOMERNUMBER,
       pay.name PAYBYCUSTOMERNAME
FROM INVOICEHEADER A
inner join INVOICEHEADEREXTRAINFO IHE on IHE.INVOICEHEADER_ID = A.INVOICEHEADER_ID
inner join CURRENCY CUR on CUR.CURRENCY_ID = A.CURRENCY_ID
inner join STATUS S on S.STATUS_ID = A.STATUS_ID
inner join BUSINESSUNIT BU on BU.BUSINESSUNIT_ID = A.INVOICEBUSINESSUNIT_ID
inner join PLANT P on P.PLANT_ID = BU.PLANT_ID
inner join CUSTOMER BTC on BTC.CUSTOMER_ID = A.BILLTOCUSTOMER_LINK_ID
inner join ADDRESS BTCA on BTCA.ADDRESS_ID = BTC.INVOICEADDRESS_ID
inner join ADDRESS PA on PA.ADDRESS_ID = P.ADDRESS_ID
LEFT OUTER JOIN INVOICEHEADERUS IHU ON IHU.INVOICEHEADER_ID = A.INVOICEHEADER_ID
LEFT OUTER JOIN customer pay ON pay.customer_id = ihe.paybycustomer_link_id
WHERE A.DOCUMENTTYPE = 2

/
create or replace view V_STATEMENTHEADER_AUJ
 (STATEMENTDATE, STATEMENTNUMBER, 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, BILLTO_CHAIN, CUSTDELIVERYSCHEME, REPORTPARAM_ID, COPY_NUMBER, PLANTPHONENO, PLANTFAX, PLANTEMAIL, NETPAYMENTDAYS, PAYMENTTERMSDUEDATE
, MAX_INVOICEDATE, NROFINVOICES, LANGUAGE_PLANT, SALESAREA_CODE)
as select a.enddate statementdate, a.invoicenumber statementnumber, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
a.billtocustomernumber, a.billtocustomername, a.deltocustomernumber, a.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.contactpersonname, a.contactpersonphone,
a.emailstatus, a.emailaddress, a.realcollectiontype, a.originalcollectiontype, a.exported,
a.invoicecomments statementcomments, a.prebillamount, a.invoicefrequency_id statementfrequencynumber,
b.code currencycode, b.description currencydesc,
s.statustype, s.code statuscode, s.factorydescription statusfactorydescription,
c.countytaxrate, c.citytaxrate, c.statestaxrate,
p.code plantcode, p.name plantname, x.street plantstreet,x.street2 plantstreet2, x.zipcode plantzipcode,
x.city plantcity, x.state plantstate, x.county plantcounty, a.purchaseorder, a.routenumber,
a.systemuser_id, a.timestamp, a.invoiceheader_id statementheader_id,
F_GetArAgingAmount(a.billtocustomer_link_id, reportparam.number_value2, 0, getdateasvarcharfixedformat(reportparam.date_value1), getdateasvarcharfixedformat(reportparam.date_value2), getdateasvarcharfixedformat(reportparam.date_value3), getdateasvarcharfixedformat(reportparam.date_value4), null, a.invoiceheader_id) days0,
F_GetArAgingAmount(a.billtocustomer_link_id, reportparam.number_value2, 1, getdateasvarcharfixedformat(reportparam.date_value1), getdateasvarcharfixedformat(reportparam.date_value2), getdateasvarcharfixedformat(reportparam.date_value3), getdateasvarcharfixedformat(reportparam.date_value4), null, a.invoiceheader_id) days30,
F_GetArAgingAmount(a.billtocustomer_link_id, reportparam.number_value2, 2, getdateasvarcharfixedformat(reportparam.date_value1), getdateasvarcharfixedformat(reportparam.date_value2), getdateasvarcharfixedformat(reportparam.date_value3), getdateasvarcharfixedformat(reportparam.date_value4), null, a.invoiceheader_id)  days60,
F_GetArAgingAmount(a.billtocustomer_link_id, reportparam.number_value2, 3, getdateasvarcharfixedformat(reportparam.date_value1), getdateasvarcharfixedformat(reportparam.date_value2), getdateasvarcharfixedformat(reportparam.date_value3), getdateasvarcharfixedformat(reportparam.date_value4), null, a.invoiceheader_id)  days90,
F_GetArAgingAmount(a.billtocustomer_link_id, reportparam.number_value2, 4, getdateasvarcharfixedformat(reportparam.date_value1), getdateasvarcharfixedformat(reportparam.date_value2), getdateasvarcharfixedformat(reportparam.date_value3), getdateasvarcharfixedformat(reportparam.date_value4), null, a.invoiceheader_id)  days120,
F_PreviousStatement(a.invoicedate, a.billtocustomernumber, a.deltocustomernumber) previousbalance,
ihe.formlayoutcode statementlayoutcode,
(select chain.code
        from chain, customer
        where chain.chain_id = customer.chain_id and
              customer.customer_id = a.billtocustomer_link_id) billto_chain
, cast(fsget_cust_delivery_days(a.billtocustomer_link_id) as varchar2(7)) custdeliveryscheme
, reportparam.reportparam_id, reportparam.copy_number
, p.phoneno plantphoneno, p.faxno plantfax, p.email plantemail, a.netpaymentdays
, ihe.paymenttermsduedate
, (select max(v.invoicedate) from V_StatementLine_AUJ v where v.statementheader_id = a.invoiceheader_id ) Max_InvoiceDate
, (select count(1) from V_StatementInvoices_AUJ vsi where vsi.statementheader_id = a.invoiceheader_id) NrOfInvoices
, (select lan.code from languages lan where lan.language_id = p.language_id) language_plant
, (select sa.code from salesarea sa, customer bil where bil.customer_id = a.billtocustomer_link_id
          and sa.salesarea_id = bil.salesarea_id) salesarea_code
from invoiceheader a
left outer join invoiceheaderus c on (a.invoiceheader_id = c.invoiceheader_id)
, currency b, businessunit e, status s, plant p, address x
, invoiceheaderextrainfo ihe
, reportparam
where a.currency_id = b.currency_id
and a.documenttype = 2
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 a.invoiceheader_id = ihe.invoiceheader_id
and reportparam.number_value = a.invoicenumber
and reportparam.copy_number = 0

/
create or replace view V_STDDDELIVERYANDSTOCK_ANG
 (CUSTOMERNUMBER, NAME, CUSTOMERLANGUAGECODE, DEPARTMENTNUMBER, DESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESC, DELIVERYPOINTCODE, DELIVERYPOINTDESC, PRODUCTCODE, PRODUCTGROUPCODE, PRODUCTDESC, SIZEDESC, SIZECODE, FINISHINGMETHODCODE, DELIVERYSCHEMECODE, SEASONCODE, SEASONDESC, DAYNUMBER, AMOUNT, STOCK_DAYNUMBER, STOCK_AMOUNT, 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)
as SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, W.CODE CUSTOMERLANGUAGECODE, DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION,
  DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION distributionpointdesc,
  DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESC, PRODUCT.CODE productcode,
  Z.CODE productgroupcode,
  (select DESCRIPTION from PRODUCT_DESC a where a.product_id = PRODUCTLISTPERDISTRIBPOINT.PRODUCT_ID and a.language_id = LG.language_id) productdesc,
  (select sdd.DESCRIPTION from SIZEDEFINITION_DESC sdd where PRODUCTLISTPERDISTRIBPOINT.SIZEDEFINITION_ID = sdd.SIZEDEFINITION_ID and LG.LANGUAGE_ID = sdd.LANGUAGE_ID) SIZEDESC,
  (select sd.code from SIZEDEFINITION sd where PRODUCTLISTPERDISTRIBPOINT.SIZEDEFINITION_ID = sd.SIZEDEFINITION_ID) SIZECODE,
  FINISHINGMETHOD.CODE finishingmethodcode,
  Y.CODE deliveryschemecode,
  X.code SEASONCODE,
  (select DESCRIPTION from SEASONTYPE_DESC ST where X.SEASONTYPE_ID=ST.SEASONTYPE_ID and ST.language_id = LG.language_id) SEASONDESC,
  D1.DAYNUMBER, STANDARDDELIVERYAMOUNT.AMOUNT,
  NS_AMOUNT.STOCK_DAYNUMBER, NS_AMOUNT.STOCK_AMOUNT,
  PRODUCTLISTPERDISTRIBPOINT.ORDERINGMETHOD, STANDARDDELIVERY.GENERATEZEROLINES, STANDARDDELIVERY.CLEANRETURN,
  STANDARDDELIVERY.DELIVERSTERILE, STANDARDDELIVERY.CORRECTSHORTAGES, STANDARDDELIVERY.CORRECTOVERDELIVERIES,
  STANDARDDELIVERY.NUMBEROFTRANSPORTARTICLES,
  DEPARTMENT.OCCUPANCY, CUSTOMER.STANDARDQTYDEFINITION,
  (select DESCRIPTION from TRANSPORTARTICLE_DESC D where D.TRANSPORTARTICLE_ID= STANDARDDELIVERY.TRANSPORTARTICLE_ID and D.language_id = LG.language_id) TRANSPORTARTICLE_DESC,
  STANDARDDELIVERYLINE.DATEACTIVE, STANDARDDELIVERYLINE.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
FROM CUSTOMER, LANGUAGES W, DEPARTMENT, DISTRIBUTIONPOINT, DELIVERYPOINT, businessunit bu,
  PRODUCT
    left outer join PRODUCTGROUP Z ON (PRODUCT.PRODUCTGROUP_ID = Z.PRODUCTGROUP_ID),
  FINISHINGMETHOD,
  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),
  PRODUCTLISTPERDISTRIBPOINT
    left outer 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(PRODUCTLISTPERDISTRIBPOINT.PRODUCTLISTPERDISTRIBPOINT_ID = NS_AMOUNT.PRODUCTLISTPERDISTRIBPOINT_ID),
  STANDARDDELIVERY,
  STANDARDDELIVERYAMOUNT, DAY D1,
  LANGUAGES LG, reportparam rp
WHERE STANDARDDELIVERY.STANDARDDELIVERY_ID = STANDARDDELIVERYLINE.STANDARDDELIVERY_ID
  AND STANDARDDELIVERYAMOUNT.DAY_ID=D1.DAY_ID
  AND STANDARDDELIVERYLINE.STANDARDDELIVERYLINE_ID = STANDARDDELIVERYAMOUNT.STANDARDDELIVERYLINE_ID
  AND STANDARDDELIVERYLINE.PRODUCTLISTPERDISTRIBPOINT_ID = PRODUCTLISTPERDISTRIBPOINT.PRODUCTLISTPERDISTRIBPOINT_ID
  and PRODUCTLISTPERDISTRIBPOINT.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
  AND DISTRIBUTIONPOINT.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  and DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
  and DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  and CUSTOMER.LANGUAGE_ID = W.LANGUAGE_ID
  and PRODUCTLISTPERDISTRIBPOINT.PRODUCT_ID = PRODUCT.PRODUCT_ID
  and PRODUCTLISTPERDISTRIBPOINT.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
  and exists (select v.customer_id from v_customersperbusinessunitdp v
              where v.customer_id = CUSTOMER.customer_id and v.businessunit_id = bu.businessunit_id)

/
create or replace view V_STDELIVAGREEMENTS
 (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, PRICE, DATEACTIVE, DATEINACTIVE, PREVIOUSDELIVERYDATE
, CUSTOMER_ID, NEXTDELIVERYDATE)
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
, pack_price.Wash_Price(customer.customer_id, product.product_id, SIZEDEFINITION.Sizedefinition_Id, finishingmethod.finishingmethod_id, GETCURRENTDATE()) Price
, STANDARDDELIVERYLINE.Dateactive, STANDARDDELIVERYLINE.Dateinactive
, case when STANDARDDELIVERYLINE.Dateactive > GETCURRENTDATE() then to_date('2099/12/31', 'yyyy/mm/dd')
else (select max(dh.DeliveryDate) from DeliveryHistory dh where dh.customer_link_id = customer.customer_id and dh.department_link_id=department.department_id and dh.distributionpoint_link_id=distributionpoint.distributionpoint_id
  and dh.product_link_id=product.product_id and dh.sizedefinition_link_id=SIZEDEFINITION.Sizedefinition_Id and dh.finishingmethod_id=finishingmethod.finishingmethod_id and dh.amountstandard > 0 and dh.deliverydate <= GETCURRENTDATE())
  end PreviousDeliveryDate
, CUSTOMER.CUSTOMER_ID
, case when STANDARDDELIVERYLINE.Dateinactive < GETCURRENTDATE() then to_date('2099/12/31', 'yyyy/mm/dd')
 when STANDARDDELIVERYLINE.Dateactive > GETCURRENTDATE() then F_getnextdeliverydate(STANDARDDELIVERYLINE.Dateactive, CUSTOMER.Customer_Id, PRODUCT.Typeofmerchandise, standarddeliveryline.deliveryscheme_id)
 when STANDARDDELIVERYLINE.Dateinactive < F_getnextdeliverydate(GETCURRENTDATE(), CUSTOMER.Customer_Id, PRODUCT.Typeofmerchandise, standarddeliveryline.deliveryscheme_id) then to_date('2099/12/31', 'yyyy/mm/dd')
 else F_getnextdeliverydate(GETCURRENTDATE(), CUSTOMER.Customer_Id, PRODUCT.Typeofmerchandise, standarddeliveryline.deliveryscheme_id)
 end NextDeliveryDate
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_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, GETDATEONLY(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, 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, GETDATEONLY(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
, 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, DISTRIBPOINTDESC, DEPARTMENTCODE, CUSTOMERNUMBER, CUSTOMERNAME, DELIVEREDAMOUNT, BUSINESSUNIT_ID, PLANT_ID, INTERNALBU, LANGUAGECODE)
as select -- + INDEX(pn, XSPEEDPACKINGNOTE) INDEX(ro, XPKROUTE) INDEX(de, XPKDEPOT) TD26279
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,
  dip.description distribpointdesc,
  de.code departmentcode,
  cu.customernumber, cu.name customername,
  pnl.deliveredamount,
  bu.businessunit_id, bu.plant_id, internalbu.businessunit_id internalBU,
  l.code languagecode
from PackingNoteLine PNL
     inner join PackingNote PN
           inner join status st on st.status_id = pn.status_id
           inner join businessunit bu on bu.businessunit_id = pn.processbusinessunit_id
           inner join businessunit internalbu on internalbu.businessunit_id = pn.internalprocessingbu_id
           left outer join route ro
                 left outer join depot de on de.depot_id = ro.depot_id
           on ro.route_id = pn.route_id
           inner join plantdepartment pld on pld.plantdepartment_id = pn.plantdepartment_id
           inner join distributionpoint dip
                 inner join department dp
                       inner join customer cu on cu.customer_id = dp.customer_id
                 on dp.department_id = dip.department_id
           on dip.distributionpoint_id = pn.distributionpoint_id
     on pn.packingnote_id = pnl.packingnote_id
     inner join product pr
           inner join productgroup pg on pr.productgroup_id = pg.productgroup_id
     on pr.product_id = pnl.product_id
     inner join sizedefinition sz on  sz.sizedefinition_id = pnl.sizedefinition_id
     inner join finishingmethod fm on fm.finishingmethod_id = pnl.finishingmethod_id
, 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 --in case depot is null
  and st.code = '30' -- processed
  and pn.origin <> 6 --TD21371 exclude Bulk Notes

/
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_THWEIGHTCOMPARISON_ANG
 (CUSTOMERNUMBER, CUSTOMER_LINK_ID, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESC, WEIGHINGCATCODE, WEIGHINGCATDESC, CLEANWEIGHT, SOILWEIGHT, PRODUCTCODE, PRODUCTDESC, SIZECODE, FINISHINGMETHOD_ID, THEORETICALWEIGHT, AMOUNTDELIVERED, CALCULATEDWEIGHT, WEIGHINGDATE, DELIVERYDATE, ORIGINALDELIVERYDATE, SYSTEMSETTINGVALUE, PLANTCODE, PLANTNAME, DELIVERYHISTORY_ID, WEIGHINGHISTORY_ID, WEIGHINGCATEGORY_ID, DEPARTMENT_LINK_ID, LANGUAGECODE, BU_CODE, BU_DESC)
as select
  vTh.customernumber, vTh.customer_link_id, vTh.customerName , vTh.departmentnumber, vTh.departmentDesc
, vTh.WeighingCatCode
, (select weighingcategory_desc.description from weighingcategory_desc where weighingcategory_desc.weighingcategory_id = vTh.weighingcategory_id
   and weighingcategory_desc.language_id = languages.language_id) WeighingCatDesc
, coalesce(vTh.cleanweight, 0) cleanweight, coalesce(vTh.soilweight, 0) soilweight
, 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
, dh.finishingmethod_id
, coalesce(productsize.theoreticalweight, 0) theoreticalweight, coalesce(dh.amountdelivered, 0) amountdelivered
, coalesce((productsize.theoreticalweight * coalesce(dh.amountdelivered,0)),0) CalculatedWeight
, vTh.weighingdate, coalesce(dh.deliverydate, vTh.weighingdate) deliverydate, dh.deliverydate originalDeliveryDate
, cast(systemsetting.value as numeric) systemsettingValue
, plant.code PlantCode, plant.name PlantName
, dh.deliveryhistory_id , vTh.weighinghistory_id, vTh.weighingcategory_id, vTh.department_link_id
, languages.code LanguageCode
, bu.code Bu_code, bu.description Bu_desc
from
  v_theoreticalweight_aux_ang vTh
      left outer join
            (
              deliveryhistory dh
                 join
                      ( product prd
                                join
                                  ( productsize join sizedefinition sz
                                                 on sz.sizedefinition_id = productsize.sizedefinition_id
                                                    )
                                 on prd.product_id = productsize.product_id )
                          on prd.product_id = dh.product_link_id
             )
            on vTh.customer_link_id = dh.customer_link_id
                 and vTh.department_link_id = dh.department_link_id
                    and vTh.distributionpoint_link_id = dh.distributionpoint_link_id
                         and vTh.weighingcategory_id = prd.weighingcategory_id
                            -- and vTh.weighingdate = dh.deliverydate
                               and vTh.processbusinessunit_id = dh.processbusinessunit_id
                                 -- and (dh.packindication = 1 or dh.packindication = 2)
, plant, systemsetting
, languages
, businessunit bu
where
    plant.plant_id = systemsetting.plant_id
and systemsetting.name = 'WEIGHTDECIMALSMANUALINPUT'
and dh.sizedefinition_link_id = sz.sizedefinition_id
and (dh.packindication = 1 or dh.packindication = 3)--502125
and vth.WeighingCatCode<>'90009'
and bu.businessunit_id = dh.processbusinessunit_id
and bu.plant_id = plant.plant_id
union all
select
 vTh.customernumber, vTh.customer_link_id, vTh.customerName , vTh.departmentnumber, vTh.departmentDesc
, vTh.WeighingCatCode
, (select weighingcategory_desc.description from weighingcategory_desc where weighingcategory_desc.weighingcategory_id = vTh.weighingcategory_id
   and weighingcategory_desc.language_id = languages.language_id) WeighingCatDesc
, coalesce(vTh.cleanweight, 0) cleanweight, coalesce(vTh.soilweight, 0) soilweight
, null ProductCode
, null ProductDesc
, null SizeCode
, null finishingmethod_id
, null theoreticalweight, null amountdelivered, null CalculatedWeight
, vTh.weighingdate,  vTh.weighingdate deliverydate,  vTh.weighingdate originalDeliveryDate
, cast(systemsetting.value as numeric) systemsettingValue
, plant.code PlantCode, plant.name PlantName
, null, vTh.weighinghistory_id, vTh.weighingcategory_id, vTh.department_link_id
, languages.code LanguageCode
, bu.code Bu_code, bu.description Bu_desc
from
  v_theoreticalweight_aux_ang vTh
  ,plant, systemsetting
  ,languages, customer c, department_link d, businessunit bu
where
vth.customernumber=c.customernumber
and vth.department_link_id=d.department_link_id
and vth.processbusinessunit_id=bu.businessunit_id
and bu.plant_id=plant.plant_id
and  plant.plant_id = systemsetting.plant_id
and systemsetting.name = 'WEIGHTDECIMALSMANUALINPUT'
and vth.WeighingCatCode='90009'

/
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, 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(*) 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.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
, prd.packingsequence, prd.product_id, prd.code productCode, sz.code sizeCode, fm.finishingmethod_id, 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
, (   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 GETDATEONLY(cds.outscantimestamp) = GETDATEONLY(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 GETDATEONLY(cds.outscantimestamp) = GETDATEONLY(ris.scantimestamp)
          and ris.transactiontype_id = 2 and flag_desc.language_id = languages.language_id )
else null
end 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 GETCURRENTDATE() 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
, (SELECT plpc.customcode FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cu.customer_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 (cu.customer_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc
, cds.uniqueresidentialitem_link_id, GETDATEONLY(cds.outscantimestamp) outscantimestamp/* Added 10-06-09 ROP */
, 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/* end of additions 10-06-09 ROP */
,(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
, wd.department_id webuserdepartment_id
, wus.websession_id
, wuc.webuser_id
--, plpc.product_id
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 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
, customerresidentialsettings crs, businessunit bu, systemsetting ss
, languages
, webusercustomer wuc
    left outer join webuserdepartment wd on (wuc.webusercustomer_id = wd.webusercustomer_id)
,  webusersession wus
--,  productlistpercustomer plpc
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.processbusinessunit_id = bu.businessunit_id
    and bu.plant_id = ss.plant_id
        AND ss.name = 'BATCHCODEUSAGE'
and cu.currency_id = crr.currency_id
and cu.customer_id = wuc.customer_id
and wuc.customer_id = wus.customer_id
--and prd.product_id = plpc.product_id
and (prd.typeofmerchandise = 5 or prd.typeofmerchandise = 1)

/
create or replace view V_WEBCLIENTDELIVERYNOTE_LTS
 (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, CLIENTSEARCHNAME, GENDER, ROOM, STREET, ZIPCODE_CITY, CLIENTDELIVERYNOTENUMBER, CLOSINGDATE, DELIVERYDATE, BOXNUMBER, BATCHCODE
, BATCHNUMBER, BATCHYEAR, BATCHWEEK, BATCHCOLORDESC, BATCH_CODENUMBER, DAYDESC, ROUTENUMBER, ROUTEDESC, STOPNUMBER, GROSSWEIGHT, WEIGHTDECIMALS, TAREWEIGHT, WEIGHTUNIT, PACKINGSEQUENCE, PRODUCT_ID, PRODUCTCODE, SIZECODE, FINISHINGMETHOD_ID, FINISHINGMETHODCODE, FINISHINGMETHODDESC, PRODUCTDESC, QTYRECEIVED, QTYDELIVERED, FLAGCODE, FLAGDESC, PRINT_V_CDN_OUTSCANNEDID, CUSTOMERCLIENTS, PRINTIDCODE, PRINTLATEPIECES, ACCEPTOTHERCLIENTS, PRINTQTYRECEIVED, SYSTEMSETTINGVALUE
, EMPLOYEENUMBER, EMPLOYEENAME, RECORDEMPLCLIENTDELNOTE, LANGUAGECODE, PRODCUSTOM_CODE, PRODCUSTOM_DESC, SEQUENCENUMBER, DEPTDELSTREET, DEPTDELZIPCODE, DEPTDELCITY, BU_DESC, PLANTCODE, PLANTNAME, PLANT_STREET, PLANT_ZIP, PLANT_CITY, PLANT_PHONE, PLANT_FAX, PLANT_EMAIL, PLANT_WEB, ROUTEDRIVINGDAYDESC, ACTIVITY_CODE_PRODUCT, ACTIVITY_DESC_PRODUCT, VATNUMBER, CREATIONDATE, BATCHDAY_ID, REGUNIT, CLIENTREMARK, LABELLAYOUTCODE, WEIGHTCATEGCODE, WEIGHTCATEGDESC, YEAR, WEEK
, WEBUSERDEPARTMENT_ID, WEBSESSION_ID, WEBUSER_ID)
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.department_id, de.departmentnumber, de.description departmentDesc
, client.clientnumber, coalesce(cdn.name, client.name) clientname, coalesce(client.searchname, cdn.name, client.name) clientsearchname
, client.gender
, 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, cdn.tareweight
, ( select systemsetting.value from systemsetting where systemsetting.plant_id = bu.plant_id and systemsetting.name = 'weightunit' ) weightunit
, prd.packingsequence, prd.product_id, prd.code productcode, sz.code sizecode, fm.finishingmethod_id, fm.code finishingmethodcode
, (select fd.description from finishingmethod_desc fd where fd.finishingmethod_id = fm.finishingmethod_id and fd.language_id = languages.language_id) finishingmethoddesc
, ( 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
, null flagcode, null flagdesc
, ( select count(*) from v_cdn_outscannedids_lts vo where vo.clientdeliverynote_id = cdn.clientdeliverynote_id ) print_v_cdn_outscannedid
, 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, 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 (cu.customer_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) prodcustom_desc
, 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/* end of additions 10-06-09 rop */
, bu.description bu_desc
, pla.code plantcode, pla.name plantname
, (select adr.street from address adr where pla.address_id = adr.address_id) plant_street
, (select adr.zipcode from address adr where pla.address_id = adr.address_id) plant_zip
, (select adr.city from address adr where pla.address_id = adr.address_id) plant_city
, pla.phoneno plant_phone
, pla.faxno plant_fax
, pla.email plant_email
, pla.website plant_web
, (select dd.description from day_desc dd where dd.day_id = route.drivingday_id and dd.language_id = languages.language_id) routedrivingdaydesc
, (select ac.code from productgroup pg, activity ac where pg.activity_id = ac.activity_id and prd.productgroup_id = pg.productgroup_id) activity_code_product
, (select acd.description from productgroup pg, activity_desc acd where pg.activity_id = acd.activity_id and prd.productgroup_id = pg.productgroup_id and acd.language_id = languages.language_id) activity_desc_product
, bu.vatnumber, cdn.creationdate, batch.day_id batchday_id
, (select rgd.description
         from   registrationunit_desc rgd
         where  rgd.registrationunit_id = prd.registrationunit_id and rgd.language_id = languages.language_id) regunit
, client.remark clientremark
, (select fl.code from formlayout fl where fl.formlayout_id = crs.clientdelnoteformlayout_id) labellayoutcode
, (select we.code from weighingcategory we where we.weighingcategory_id = cdn.weighingcategory_link_id) weightcategcode
, (select wed.description from weighingcategory_desc wed where wed.weighingcategory_id = cdn.weighingcategory_link_id and wed.language_id = languages.language_id) weightcategdesc
, batch.year, batch.week
, 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
      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
      ) 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
, customerresidentialsettings crs, businessunit bu, systemsetting ss, plant pla
, languages
, webusercustomer wuc
    left outer join webuserdepartment wd on (wuc.webusercustomer_id = wd.webusercustomer_id)
,  webusersession wus
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.processbusinessunit_id = bu.businessunit_id
    and bu.plant_id = pla.plant_id
    and bu.plant_id = ss.plant_id
        and ss.name = 'BATCHCODEUSAGE'
and cu.currency_id = crr.currency_id
  and ((cdl.qtyscannedin + cdl.qtycountedin+ cdl.qtyscannedout+cdl.qtycountedout) <> 0 or nvl(cdn.grossweight,0) > 0)
and cu.customer_id = wuc.customer_id
and wuc.customer_id = wus.customer_id

/
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
, (select crr.invoiceamountdecimals from currency crr where cus.currency_id=crr.currency_id) invoiceamountdecimals
, (select crr.decimals from currency crr where cus.currency_id=crr.currency_id) pricedecimals
, cdn.closingdate--, cbi.residentialservicesallowed
, 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--SUM(ctx.TAXAMOUNT) 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
     join invoiceheader ih on (ih.invoiceheader_id=il.invoiceheader_id)
on cdl.invoiceline_id=il.invoiceline_id
, client cli --left outer join clientbillinginfo cbi on cbi.client_id = cli.client_id
left outer join clientresident cr on cli.client_id=cr.client_id
, v_ClientDepartment v
, address a, customer cus
left outer join Customerresidentialsettings crs on cus.customer_id=crs.customer_id
, clientdeliverynote cdn
  left outer join invoiceline ilh
       join invoiceheader ihh on (ihh.invoiceheader_id = ilh.invoiceheader_id)
  on cdn.invoiceline_id = ilh.invoiceline_id
  left outer join clientdeliverynotetax ctx
       join taxgroup txg on (ctx.taxgroup_id = txg.taxgroup_id)
  ON ctx.CLIENTDELIVERINOTE_ID = cdn.ClientDeliveryNote_ID
, languages l
, product p, sizedefinition s, finishingmethod f,
webusercustomer wuc
    left outer join webuserdepartment wd on (wuc.webusercustomer_id = wd.webusercustomer_id),
  webusersession wus
where cdl.clientdeliverinote_id = cdn.clientdeliverynote_id
and cdn.customer_link_id = cus.customer_id
and cli.client_id = cdn.client_link_id
and cus.visitaddress_id = a.address_id
and cdl.product_link_id = p.product_id
and cdl.sizedefinition_link_id = s.sizedefinition_id
and cdl.finishingmethod_id = f.finishingmethod_id
and cli.client_id=v.client_id
and cdn.closingdate is not null
and cus.language_id=l.language_id
and cli.customer_id = wuc.customer_id
and wuc.customer_id = wus.customer_id
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
, (select crr.invoiceamountdecimals from currency crr where cus.currency_id=crr.currency_id) invoiceamountdecimals
, (select crr.decimals from currency crr where cus.currency_id=crr.currency_id) pricedecimals
, cdn.closingdate--, cbi.residentialservicesallowed
, 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--SUM(ctx.TAXAMOUNT) 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
, client cli --left outer join clientbillinginfo cbi on cbi.client_id = cli.client_id
left outer join clientresident cr on cli.client_id=cr.client_id
, v_ClientDepartment v
, address a, customer cus
left outer join Customerresidentialsettings crs on cus.customer_id=crs.customer_id
, clientdeliverynote cdn left outer join invoiceline ilh
       join invoiceheader ihh on (ihh.invoiceheader_id = ilh.invoiceheader_id)
  on cdn.invoiceline_id = ilh.invoiceline_id
  left outer join clientdeliverynotetax ctx
       join taxgroup txg on (ctx.taxgroup_id = txg.taxgroup_id)
  ON ctx.CLIENTDELIVERINOTE_ID = cdn.ClientDeliveryNote_ID
, languages l
, specialcharge sc
, webusercustomer wuc
    left outer join webuserdepartment wd on (wuc.webusercustomer_id = wd.webusercustomer_id)
, webusersession wus
where cdc.clientdeliverinote_id=cdn.clientdeliverynote_id
and cdn.customer_link_id=cus.customer_id
and cli.client_id=cdn.client_link_id
and cus.visitaddress_id=a.address_id
and cdc.specialcharge_id=sc.specialcharge_id
and cli.client_id=v.client_id
and cdn.closingdate is not null
and cus.language_id=l.language_id
and cli.customer_id = wuc.customer_id
and wuc.customer_id = wus.customer_id
and (cdn.invoicebusinessunit_id = cus.defaultbusinessunit_id or
     cdn.processbusinessunit_id = cus.defaultbusinessunit_id)
--and p.typeofmerchandise = 5
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
, (select crr.invoiceamountdecimals from currency crr where cus.currency_id=crr.currency_id) invoiceamountdecimals
, (select crr.decimals from currency crr where cus.currency_id=crr.currency_id) pricedecimals
, cdn.closingdate--, cbi.residentialservicesallowed
, 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--SUM(ctx.TAXAMOUNT) 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
     join invoiceheader ih on (ih.invoiceheader_id=il.invoiceheader_id)
  on cdn.invoiceline_id=il.invoiceline_id
  left outer join clientdeliverynotetax ctx
       join taxgroup txg on (ctx.taxgroup_id = txg.taxgroup_id)
  ON ctx.CLIENTDELIVERINOTE_ID = cdn.ClientDeliveryNote_ID
, client cli --left outer join clientbillinginfo cbi on cbi.client_id = cli.client_id
left outer join clientresident cr on cli.client_id=cr.client_id
, v_ClientDepartment v
, address a, customer cus
left outer join Customerresidentialsettings crs on cus.customer_id=crs.customer_id
, languages l
, weighingcategory wc
, webusercustomer wuc
    left outer join webuserdepartment wd on (wuc.webusercustomer_id = wd.webusercustomer_id)
, webusersession wus
where cdn.customer_link_id=cus.customer_id
and cli.client_id=cdn.client_link_id
and cus.visitaddress_id=a.address_id
and wc.weighingcategory_id=cdn.weighingcategory_link_id
and cli.client_id=v.client_id
and cdn.closingdate is not null
and cus.language_id=l.language_id
and cli.customer_id = wuc.customer_id
and wuc.customer_id = wus.customer_id
and (cdn.invoicebusinessunit_id = cus.defaultbusinessunit_id or
     cdn.processbusinessunit_id = cus.defaultbusinessunit_id)
--and p.typeofmerchandise = 5
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--, cbi.residentialservicesallowed
, 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
, '11' 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--SUM(ctx.TAXAMOUNT) 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
     join invoiceheader ih on (ih.invoiceheader_id=il.invoiceheader_id)
on pqr.invoiceline_id=il.invoiceline_id
, client cli --left outer join clientbillinginfo cbi on cbi.client_id = cli.client_id
left outer join clientresident cr on cli.client_id=cr.client_id
, v_ClientDepartment v
, address a, customer cus
left outer join Customerresidentialsettings crs on cus.customer_id=crs.customer_id
, currency crr
, clientdeliverynote cdn
  left outer join invoiceline ilh
       join invoiceheader ihh on (ihh.invoiceheader_id = ilh.invoiceheader_id)
  on cdn.invoiceline_id = ilh.invoiceline_id
  left outer join clientdeliverynotetax ctx
       join taxgroup txg on (ctx.taxgroup_id = txg.taxgroup_id)
  ON ctx.CLIENTDELIVERINOTE_ID = cdn.ClientDeliveryNote_ID
, languages l
, labellayout ll
, webusercustomer wuc
    left outer join webuserdepartment wd on (wuc.webusercustomer_id = wd.webusercustomer_id)
, webusersession wus
where pqr.clientdeliverynote_id=cdn.clientdeliverynote_id
and cdn.customer_link_id=cus.customer_id
and cli.client_id=cdn.client_link_id
and cus.visitaddress_id=a.address_id
and cus.currency_id=crr.currency_id
and pqr.labellayout_id=ll.labellayout_id
and cli.client_id=v.client_id
and cdn.closingdate is not null
and cus.language_id=l.language_id
and cli.customer_id = wuc.customer_id
and wuc.customer_id = wus.customer_id
and (cdn.invoicebusinessunit_id = cus.defaultbusinessunit_id or
     cdn.processbusinessunit_id = cus.defaultbusinessunit_id)
--and p.typeofmerchandise = 5
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--, cbi.residentialservicesallowed
, 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

/
create or replace view V_WEBCOSTSSPECPERCLIENT_LTS
 (LINE_TYPE, LABELLAYOUT_ID, L_INVOICELINE_ID, INVOICEHEADER_ID, L_INVOICENUMBER, L_DOCUMENTTYPE, H_INVOICELINE_ID, H_INVOICENUMBER, H_DOCUMENTTYPE, L_INVOICEDATE, H_INVOICEDATE, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, L_BILLSTREET, L_BILLCITY, L_BILLZIP, PURCHASEORDER, INVOICEFREQUENCYNUMBER, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, STARTWEEK, STARTMONTH, ENDWEEK, ENDMONTH, DELTOCUSTVATNUMBER, IHINVOICEBUSINESSUNIT_ID, CDNINVOICEBUSINESSUNIT_ID
, PROCESSBUSINESSUNIT_ID, CUSTOMER_ID, DELIVERYDATE, INVOICEAMOUNTDECIMALS, PRICEDECIMALS, CLOSINGDATE, CUSTOMERCLIENTS, LAUNDRYSERVICESPARTICIPANT, DEPARTMENTNUMBER, DEP_DESC, DEPARTMENT_ID, ROOMNUMBER, CLIENTDELIVERYNOTENUMBER, CLIENTNUMBER, SEARCHNAME, CLIENT_NAME, ADMINNUMBER, CLIENT_ID, CUSTOMER_NAME, CUSTOMERNUMBER, CITY, CUSTOMER_EXTRANAME, CUSTMER_STR, CUSTOMER_ZIP, CUSTOMER_COUNTRY, PROD_CODE, PROD_DESC, SIZEDEF_DESC, FINISH_DESC, QUANTITY, WEIGHTDECIMALS
, IL_PRICE, PRICE, LINEINVOICEBUSINESSUNIT_ID, LANGUAGE_CODE, SIZE_CODE, FINISHING_CODE, FMWASHTYPE, PRODUCT_ID, FINISHINGMETHOD_ID, TAXPERCENTAGE, TAXAMOUNT, TAXRATE, TAXGROUP_CODE, TAXGROUP_DESC, PNNUMBER, CLIENTINVOICECATEG, CLIENTFLAGCODE, WEIGHTCODE, CALCULATEDWEIGHT, WEIGHTPRICE, SPECIALPRICE, PLANTNAME, PLANTSTREET, PLANTZIP, PLANTCITY, PLANTPHONE, PLANTFAX, PLANTEMAIL, PLANTWEBSITE, CLIENT_REMARK, INVOICEPLANTCONTACT, INVOICELAYOUTCODE, BATCHDATE, CLIENTINVOICEDBASEDON
, 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.invoicedate l_invoicedate, ihh.invoicedate h_invoicedate
, ih.billtocustomernumber, ih.billtocustomername, ih.street l_billstreet, ih.city l_billcity, ih.zipcode l_billzip, ih.purchaseorder
, ih.invoicefrequency_id invoicefrequencynumber, ih.nextperiodstartdate, ih.nextperiodenddate, ih.nextperiodstartweek, ih.nextperiodendweek, ih.startweek, ih.startmonth, ih.endweek, ih.endmonth
, (select ihextr.deltocustvatnumber from invoiceheaderextrainfo ihextr where ihextr.invoiceheader_id = ih.invoiceheader_id) deltocustvatnumber
, 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 cus.currency_id=crr.currency_id) invoiceamountdecimals
, (select crr.decimals from currency crr where cus.currency_id=crr.currency_id) pricedecimals
, cdn.closingdate--, cbi.residentialservicesallowed
, crs.customerclients, cr.laundryservicesparticipant
, v.departmentnumber, v.Dep_desc, v.department_id
, cdn.roomnumber, cdn.clientdeliverynotenumber, cli.clientnumber
, cli.searchname, cli.name Client_name, cli.adminnumber, cli.client_id
, cus.name Customer_name, cus.customernumber, a.city
, cus.extraname1 customer_extraname, a.street custmer_str, a.zipcode customer_zip
, (select cou.description from country cou where cus.country_id = cou.country_id) customer_country
, 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 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)
  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, p.product_id, f.finishingmethod_id
, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT,
         (select case when ih.enddate < tg.startdatetaxrate then tg.oldtaxrate
               else tg.taxrate
               end taxrate
         from taxgroup tg, customer bill
         where il.taxgroupcode = tg.code
               and bill.customer_id = ih.billtocustomer_link_id
               and tg.country_id = bill.country_id) taxrate
, txg.code taxgroup_code, txg.description taxgroup_desc, cus.PNNUMBER
, (select cic.code
   from clientbillinginfo cbi, clientinvoicecategory cic
   where cbi.client_id = cli.client_id
         and cbi.clientinvoicecategory_id = cic.clientinvoicecategory_id) clientinvoicecateg
, (select fg.code from flag fg where cli.flag_id = fg.flag_id) clientflagcode
, (select wc.code from weighingcategory_link wc where wc.weighingcategory_link_id = cdn.weighingcategory_link_id) weightcode
, (cdn.grossweight-cdn.tareweight) calculatedweight
, cdn.weightprice weightprice
,(select wp.price
  from generalwashprice wp, generalpricelist g
  where wp.generalpricelist_id = g.generalpricelist_id
    and g.code = to_char(cus.pnnumber)
    and cdl.product_link_id = wp.product_id
    and cdl.sizedefinition_link_id = wp.sizedefinition_id
    and cdl.finishingmethod_id = wp.finishingmethod_id
    and wp.pricetype = 1
    and wp.startdate = ( select max(x.startdate)
      from generalwashprice x
      where x.generalpricelist_id  = wp.generalpricelist_id
        and x.startdate <= cdn.Deliverydate
        and x.product_id = wp.product_id
        and x.sizedefinition_id = wp.sizedefinition_id
        and x.finishingmethod_id = wp.finishingmethod_id
        and x.pricetype = wp.pricetype )) specialprice
, pp.name plantname, pladdress.street plantstreet
, pladdress.zipcode plantzip, pladdress.city plantcity
, pp.phoneno plantphone, pp.faxno plantfax
, pp.email plantemail, pp.website plantwebsite
, cli.remark client_remark
, (select max(pt.name || ' ' || pt.phoneno)
   from plant pt, businessunit bu, productgroup pg, customeractivities ca
   where pt.plant_id = bu.plant_id
         and ca.invoicebusinessunit_id = bu.businessunit_id
         and pg.activity_id = ca.activity_id
         and pg.productgroup_id = p.productgroup_id
         and ca.customer_id = cus.customer_id) invoiceplantcontact
, (select ihextr.formlayoutcode
   from invoiceheaderextrainfo ihextr
   where ihextr.invoiceheader_id = ih.invoiceheader_id) invoicelayoutcode
, (select ba.batchdate from batch ba where ba.batch_id = cdn.batch_id) batchdate
, (select cast(sst.value as varchar2(10)) from systemsetting sst where sst.plant_id = pp.plant_id and sst.name = 'CLIENTINVOICEDBASEDON') CLIENTINVOICEDBASEDON
, wd.department_id webuserdepartment_id
, wus.websession_id
, wuc.webuser_id
from clientdeliverynoteline cdl
left outer join invoiceline il
     join invoiceheader ih on (ih.invoiceheader_id=il.invoiceheader_id)
on cdl.invoiceline_id=il.invoiceline_id
, client cli --left outer join clientbillinginfo cbi on cbi.client_id = cli.client_id
left outer join clientresident cr on cli.client_id=cr.client_id
, v_ClientDepartment v
, address a, customer cus
left outer join Customerresidentialsettings crs on cus.customer_id=crs.customer_id
, clientdeliverynote cdn
  left outer join invoiceline ilh
       join invoiceheader ihh on (ihh.invoiceheader_id = ilh.invoiceheader_id)
  on cdn.invoiceline_id = ilh.invoiceline_id
  left outer join clientdeliverynotetax ctx
	     join taxgroup txg on (ctx.taxgroup_id = txg.taxgroup_id)
	ON ctx.CLIENTDELIVERINOTE_ID = cdn.ClientDeliveryNote_ID
, languages l
, product p, sizedefinition s, finishingmethod f
, address pladdress, businessunit bu, plant pp,
webusercustomer wuc
    left outer join webuserdepartment wd on (wuc.webusercustomer_id = wd.webusercustomer_id),
  webusersession wus
where cdl.clientdeliverinote_id = cdn.clientdeliverynote_id
and cdn.customer_link_id = cus.customer_id
and cli.client_id = cdn.client_link_id
and cus.visitaddress_id = a.address_id
and cdl.product_link_id = p.product_id
and cdl.sizedefinition_link_id = s.sizedefinition_id
and cdl.finishingmethod_id = f.finishingmethod_id
and cli.client_id=v.client_id
and cdn.closingdate is not null
and cdn.processbusinessunit_id = bu.businessunit_id
and bu.plant_id = pp.plant_id
and pp.address_id = pladdress.address_id
and cli.customer_id = wuc.customer_id
and wuc.customer_id = wus.customer_id
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.invoicedate l_invoicedate, ihh.invoicedate h_invoicedate
, ih.billtocustomernumber, ih.billtocustomername, ih.street l_billstreet, ih.city l_billcity, ih.zipcode l_billzip, ih.purchaseorder
, ih.invoicefrequency_id invoicefrequencynumber, ih.nextperiodstartdate, ih.nextperiodenddate, ih.nextperiodstartweek, ih.nextperiodendweek, ih.startweek, ih.startmonth, ih.endweek, ih.endmonth
, (select ihextr.deltocustvatnumber from invoiceheaderextrainfo ihextr where ihextr.invoiceheader_id = ih.invoiceheader_id) deltocustvatnumber
, 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 cus.currency_id=crr.currency_id) invoiceamountdecimals
, (select crr.decimals from currency crr where cus.currency_id=crr.currency_id) pricedecimals
, cdn.closingdate--, cbi.residentialservicesallowed
, crs.customerclients, cr.laundryservicesparticipant
, v.departmentnumber, v.Dep_desc, v.department_id
, cdn.roomnumber, cdn.clientdeliverynotenumber, cli.clientnumber
, cli.searchname, cli.name Client_name, cli.adminnumber, cli.client_id
, cus.name Customer_name, cus.customernumber, a.city
, cus.extraname1 customer_extraname, a.street custmer_str, a.zipcode customer_zip
, (select cou.description from country cou where cus.country_id = cou.country_id) customer_country
, 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 weightdecimals, il.price Il_Price, cdc.price
, -2 LineInvoicebusinessunit_id
, l.code Language_code
, '' Size_code, '' Finishing_code,  -1 FMwashtype, -1 product_id, -1 finishingmethod_id
, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT--SUM(ctx.TAXAMOUNT) TAXAMOUNT
, null taxrate
, txg.code taxgroup_code, txg.description taxgroup_desc, cus.PNNUMBER
, (select cic.code
   from clientbillinginfo cbi, clientinvoicecategory cic
   where cbi.client_id = cli.client_id
         and cbi.clientinvoicecategory_id = cic.clientinvoicecategory_id) clientinvoicecateg
, (select fg.code from flag fg where cli.flag_id = fg.flag_id) clientflagcode
, (select wc.code from weighingcategory_link wc where wc.weighingcategory_link_id = cdn.weighingcategory_link_id) weightcode
, (cdn.grossweight-cdn.tareweight) calculatedweight
, cdn.weightprice weightprice
, null specialprice
, pp.name plantname, pladdress.street plantstreet
, pladdress.zipcode plantzip, pladdress.city plantcity
, pp.phoneno plantphone, pp.faxno plantfax
, pp.email plantemail, pp.website plantwebsite
, cli.remark client_remark
, (select max(pt.name || ' ' || pt.phoneno)
   from plant pt, businessunit bu, customeractivities ca
   where pt.plant_id = bu.plant_id
         and ca.invoicebusinessunit_id = bu.businessunit_id
         and ca.customer_id = cus.customer_id
         and ca.includenotactivityrelcharges = 'Y') invoiceplantcontact
, (select ihextr.formlayoutcode
   from invoiceheaderextrainfo ihextr
   where ihextr.invoiceheader_id = ih.invoiceheader_id) invoicelayoutcode
, (select ba.batchdate from batch ba where ba.batch_id = cdn.batch_id) batchdate
, (select cast(sst.value as varchar2(10)) from systemsetting sst where sst.plant_id = pp.plant_id and sst.name = 'CLIENTINVOICEDBASEDON') CLIENTINVOICEDBASEDON
, 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
, client cli --left outer join clientbillinginfo cbi on cbi.client_id = cli.client_id
left outer join clientresident cr on cli.client_id=cr.client_id
, v_ClientDepartment v
, address a, customer cus
left outer join Customerresidentialsettings crs on cus.customer_id=crs.customer_id
, clientdeliverynote cdn left outer join invoiceline ilh
       join invoiceheader ihh on (ihh.invoiceheader_id = ilh.invoiceheader_id)
  on cdn.invoiceline_id = ilh.invoiceline_id
  left outer join clientdeliverynotetax ctx
	     join taxgroup txg on (ctx.taxgroup_id = txg.taxgroup_id)
	ON ctx.CLIENTDELIVERINOTE_ID = cdn.ClientDeliveryNote_ID
, languages l
, specialcharge sc
, address pladdress, businessunit bu, plant pp,
webusercustomer wuc
    left outer join webuserdepartment wd on (wuc.webusercustomer_id = wd.webusercustomer_id),
  webusersession wus
where cdc.clientdeliverinote_id=cdn.clientdeliverynote_id
and cdn.customer_link_id=cus.customer_id
and cli.client_id=cdn.client_link_id
and cus.visitaddress_id=a.address_id
and cdc.specialcharge_id=sc.specialcharge_id
and cli.client_id=v.client_id
and cdn.closingdate is not null
and cdn.processbusinessunit_id = bu.businessunit_id
and bu.plant_id = pp.plant_id
and pp.address_id = pladdress.address_id
and cli.customer_id = wuc.customer_id
and wuc.customer_id = wus.customer_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.invoicedate l_invoicedate, ih.invoicedate h_invoicedate
, ih.billtocustomernumber, ih.billtocustomername, ih.street l_billstreet, ih.city l_billcity, ih.zipcode l_billzip, ih.purchaseorder
, ih.invoicefrequency_id invoicefrequencynumber, ih.nextperiodstartdate, ih.nextperiodenddate, ih.nextperiodstartweek, ih.nextperiodendweek, ih.startweek, ih.startmonth, ih.endweek, ih.endmonth
, (select ihextr.deltocustvatnumber from invoiceheaderextrainfo ihextr where ihextr.invoiceheader_id = ih.invoiceheader_id) deltocustvatnumber
, 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 cus.currency_id=crr.currency_id) invoiceamountdecimals
, (select crr.decimals from currency crr where cus.currency_id=crr.currency_id) pricedecimals
, cdn.closingdate--, cbi.residentialservicesallowed
, crs.customerclients, cr.laundryservicesparticipant
, v.departmentnumber, v.Dep_desc, v.department_id
, cdn.roomnumber, cdn.clientdeliverynotenumber, cli.clientnumber
, cli.searchname, cli.name Client_name, cli.adminnumber, cli.client_id
, cus.name Customer_name, cus.customernumber, a.city
, cus.extraname1 customer_extraname, a.street custmer_str, a.zipcode customer_zip
, (select cou.description from country cou where cus.country_id = cou.country_id) customer_country
, 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, cdn.weightdecimals, il.price Il_Price, cdn.weightprice Price
, -3 LineInvoicebusinessunit_id
, l.code Language_code
, '' Size_code, '' Finishing_code,  -1 FMwashtype, -1 product_id, -1 finishingmethod_id
, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT--SUM(ctx.TAXAMOUNT) TAXAMOUNT
, (select tg.taxrate
   from taxgroup tg, weighingcategorytax wct
   where tg.taxgroup_id = wct.taxgroup_id
         and wct.weighingcategory_id = wc.weighingcategory_id
         and wct.country_id = cus.country_id) taxrate
, txg.code taxgroup_code, txg.description taxgroup_desc, cus.PNNUMBER
, (select cic.code
   from clientbillinginfo cbi, clientinvoicecategory cic
   where cbi.client_id = cli.client_id
         and cbi.clientinvoicecategory_id = cic.clientinvoicecategory_id) clientinvoicecateg
, (select fg.code from flag fg where cli.flag_id = fg.flag_id) clientflagcode
, (select wc.code from weighingcategory_link wc where wc.weighingcategory_link_id = cdn.weighingcategory_link_id) weightcode
, (cdn.grossweight-cdn.tareweight) calculatedweight
, cdn.weightprice weightprice
, null specialprice
, pp.name plantname, pladdress.street plantstreet
, pladdress.zipcode plantzip, pladdress.city plantcity
, pp.phoneno plantphone, pp.faxno plantfax
, pp.email plantemail, pp.website plantwebsite
, cli.remark client_remark
, (select max(pt.name || ' ' || pt.phoneno)
   from plant pt, businessunit bu, productgroup pg, customeractivities ca
   where pt.plant_id = bu.plant_id
         and ca.invoicebusinessunit_id = bu.businessunit_id
         and wc.activity_id = ca.activity_id
         and ca.customer_id = cus.customer_id) invoiceplantcontact
, (select ihextr.formlayoutcode
   from invoiceheaderextrainfo ihextr
   where ihextr.invoiceheader_id = ih.invoiceheader_id) invoicelayoutcode
, (select ba.batchdate from batch ba where ba.batch_id = cdn.batch_id) batchdate
, (select cast(sst.value as varchar2(10)) from systemsetting sst where sst.plant_id = pp.plant_id and sst.name = 'CLIENTINVOICEDBASEDON') CLIENTINVOICEDBASEDON
, wd.department_id webuserdepartment_id
, wus.websession_id
, wuc.webuser_id
from clientdeliverynote cdn
  left outer join invoiceline il
     join invoiceheader ih on (ih.invoiceheader_id=il.invoiceheader_id)
  on cdn.invoiceline_id=il.invoiceline_id
  left outer join clientdeliverynotetax ctx
	     join taxgroup txg on (ctx.taxgroup_id = txg.taxgroup_id)
	ON ctx.CLIENTDELIVERINOTE_ID = cdn.ClientDeliveryNote_ID
, client cli --left outer join clientbillinginfo cbi on cbi.client_id = cli.client_id
left outer join clientresident cr on cli.client_id=cr.client_id
, v_ClientDepartment v
, address a, customer cus
left outer join Customerresidentialsettings crs on cus.customer_id=crs.customer_id
, languages l
, weighingcategory wc
, address pladdress, businessunit bu, plant pp,
webusercustomer wuc
    left outer join webuserdepartment wd on (wuc.webusercustomer_id = wd.webusercustomer_id),
  webusersession wus
where cdn.customer_link_id=cus.customer_id
and cli.client_id=cdn.client_link_id
and cus.visitaddress_id=a.address_id
and wc.weighingcategory_id=cdn.weighingcategory_link_id
and cli.client_id=v.client_id
and cdn.closingdate is not null
and cdn.processbusinessunit_id = bu.businessunit_id
and bu.plant_id = pp.plant_id
and pp.address_id = pladdress.address_id
and cli.customer_id = wuc.customer_id
and wuc.customer_id = wus.customer_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.invoicedate l_invoicedate, ihh.invoicedate h_invoicedate
, ih.billtocustomernumber, ih.billtocustomername, ih.street l_billstreet, ih.city l_billcity, ih.zipcode l_billzip, ih.purchaseorder
, ih.invoicefrequency_id invoicefrequencynumber, ih.nextperiodstartdate, ih.nextperiodenddate, ih.nextperiodstartweek, ih.nextperiodendweek, ih.startweek, ih.startmonth, ih.endweek, ih.endmonth
, (select ihextr.deltocustvatnumber from invoiceheaderextrainfo ihextr where ihextr.invoiceheader_id = ih.invoiceheader_id) deltocustvatnumber
, 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--, cbi.residentialservicesallowed
, crs.customerclients, cr.laundryservicesparticipant
, v.departmentnumber, v.Dep_desc, v.department_id
, cdn.roomnumber, cdn.clientdeliverynotenumber, cli.clientnumber
, cli.searchname, cli.name Client_name, max(cli.adminnumber) adminnumber, cli.client_id
, cus.name Customer_name, cus.customernumber, a.city
, cus.extraname1 customer_extraname, a.street custmer_str, a.zipcode customer_zip
, (select cou.description from country cou where cus.country_id = cou.country_id) customer_country
, ll.code Prod_code
, pqr.preprinted Sizedef_Desc
, pqr.chargeable Prod_Desc
, '11' 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, -1 product_id, -1 finishingmethod_id
, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT--SUM(ctx.TAXAMOUNT) TAXAMOUNT
, null taxrate
, txg.code taxgroup_code, txg.description taxgroup_desc, max(cus.PNNUMBER) PNNUMBER
, (select cic.code
   from clientbillinginfo cbi, clientinvoicecategory cic
   where cbi.client_id = cli.client_id
         and cbi.clientinvoicecategory_id = cic.clientinvoicecategory_id) clientinvoicecateg
, (select fg.code from flag fg where cli.flag_id = fg.flag_id) clientflagcode
, (select wc.code from weighingcategory_link wc where wc.weighingcategory_link_id = cdn.weighingcategory_link_id) weightcode
, (cdn.grossweight-cdn.tareweight) calculatedweight
, cdn.weightprice weightprice
, il.price specialprice
, pp.name plantname, pladdress.street plantstreet
, pladdress.zipcode plantzip, pladdress.city plantcity
, pp.phoneno plantphone, pp.faxno plantfax
, pp.email plantemail, pp.website plantwebsite
, cli.remark client_remark
, (select max(pt.name || ' ' || pt.phoneno)
   from plant pt, businessunit bu, customeractivities ca
   where pt.plant_id = bu.plant_id
         and ca.invoicebusinessunit_id = bu.businessunit_id
         and ca.customer_id = cus.customer_id
         and ca.includenotactivityrelcharges = 'Y') invoiceplantcontact
, (select ihextr.formlayoutcode
   from invoiceheaderextrainfo ihextr
   where ihextr.invoiceheader_id = ih.invoiceheader_id) invoicelayoutcode
, (select ba.batchdate from batch ba where ba.batch_id = cdn.batch_id) batchdate
, (select cast(sst.value as varchar2(10)) from systemsetting sst where sst.plant_id = pp.plant_id and sst.name = 'CLIENTINVOICEDBASEDON') CLIENTINVOICEDBASEDON
, wd.department_id webuserdepartment_id
, wus.websession_id
, wuc.webuser_id
from printqueueresidentialitem pqr
left outer join invoiceline il
     join invoiceheader ih on (ih.invoiceheader_id=il.invoiceheader_id)
on pqr.invoiceline_id=il.invoiceline_id
, client cli --left outer join clientbillinginfo cbi on cbi.client_id = cli.client_id
left outer join clientresident cr on cli.client_id=cr.client_id
, v_ClientDepartment v
, address a, customer cus
left outer join Customerresidentialsettings crs on cus.customer_id=crs.customer_id
, currency crr
, clientdeliverynote cdn
  left outer join invoiceline ilh
	     join invoiceheader ihh on (ihh.invoiceheader_id = ilh.invoiceheader_id)
  on cdn.invoiceline_id = ilh.invoiceline_id
  left outer join clientdeliverynotetax ctx
	     join taxgroup txg on (ctx.taxgroup_id = txg.taxgroup_id)
	ON ctx.CLIENTDELIVERINOTE_ID = cdn.ClientDeliveryNote_ID
, languages l
, labellayout ll
, address pladdress, businessunit bu, plant pp,
webusercustomer wuc
    left outer join webuserdepartment wd on (wuc.webusercustomer_id = wd.webusercustomer_id),
  webusersession wus
where pqr.clientdeliverynote_id=cdn.clientdeliverynote_id
and cdn.customer_link_id=cus.customer_id
and cli.client_id=cdn.client_link_id
and cus.visitaddress_id=a.address_id
and cus.currency_id=crr.currency_id
and pqr.labellayout_id=ll.labellayout_id
and cli.client_id=v.client_id
and cdn.closingdate is not null
and cdn.processbusinessunit_id = bu.businessunit_id
and bu.plant_id = pp.plant_id
and pp.address_id = pladdress.address_id
and cli.customer_id = wuc.customer_id
and wuc.customer_id = wus.customer_id
group by ll.labellayout_id, il.invoiceline_id, pqr.chargeable , pqr.preprinted
, ih.invoiceheader_id , ih.invoicenumber, ih.invoicedate, ih.invoicebusinessunit_id
, cdn.processbusinessunit_id, cdn.customer_link_id, cdn.deliverydate
, cdn.closingdate--, cbi.residentialservicesallowed
, v.departmentnumber, v.Dep_desc
, cdn.roomnumber, cdn.clientdeliverynotenumber, cli.clientnumber
, cli.searchname, cli.name, cli.client_id
, cus.name , cus.customernumber, cus.customer_id, cus.extraname1, a.city, a.street, a.zipcode, cus.country_id
, ll.code, il.price, pqr.price, cdn.invoicebusinessunit_id, l.code
, ih.documenttype , ilh.invoiceline_id , ihh.invoicenumber, ihh.invoicedate, ihh.documenttype
, crr.invoiceamountdecimals, crr.decimals, crs.customerclients, cr.laundryservicesparticipant
, pqr.invoicebusinessunit_id
, ctx.TAXPERCENTAGE, ctx.TAXAMOUNT, txg.code, txg.description, cli.flag_id
, cdn.weighingcategory_link_id, cdn.grossweight, cdn.tareweight, cdn.weightprice
, pp.name, pladdress.street, pladdress.zipcode, pladdress.city, pp.phoneno, pp.faxno
, pp.email, pp.website, cli.remark, ih.purchaseorder, ih.billtocustomernumber, ih.billtocustomername, ih.street, ih.city, ih.zipcode
, ih.invoicefrequency_id, ih.startweek, ih.startmonth, ih.endweek, ih.endmonth
, ih.nextperiodstartdate, ih.nextperiodenddate, ih.nextperiodstartweek, ih.nextperiodendweek, cdn.batch_id, pp.plant_id
, wd.department_id, wus.websession_id, wuc.webuser_id, v.department_id

/
create or replace view V_WORKORDERPRODUCTEMBLEM
 (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, EMBROIDERYCOLOR_ID, SEQUENCENUMBER, COLOR_ID, COLOR_CODE, COLOR_RALCODE, COLOR_USEDFOREMBLEM, COLOR_DESCRIPTION, SYSTEMUSER_ID, TIMESTAMP, PRODNR, PRODDESCRIPTION
, PRODLONGDESCRIPTION, FINMETHCODE, SIZECODE, UNIQUEYN, QUALITYGRADE, QUANTITYORDERED, QUANTITYCANCELLED, QDONE, QORDER, QOPEN, MODIFICATIONGROUPCODE, MODIFICATIONCODE, MODIFICATIONDESC, INSTRUCTIONS)
as select b.workorder_id,
       b.workorderline_id,
       b.LanguageCode,
       b.EmblemNr,
       b.EmblemDescription,
       b.EmblemType,
       b.SizeShape,
       b.Background,
       b.Border,
       b.Text,
       b.Quantity,
       b.placement,
       b.PutEmblemOn,
       b.workorderlineemblem_id,
       b.fabric,
       b.emblem_font,
       b.product_id,
       b.sizedefinition_id,
       b.attachment_by,
       b.embroyderyfilepathproduction,
       b.fontsize,
       b.colorpalette,
       b.emblemtemplateline_id,
       c.embroiderycolor_id,
       c.sequencenumber,
       c.color_id,
       c.color_code,
       c.color_ralcode,
       c.color_usedforemblem,
       c.color_description,
       c.systemuser_id,
       c.timestamp,
       --c.LANGUAGECODE,
       d.ProdNr,
       d.ProdDescription,
       d.ProdLongDescription,
       d.FinMethCode,
       d.SizeCode,
       d.UniqueYN,
       d.qualitygrade,
       d.quantityordered,
       d.quantitycancelled,
       d.qDone,
       d.qOrder,
       d.qOpen,
       d.ModificationGroupCode,
       d.ModificationCode,
       d.ModificationDesc,
       d.instructions
  from v_workorder a, v_workorderplpc e, v_workorderline d
  left outer join v_workorderemblem b
  left outer join v_workorderemblem_embcolors c on c.emblemtemplateline_id = b.emblemtemplateline_id on
 d.workorderline_id = b.workorderline_id
 where a.workorder_id = d.workorder_id
   and d.workorderline_id = e.workorderline_id
/
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, 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)
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,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,
(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
, address.street, address.zipcode, address.city
, null wcustomernumber, '' wname, '' wcustomermarkinggarment
, '' wstreet, '' wzipcode, '' 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 = distributionpoint.deliverypoint_id) DeliveryPointDesc,
department.description Department
, department.departmentnumber
, w.emblemname NameOnLabel, distributionpoint.description ConsPoint--, wearerfunction.description FunctionX
, (select wf.description from wearerfunction wf where we.wearerfunction_id = wf.wearerfunction_id) FunctionX
, w.remark WearerRemark, route.routenumber, route.description RouteDescription
, wok.customerowned NotLaundryOwned, status.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
, plant.code plant_code, plant.name plant_name, plant.phoneno plant_phoneno, plant.faxno plant_faxno
, plant.email plant_email, plant.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 = plant.plant_id and ss.name = 'PRINTBARCODEONWORKORDER'), 1) Print_Barcode
, lan.code Language_code
, lpad((select sy.value from systemsetting sy where sy.plant_id = plant.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
from workorder wok   --left outer
            join weareremployment we  on wok.weareremployment_link_id = we.weareremployment_id --left outer join wearerfunction on we.wearerfunction_id = wearerfunction.wearerfunction_id
                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
                left outer join deliverypoint dpl 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 address adr on dpl.deliveryaddress_id=adr.address_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
                        join address on cu.visitaddress_id = address.address_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 employee emp on su.employee_id=emp.employee_id
 left outer join woreferencenumber worefnr on wok.woreferencenumber_id = worefnr.woreferencenumber_id
, status, businessunit bu, plant, address paddr--, SYSTEMSETTING SS
, languages lan, orderpriority op, reasoncode rc
, reportparam rp
where wok.status_id = status.status_id
    and wok.businessunit_id = bu.businessunit_id
    and bu.plant_id = plant.plant_id
    and plant.address_id = paddr.address_id    --and ss.plant_id=plant.plant_id and ss.name='PRINTBARCODEONWORKORDER'
    and rp.number_value = wok.workorder_id
    and wok.orderpriority_id=op.orderpriority_id
    and op.ordertype=1
    and wok.reasoncode_id=rc.reasoncode_id
  UNION
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, 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,
(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
, address.street, address.zipcode, address.city
, cus.customernumber wcustomernumber, cus.name wname, cus.customermarkinggarment wcustomermarkinggarment
, addr.street wstreet, addr.zipcode wzipcode, addr.city wcity
, null WearerNr
, null WearerName, null wearersearchname, null WearerFIRSTNAME
, null Admin, null EmplNr, null CupBoard, null
, null GarmentDispenser, (select de.code from deliverypoint de where de.deliverypoint_id = distributionpoint.deliverypoint_id) DeliveryPoint,
(select de.description from deliverypoint de where de.deliverypoint_id = distributionpoint.deliverypoint_id) DeliveryPointDesc,
department.description Department
, department.departmentnumber
, null NameOnLabel, distributionpoint.description ConsPoint--, wearerfunction.description FunctionX
, null FunctionX
, null WearerRemark, route.routenumber, route.description RouteDescription
, wok.customerowned NotLaundryOwned, status.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
, plant.code plant_code, plant.name plant_name, plant.phoneno plant_phoneno, plant.faxno plant_faxno
, plant.email plant_email, plant.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 = plant.plant_id and ss.name = 'PRINTBARCODEONWORKORDER'), 1) Print_Barcode
, lan.code Language_code
, lpad((select sy.value from systemsetting sy where sy.plant_id = plant.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
, null
, null
, null
, null
, null
, null
, null
, null
, null
, null
, 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
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 address on cu.visitaddress_id=address.address_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 address  addr on cus.visitaddress_id=addr.address_id
 left outer join Systemuser su on wok.creationuser_id=su.systemuser_id
 left outer join employee emp on su.employee_id=emp.employee_id
 left outer join woreferencenumber worefnr on wok.woreferencenumber_id = worefnr.woreferencenumber_id
, status, businessunit bu, plant, address paddr--, SYSTEMSETTING SS
, languages lan, orderpriority op , reasoncode rc
, reportparam rp
where wok.status_id = status.status_id
    and wok.businessunit_id = bu.businessunit_id
    and plant.address_id = paddr.address_id
    and bu.plant_id = plant.plant_id    --and ss.plant_id=plant.plant_id and ss.name='PRINTBARCODEONWORKORDER'
    and wok.weareremployment_link_id is null
    and rp.number_value = wok.workorder_id
    and wok.orderpriority_id=op.orderpriority_id
    and op.ordertype=1
    and wok.reasoncode_id=rc.reasoncode_id

/
create or replace view V_WORKORDER_LTS
 (WORKORDER_ID, WORKORDERNUMBER, ORDERDATE, REFERENCENUMBER, ORDERREMARK, DELIVERYDATE, SCHEDULEDDELIVERY, ORIGIN, DELIVERYDAY_DESC, SCHEDULEDDELIVERY_DESC, DOCKET, CUSTOMERNUMBER, NAME, CUSTOMERMARKINGGARMENT, STREET, ZIPCODE, CITY, WCUSTOMERNUMBER, WNAME, WCUSTOMERMARKINGGARMENT, WSTREET, WZIPCODE, WCITY, WEARERNR, WEARERNAME, WEARERSEARCHNAME, WEARERFIRSTNAME, ADMIN, EMPLNR, CUPBOARD, LOCKER, 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, VATNUMBER)
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
, cu.customernumber, cu.name, cu.customermarkinggarment
, address.street, address.zipcode, address.city
, null wcustomernumber, '' wname, '' wcustomermarkinggarment
, '' wstreet, '' wzipcode, '' wcity
, w.wearernumber WearerNr
, w.fullname WearerName, w.searchname wearersearchname, W.FIRSTNAME WearerFIRSTNAME
, 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 FunctionX
, (select wf.description from wearerfunction wf where we.wearerfunction_id = wf.wearerfunction_id) FunctionX
, w.remark WearerRemark, route.routenumber, route.description RouteDescription
, wok.customerowned NotLaundryOwned, status.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
, plant.code plant_code, plant.name plant_name, plant.phoneno plant_phoneno, plant.faxno plant_faxno
, plant.email plant_email, plant.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
, (select ss.value from systemsetting ss where ss.plant_id = plant.plant_id and ss.name = 'PRINTBARCODEONWORKORDER') Print_Barcode
, lan.code Language_code
, (select sy.value from systemsetting sy where sy.plant_id = plant.plant_id and sy.name = 'PRINTREPLACEMENTSONWO') 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
, bu.vatnumber
from workorder wok   --left outer
   join weareremployment_LINK welk on wok.weareremployment_link_id = welk.weareremployment_link_id
            left outer join weareremployment we  on welk.weareremployment_id = we.weareremployment_id --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
                   left outer join deliverypointopeninghour dpoh on de.deliverypoint_id=dpoh.deliverypoint_id and dpoh.day_id = getabsdaynumber(wok.neededdate)
                  left outer join address adr on de.deliveryaddress_id=adr.address_id
                left outer join distributionpoint on distributionpoint.distributionpoint_id = we.distributionpoint_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 address on cu.visitaddress_id = address.address_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 employee emp on su.employee_id=emp.employee_id
, status, businessunit bu, plant, address paddr--, SYSTEMSETTING SS
, languages lan
where wok.status_id = status.status_id
    and wok.businessunit_id = bu.businessunit_id
    and bu.plant_id = plant.plant_id
    and plant.address_id = paddr.address_id    --and ss.plant_id=plant.plant_id and ss.name='PRINTBARCODEONWORKORDER'
UNION ALL
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
, cu.customernumber, cu.name, cu.customermarkinggarment
, address.street, address.zipcode, address.city
, cus.customernumber wcustomernumber, cus.name wname, cus.customermarkinggarment wcustomermarkinggarment
, addr.street wstreet, addr.zipcode wzipcode, addr.city wcity
, w.wearernumber WearerNr
, w.fullname WearerName, w.searchname wearersearchname, W.FIRSTNAME WearerFIRSTNAME
, 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 FunctionX
, (select wf.description from wearerfunction wf where we.wearerfunction_id = wf.wearerfunction_id) FunctionX
, w.remark WearerRemark, route.routenumber, route.description RouteDescription
, wok.customerowned NotLaundryOwned, status.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
, plant.code plant_code, plant.name plant_name, plant.phoneno plant_phoneno, plant.faxno plant_faxno
, plant.email plant_email, plant.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
, (select ss.value from systemsetting ss where ss.plant_id = plant.plant_id and ss.name = 'PRINTBARCODEONWORKORDER') Print_Barcode
, lan.code Language_code
, (select sy.value from systemsetting sy where sy.plant_id = plant.plant_id and sy.name = 'PRINTREPLACEMENTSONWO') 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
, bu.vatnumber
from workorder wok
   left outer join weareremployment_LINK welk on wok.weareremployment_link_id = welk.weareremployment_link_id
            left outer join weareremployment we on welk.weareremployment_id = we.weareremployment_id               -- 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
                    left outer join deliverypointopeninghour dpoh on de.deliverypoint_id=dpoh.deliverypoint_id and dpoh.day_id = getabsdaynumber(wok.neededdate)
                   left outer join address adr on de.deliveryaddress_id=adr.address_id
   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 address on cu.visitaddress_id=address.address_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 address  addr on cus.visitaddress_id=addr.address_id
 left outer join Systemuser su on wok.creationuser_id=su.systemuser_id
 left outer join employee emp on su.employee_id=emp.employee_id
, status, businessunit bu, plant, address paddr--, SYSTEMSETTING SS
, languages lan
where wok.status_id = status.status_id
    and wok.businessunit_id = bu.businessunit_id
    and plant.address_id = paddr.address_id
    and bu.plant_id = plant.plant_id    --and ss.plant_id=plant.plant_id and ss.name='PRINTBARCODEONWORKORDER'
    and wok.weareremployment_link_id is null

/
create or replace view V_WORKORDER_REP
 (WORKORDER_ID, WORKORDERNUMBER, ORDERDATE, REFERENCENUMBER, ORDERREMARK, DELIVERYDATE, SCHEDULEDDELIVERY, ORIGIN, DELIVERYDAY_DESC, SCHEDULEDDELIVERY_DESC, DOCKET, CUSTOMERNUMBER, NAME, CUSTOMERMARKINGGARMENT, STREET, ZIPCODE, CITY, WCUSTOMERNUMBER, WNAME, WCUSTOMERMARKINGGARMENT, WSTREET, WZIPCODE, WCITY, WEARERNR, WEARERNAME, WEARERSEARCHNAME, WEARERFIRSTNAME, ADMIN, EMPLNR, CUPBOARD, LOCKER, 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, REPORTPARAM_ID)
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
, cu.customernumber, cu.name, cu.customermarkinggarment
, address.street, address.zipcode, address.city
, null wcustomernumber, '' wname, '' wcustomermarkinggarment
, '' wstreet, '' wzipcode, '' 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, department.description Department
, department.departmentnumber
, w.emblemname NameOnLabel, distributionpoint.description ConsPoint--, wearerfunction.description FunctionX
, (select wf.description from wearerfunction wf where we.wearerfunction_id = wf.wearerfunction_id) FunctionX
, w.remark WearerRemark, route.routenumber, route.description RouteDescription
, wok.customerowned NotLaundryOwned, status.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
, plant.code plant_code, plant.name plant_name, plant.phoneno plant_phoneno, plant.faxno plant_faxno
, plant.email plant_email, plant.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 = plant.plant_id and ss.name = 'PRINTBARCODEONWORKORDER'), 1) Print_Barcode
, lan.code Language_code
, lpad((select sy.value from systemsetting sy where sy.plant_id = plant.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
from workorder wok   --left outer
            join weareremployment we  on wok.weareremployment_link_id = we.weareremployment_id --left outer join wearerfunction on we.wearerfunction_id = wearerfunction.wearerfunction_id
                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
                   left outer join deliverypointopeninghour dpoh on de.deliverypoint_id=dpoh.deliverypoint_id and dpoh.day_id = getabsdaynumber(wok.neededdate)
                  left outer join address adr on de.deliveryaddress_id=adr.address_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
                        join address on cu.visitaddress_id = address.address_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 employee emp on su.employee_id=emp.employee_id
 left outer join woreferencenumber worefnr on wok.woreferencenumber_id = worefnr.woreferencenumber_id
, status, businessunit bu, plant, address paddr--, SYSTEMSETTING SS
, languages lan
, reportparam rp
where wok.status_id = status.status_id
    and wok.businessunit_id = bu.businessunit_id
    and bu.plant_id = plant.plant_id
    and plant.address_id = paddr.address_id    --and ss.plant_id=plant.plant_id and ss.name='PRINTBARCODEONWORKORDER'
    and rp.number_value = wok.workorder_id
UNION
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
, cu.customernumber, cu.name, cu.customermarkinggarment
, address.street, address.zipcode, address.city
, cus.customernumber wcustomernumber, cus.name wname, cus.customermarkinggarment wcustomermarkinggarment
, addr.street wstreet, addr.zipcode wzipcode, addr.city wcity
, null WearerNr
, null WearerName, null wearersearchname, null WearerFIRSTNAME
, null Admin, null EmplNr, null CupBoard, null
, null GarmentDispenser, (select de.code from deliverypoint de where de.deliverypoint_id = distributionpoint.deliverypoint_id) DeliveryPoint, department.description Department
, department.departmentnumber
, null NameOnLabel, distributionpoint.description ConsPoint--, wearerfunction.description FunctionX
, null FunctionX
, null WearerRemark, route.routenumber, route.description RouteDescription
, wok.customerowned NotLaundryOwned, status.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
, plant.code plant_code, plant.name plant_name, plant.phoneno plant_phoneno, plant.faxno plant_faxno
, plant.email plant_email, plant.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 = plant.plant_id and ss.name = 'PRINTBARCODEONWORKORDER'), 1) Print_Barcode
, lan.code Language_code
, lpad((select sy.value from systemsetting sy where sy.plant_id = plant.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
, null
, null
, null
, null
, null
, null
, null
, null
, null
, null
, wok.replacement
, wok.woreferencenumber_id
, worefnr.referencenumber woreferencenr
, worefnr.description worefnr_desc
, rp.reportparam_id
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 address on cu.visitaddress_id=address.address_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 address  addr on cus.visitaddress_id=addr.address_id
 left outer join Systemuser su on wok.creationuser_id=su.systemuser_id
 left outer join employee emp on su.employee_id=emp.employee_id
 left outer join woreferencenumber worefnr on wok.woreferencenumber_id = worefnr.woreferencenumber_id
, status, businessunit bu, plant, address paddr--, SYSTEMSETTING SS
, languages lan
, reportparam rp
where wok.status_id = status.status_id
    and wok.businessunit_id = bu.businessunit_id
    and plant.address_id = paddr.address_id
    and bu.plant_id = plant.plant_id    --and ss.plant_id=plant.plant_id and ss.name='PRINTBARCODEONWORKORDER'
    and wok.weareremployment_link_id is null
    and rp.number_value = wok.workorder_id

/
create or replace view V_WORKORDER_REP_ANF
 (WORKORDER_ID, WORKORDERNUMBER, ORDERDATE, REFERENCENUMBER, ORDERREMARK, DELIVERYDATE, SCHEDULEDDELIVERY, ORIGIN, DELIVERYDAY_DESC, SCHEDULEDDELIVERY_DESC, DOCKET, CUSTOMERNUMBER, NAME, CUSTOMERMARKINGGARMENT, STREET, ZIPCODE, CITY, WCUSTOMERNUMBER, WNAME, WCUSTOMERMARKINGGARMENT, WSTREET, WZIPCODE, WCITY, WEARERNR, WEARERNAME, WEARERSEARCHNAME, WEARERFIRSTNAME, ADMIN, EMPLNR, CUPBOARD, LOCKER, 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, REPORTPARAM_ID, CUSTOMERTYPE, IPO_BU_CODE, IPO_BU_DESC, IPO_SENT_DATE, IPO_PRIORITY, PURCHASEORDER, PO_REQUESTEDDATE)
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
, cu.customernumber, cu.name, cu.customermarkinggarment
, address.street, address.zipcode, address.city
, null wcustomernumber, '' wname, '' wcustomermarkinggarment
, '' wstreet, '' wzipcode, '' 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, department.description Department
, department.departmentnumber
, w.emblemname NameOnLabel, distributionpoint.description ConsPoint--, wearerfunction.description FunctionX
, (select wf.description from wearerfunction wf where we.wearerfunction_id = wf.wearerfunction_id) FunctionX
, w.remark WearerRemark, route.routenumber, route.description RouteDescription
, wok.customerowned NotLaundryOwned, status.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
, plant.code plant_code, plant.name plant_name, plant.phoneno plant_phoneno, plant.faxno plant_faxno
, plant.email plant_email, plant.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 = plant.plant_id and ss.name = 'PRINTBARCODEONWORKORDER'), 1) Print_Barcode
, lan.code Language_code
, lpad((select sy.value from systemsetting sy where sy.plant_id = plant.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
, cu.customertype, ipo.code IPO_BU_code, ipo.description IPO_BU_desc
, null ipo_sent_date, null ipo_priority, -1 purchaseorder, null po_requesteddate
from workorder wok   --left outer
            join weareremployment we  on wok.weareremployment_link_id = we.weareremployment_id --left outer join wearerfunction on we.wearerfunction_id = wearerfunction.wearerfunction_id
                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
                left outer join deliverypointopeninghour dpoh on de.deliverypoint_id=dpoh.deliverypoint_id and dpoh.day_id = getabsdaynumber(wok.neededdate)
                left outer join address adr on de.deliveryaddress_id=adr.address_id
                inner join distributionpoint on distributionpoint.distributionpoint_id = we.distributionpoint_id
                      inner join department on distributionpoint.department_id = department.department_id
                       inner join customer cu
                            inner join businessunit ipo on ipo.businessunit_id = cu.defaultbusinessunit_id
                            inner join address on cu.visitaddress_id = address.address_id
                       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 employee emp on su.employee_id = emp.employee_id
 left outer join woreferencenumber worefnr on wok.woreferencenumber_id = worefnr.woreferencenumber_id
, status, businessunit bu, plant, address paddr--, SYSTEMSETTING SS
, languages lan
, reportparam rp
where wok.status_id = status.status_id
    and wok.businessunit_id = bu.businessunit_id
    and bu.plant_id = plant.plant_id
    and plant.address_id = paddr.address_id    --and ss.plant_id=plant.plant_id and ss.name='PRINTBARCODEONWORKORDER'
    and rp.number_value = wok.workorder_id
UNION ALL
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
, cu.customernumber, cu.name, cu.customermarkinggarment
, address.street, address.zipcode, address.city
, cus.customernumber wcustomernumber, cus.name wname, cus.customermarkinggarment wcustomermarkinggarment
, addr.street wstreet, addr.zipcode wzipcode, addr.city wcity
, null WearerNr
, null WearerName, null wearersearchname, null WearerFIRSTNAME
, null Admin, null EmplNr, null CupBoard, null
, null GarmentDispenser, (select de.code from deliverypoint de where de.deliverypoint_id = distributionpoint.deliverypoint_id) DeliveryPoint, department.description Department
, department.departmentnumber
, null NameOnLabel, distributionpoint.description ConsPoint--, wearerfunction.description FunctionX
, null FunctionX
, null WearerRemark, route.routenumber, route.description RouteDescription
, wok.customerowned NotLaundryOwned, status.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
, plant.code plant_code, plant.name plant_name, plant.phoneno plant_phoneno, plant.faxno plant_faxno
, plant.email plant_email, plant.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 = plant.plant_id and ss.name = 'PRINTBARCODEONWORKORDER'), 1) Print_Barcode
, lan.code Language_code
, lpad((select sy.value from systemsetting sy where sy.plant_id = plant.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
, null
, null
, null
, null
, null
, null
, null
, null
, null
, null
, wok.replacement
, wok.woreferencenumber_id
, worefnr.referencenumber woreferencenr
, worefnr.description worefnr_desc
, rp.reportparam_id
, cu.customertype, ipo.code IPO_BU_code, ipo.description IPO_BU_desc, poh.orderdate ipo_sent_date
, (select opd.description from orderpriority_desc opd where opd.orderpriority_id = poh.orderpriority_id and opd.language_id = lan.language_id) ipo_priority
, poh.purchaseordernumber purchaseorder, poh.requesteddate po_requesteddate
from workorder wok
   left outer join distributionpoint
        inner join department
             inner join customer cu
                  inner join address on cu.visitaddress_id=address.address_id
             on cu.customer_id = department.customer_id
        on distributionpoint.department_id = department.department_id
   on distributionpoint.distributionpoint_id = wok.distributionpoint_link_id
   left outer join route on wok.route_id = route.route_id
   left outer join customer cus
             inner join businessunit ipo on ipo.businessunit_id = cus.defaultbusinessunit_id
             inner join address  addr on cus.visitaddress_id=addr.address_id
   on cus.customer_id = wok.customer_link_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 purchaseorderheader poh on castnumberasvarchar(poh.purchaseordernumber) = wok.referencenumber
, status, businessunit bu, plant, address paddr--, SYSTEMSETTING SS
, languages lan
, reportparam rp
where wok.status_id = status.status_id
    and wok.businessunit_id = bu.businessunit_id
    and plant.address_id = paddr.address_id
    and bu.plant_id = plant.plant_id    --and ss.plant_id=plant.plant_id and ss.name='PRINTBARCODEONWORKORDER'
    and wok.weareremployment_link_id is null
    and rp.number_value = wok.workorder_id

/
create or replace view V_WORKORDER_REP_CUS
 (WORKORDER_ID, WORKORDERNUMBER, ORDERDATE, REFERENCENUMBER, ORDERREMARK, DELIVERYDATE, SCHEDULEDDELIVERY, ORIGIN, DELIVERYDAY_DESC, SCHEDULEDDELIVERY_DESC, DOCKET, DELIVERFROM, CUSTOMERNUMBER, NAME, CUSTOMERMARKINGGARMENT, STREET, ZIPCODE, CITY, WCUSTOMERNUMBER, WNAME, WCUSTOMERMARKINGGARMENT, WSTREET, WZIPCODE, WCITY, WEARERNR, WEARERNAME, WEARERSEARCHNAME, WEARERFIRSTNAME, ADMIN, EMPLNR, CUPBOARD, LOCKER, GARMENTDISPENSER, DELIVERYPOINT, DEPARTMENT, DEPARTMENTNUMBER, NAMEONLABEL, CONSPOINT
, FUNCTIONX, WEARERREMARK, ROUTENUMBER, ROUTEDESCRIPTION, ROUTEDAYCODE, ROUTESTOPNR, DISTRICTDESCRIPTION, 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, PURCHORDERINFO)
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
, wok.deliverfrom
, cu.customernumber, cu.name, cu.customermarkinggarment
, address.street, address.zipcode, address.city
, null wcustomernumber, '' wname, '' wcustomermarkinggarment
, '' wstreet, '' wzipcode, '' 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, department.description Department
, department.departmentnumber
, w.emblemname NameOnLabel, distributionpoint.description ConsPoint--, wearerfunction.description FunctionX
, (select wf.description from wearerfunction wf where we.wearerfunction_id = wf.wearerfunction_id) FunctionX
, w.remark WearerRemark, route.routenumber, route.description RouteDescription
, (select day_desc.code from day_desc where day_desc.day_id = route.drivingday_id and day_desc.language_id = lan.language_id) RouteDayCode
, (select max(rstop.stopnumber) from routestop rstop where rstop.route_id = route.route_id and rstop.customer_id = cu.customer_id) RouteStopNr
, (select distr.description
   from district distr
   where distr.district_id = route.district_id) DistrictDescription
, wok.customerowned NotLaundryOwned, status.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
, plant.code plant_code, plant.name plant_name, plant.phoneno plant_phoneno, plant.faxno plant_faxno
, plant.email plant_email, plant.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 = plant.plant_id and ss.name = 'PRINTBARCODEONWORKORDER'), 1) Print_Barcode
, lan.code Language_code
, lpad((select sy.value from systemsetting sy where sy.plant_id = plant.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 max(concatenatewithblank(to_char(poh.purchaseordernumber), sup.name))
   from purchaseorderheader poh, purchaseorderline pol, supplier sup, workorderline wol
   where wol.workorder_id = wok.workorder_id
         and wol.purchaseorderline_id = pol.purchaseorderline_id
         and pol.purchaseorderheader_id = poh.purchaseorderheader_id
         and poh.supplier_id = sup.supplier_id
) PurchOrderInfo
from workorder wok   --left outer
            join weareremployment we  on wok.weareremployment_link_id = we.weareremployment_id --left outer join wearerfunction on we.wearerfunction_id = wearerfunction.wearerfunction_id
                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
                   left outer join deliverypointopeninghour dpoh on de.deliverypoint_id=dpoh.deliverypoint_id and dpoh.day_id = getabsdaynumber(wok.neededdate)
                  left outer join address adr on de.deliveryaddress_id=adr.address_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
                        join address on cu.visitaddress_id = address.address_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 employee emp on su.employee_id=emp.employee_id
 left outer join woreferencenumber worefnr on wok.woreferencenumber_id = worefnr.woreferencenumber_id
, status, businessunit bu, plant, address paddr--, SYSTEMSETTING SS
, languages lan
, reportparam rp
where wok.status_id = status.status_id
    and wok.businessunit_id = bu.businessunit_id
    and bu.plant_id = plant.plant_id
    and plant.address_id = paddr.address_id    --and ss.plant_id=plant.plant_id and ss.name='PRINTBARCODEONWORKORDER'
    and rp.number_value = wok.workorder_id
UNION
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
, wok.deliverfrom
, cu.customernumber, cu.name, cu.customermarkinggarment
, address.street, address.zipcode, address.city
, cus.customernumber wcustomernumber, cus.name wname, cus.customermarkinggarment wcustomermarkinggarment
, addr.street wstreet, addr.zipcode wzipcode, addr.city wcity
, null WearerNr
, null WearerName, null wearersearchname, null WearerFIRSTNAME
, null Admin, null EmplNr, null CupBoard, null
, null GarmentDispenser, (select de.code from deliverypoint de where de.deliverypoint_id = distributionpoint.deliverypoint_id) DeliveryPoint, department.description Department
, department.departmentnumber
, null NameOnLabel, distributionpoint.description ConsPoint--, wearerfunction.description FunctionX
, null FunctionX
, null WearerRemark, route.routenumber, route.description RouteDescription
, (select day_desc.code from day_desc where day_desc.day_id = route.drivingday_id and day_desc.language_id = lan.language_id) RouteDayCode
, (select max(rstop.stopnumber) from routestop rstop where rstop.route_id = route.route_id and rstop.customer_id = cu.customer_id) RouteStopNr
, (select distr.description
   from district distr
   where distr.district_id = route.district_id) DistrictDescription
, wok.customerowned NotLaundryOwned, status.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
, plant.code plant_code, plant.name plant_name, plant.phoneno plant_phoneno, plant.faxno plant_faxno
, plant.email plant_email, plant.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 = plant.plant_id and ss.name = 'PRINTBARCODEONWORKORDER'), 1) Print_Barcode
, lan.code Language_code
, lpad((select sy.value from systemsetting sy where sy.plant_id = plant.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
, null
, null
, null
, null
, null
, null
, null
, null
, null
, null
, wok.replacement
, wok.woreferencenumber_id
, worefnr.referencenumber woreferencenr
, worefnr.description worefnr_desc
, rp.reportparam_id
, (select max(concatenatewithblank(to_char(poh.purchaseordernumber), sup.name))
   from purchaseorderheader poh, purchaseorderline pol, supplier sup, workorderline wol
   where wol.workorder_id = wok.workorder_id
         and wol.purchaseorderline_id = pol.purchaseorderline_id
         and pol.purchaseorderheader_id = poh.purchaseorderheader_id
         and poh.supplier_id = sup.supplier_id
) PurchOrderInfo
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 address on cu.visitaddress_id=address.address_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 address  addr on cus.visitaddress_id=addr.address_id
 left outer join Systemuser su on wok.creationuser_id=su.systemuser_id
 left outer join employee emp on su.employee_id=emp.employee_id
 left outer join woreferencenumber worefnr on wok.woreferencenumber_id = worefnr.woreferencenumber_id
, status, businessunit bu, plant, address paddr--, SYSTEMSETTING SS
, languages lan
, reportparam rp
where wok.status_id = status.status_id
    and wok.businessunit_id = bu.businessunit_id
    and plant.address_id = paddr.address_id
    and bu.plant_id = plant.plant_id    --and ss.plant_id=plant.plant_id and ss.name='PRINTBARCODEONWORKORDER'
    and wok.weareremployment_link_id is null
    and rp.number_value = wok.workorder_id

/
create or replace view V_WORKORDER_SMG
 (WORKORDER_ID, WORKORDERNUMBER, ORDERDATE, REFERENCENUMBER, ORDERREMARK, DELIVERYDATE, SCHEDULEDDELIVERY, ORIGIN, DELIVERYDAY_DESC, SCHEDULEDDELIVERY_DESC, DOCKET, CUSTOMERNUMBER, NAME, CUSTOMERMARKINGGARMENT, STREET, ZIPCODE, CITY, WCUSTOMERNUMBER, WNAME, WCUSTOMERMARKINGGARMENT, WSTREET, WZIPCODE, WCITY, WEARERNR, WEARERNAME, WEARERSEARCHNAME, WEARERFIRSTNAME, ADMIN, EMPLNR, CUPBOARD, LOCKER, 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, INTPROCESSBU_CODE, INTPROCESSBU_DESC, PROCESSBU_CODE, PROCESSBU_DESC, STOCKNAME, ALLOWPHASEDELIVERY, APPROVALTIMESTAMP, APPROVALUSER, CREATIONTIMESTAMP, CREATEDBYUSER, SERVEMPLNAME)
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 =route.drivingday_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
, cu.customernumber, cu.name, cu.customermarkinggarment
, address.street, address.zipcode, address.city
, null wcustomernumber, '' wname, '' wcustomermarkinggarment
, '' wstreet, '' wzipcode, '' 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, department.description Department
, department.departmentnumber
, w.emblemname NameOnLabel, distributionpoint.description ConsPoint
, (select wf.description from wearerfunction wf where we.wearerfunction_id = wf.wearerfunction_id) FunctionX
, w.remark WearerRemark, route.routenumber, route.description RouteDescription
, wok.customerowned NotLaundryOwned, status.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
, plant.code plant_code, plant.name plant_name, plant.phoneno plant_phoneno, plant.faxno plant_faxno
, plant.email plant_email, plant.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
, lpad((select ss.value from systemsetting ss where ss.plant_id = plant.plant_id and ss.name = 'PRINTBARCODEONWORKORDER'), 3) Print_Barcode
, lan.code Language_code
, lpad((select sy.value from systemsetting sy where sy.plant_id = plant.plant_id and sy.name = 'PRINTREPLACEMENTSONWO'), 3) 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
, coalesce((select worefnr.referencenumber from  woreferencenumber worefnr where wok.woreferencenumber_id = worefnr.woreferencenumber_id),-1)
 woreferencenr
,coalesce((select worefnr.description from  woreferencenumber worefnr where wok.woreferencenumber_id = worefnr.woreferencenumber_id),'')
 worefnr_desc
,(select b.code from businessunit  b where b.businessunit_id=f_getintprocbuid(wok.workorder_id)) intprocessbu_code
, (select b.description from businessunit  b where b.businessunit_id=f_getintprocbuid(wok.workorder_id)) intprocessbu_desc
,(select b.code from businessunit  b where b.businessunit_id=f_getprocbuid(wok.workorder_id)) processbu_code
,(select b.description from businessunit  b where b.businessunit_id=f_getprocbuid(wok.workorder_id)) processbu_desc
,(select s.name from  stockroom s where wok.processingstockroom_id=s.stockroom_id ) stockname
,wok.allowphasedelivery
,wok.approvaltimestamp
,( select su.fullname from systemuser su where su.systemuser_id=wok.approvaluser_id)approvaluser
,wok.creationtimestamp
,( select su.fullname from systemuser su where su.systemuser_id=wok.creationuser_id)createdbyuser
,( select sevempl.name from employee sevempl where sevempl.employee_id= cu.serviceemployee_id) servemplname
  from workorder wok   --left outer
            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
                left outer join garmentdispenser ga on we.garmentdispenser_id=ga.garmentdispenser_id
                left outer join deliverypoint de on we.deliverypoint_id=de.deliverypoint_id
                   left outer join deliverypointopeninghour dpoh on de.deliverypoint_id=dpoh.deliverypoint_id and dpoh.day_id = getabsdaynumber(wok.neededdate)
                  left outer join address adr on de.deliveryaddress_id=adr.address_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
                        join address on cu.visitaddress_id = address.address_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 employee emp on su.employee_id=emp.employee_id
, status, businessunit bu, plant, address paddr
, languages lan
where wok.status_id = status.status_id
    and wok.businessunit_id = bu.businessunit_id
    and bu.plant_id = plant.plant_id
    and plant.address_id = paddr.address_id
UNION
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 =route.drivingday_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
, cu.customernumber, cu.name, cu.customermarkinggarment
, address.street, address.zipcode, address.city
, cus.customernumber wcustomernumber, cus.name wname, cus.customermarkinggarment wcustomermarkinggarment
, addr.street wstreet, addr.zipcode wzipcode, addr.city wcity
, null WearerNr
, null WearerName, null wearersearchname, null WearerFIRSTNAME
, null Admin, null EmplNr, null CupBoard, null
, null GarmentDispenser, (select de.code from deliverypoint de where de.deliverypoint_id = distributionpoint.deliverypoint_id) DeliveryPoint, department.description Department
, department.departmentnumber
, null NameOnLabel, distributionpoint.description ConsPoint
, null FunctionX
, null WearerRemark, route.routenumber, route.description RouteDescription
, wok.customerowned NotLaundryOwned, status.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
, plant.code plant_code, plant.name plant_name, plant.phoneno plant_phoneno, plant.faxno plant_faxno
, plant.email plant_email, plant.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
, lpad((select ss.value from systemsetting ss where ss.plant_id = plant.plant_id and ss.name = 'PRINTBARCODEONWORKORDER'), 3) Print_Barcode
, lan.code Language_code
, lpad((select sy.value from systemsetting sy where sy.plant_id = plant.plant_id and sy.name = 'PRINTREPLACEMENTSONWO'), 3) 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
, null
, null
, null
, null
, null
, null
, null
, null
, null
, null
, wok.replacement
, wok.woreferencenumber_id
, coalesce((select worefnr.referencenumber from  woreferencenumber worefnr where wok.woreferencenumber_id = worefnr.woreferencenumber_id),-1)
 woreferencenr
 ,coalesce((select worefnr.description from  woreferencenumber worefnr where wok.woreferencenumber_id = worefnr.woreferencenumber_id),'')
 worefnr_desc
,(select b.code from businessunit  b where b.businessunit_id=f_getintprocbuid(wok.workorder_id)) intprocessbu_code
 , (select b.description from businessunit  b where b.businessunit_id=f_getintprocbuid(wok.workorder_id)) intprocessbu_desc
 ,(select b.code from businessunit  b where b.businessunit_id=f_getprocbuid(wok.workorder_id)) processbu_code,
 (select b.description from businessunit  b where b.businessunit_id=f_getprocbuid(wok.workorder_id)) processbu_desc,
 (select s.name from  stockroom s where wok.processingstockroom_id=s.stockroom_id ) stockname
 ,wok.allowphasedelivery
 ,wok.approvaltimestamp
 ,( select su.fullname from systemuser su where su.systemuser_id=wok.approvaluser_id)approvaluser
 ,wok.creationtimestamp
  ,( select su.fullname from systemuser su where su.systemuser_id=wok.creationuser_id)createdbyuser
  ,( select sevempl.name from employee sevempl where sevempl.employee_id= cu.serviceemployee_id) servemplname
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 address on cu.visitaddress_id=address.address_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 address  addr on cus.visitaddress_id=addr.address_id
 left outer join Systemuser su on wok.creationuser_id=su.systemuser_id
 left outer join employee emp on su.employee_id=emp.employee_id
, status, businessunit bu, plant, address paddr
, languages lan
where wok.status_id = status.status_id
    and wok.businessunit_id = bu.businessunit_id
    and plant.address_id = paddr.address_id
    and bu.plant_id = plant.plant_id
    and wok.weareremployment_link_id is null

/
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 DW_BUDGET
 (CUSTOMER_ID, CUSTOMERNUMBER, DEPARTMENT_ID, DEPARTMENTNUMBER, YEAR, MONTH, WEEK, AMOUNT)
as select dep.customer_id, cu.customernumber, bu.department_link_id department_id, dep.departmentnumber,
       bu.year, bu.month, bu.week, bu.amount
from Budget bu, department dep, customer cu
where bu.department_link_id = dep.department_id and dep.customer_id = cu.customer_id

/
create or replace view DW_CIRCULATINGINVENTORY
 (CUSTOMER_ID, CUSTOMERNUMBER, DEPARTMENT_ID, DEPARTMENTNUMBER, PRODUCTCODE, SIZECODE, FINISHINGMETHODCODE, QUANTITY)
as select dep.customer_id, cu.customernumber, dp.department_id, dep.departmentnumber,
       p.code ProductCode, sd.code SizeCode, fm.code FinishingMethodCode,
       sum(rqa.quantity) Quantity
from ProductListPerDistribPoint plpd, distributionpoint dp, department dep, customer cu,
     product p, sizedefinition sd, finishingmethod fm, RentalQtyAdjustment rqa
where plpd.distributionpoint_id = dp.distributionpoint_id and dp.department_id = dep.department_id
      and dep.customer_id = cu.customer_id and plpd.product_id = p.product_id
      and plpd.sizedefinition_id = sd.sizedefinition_id and plpd.finishingmethod_id = fm.finishingmethod_id
      and plpd.productlistperdistribpoint_id = rqa.productlistperdistribpoint_id
      and rqa.adjustmentdate <= GETCURRENTDATE()
group by dep.customer_id, cu.customernumber, dp.department_id, dep.departmentnumber,
       p.code, sd.code, fm.code

/
create or replace view DW_CLUSTER
 (CLUSTER_ID, CODE, DESCRIPTION, TIMESTAMP)
as select cc.cluster_id, cc.code, cc.description, cc.timestamp
from CustomerCluster cc

/
create or replace view DW_CONTACTPERSON
 (CUSTOMER_ID, CUSTOMERNUMBER, CONTACTPERSON_ID, CONTACTPERSONNUMBER, NAME, PHONE, MOBILEPHONE, FAX, EMAIL, FUNCTIONCODE, FUNCTIONDESCRIPTION, TIMESTAMP)
as select cp.customer_id, cu.customernumber, cp.Contactperson_Id, cp.contactpersonnumber, cp.name, cp.phone
       , cp.mobilephone, cp.fax, cp.email, cpf.code FunctionCode
       , (select cpfd.description from Contactpersonfunction_Desc cpfd where cpfd.contactpersonfunction_id = cpf.contactpersonfunction_id and cpfd.language_id = cu.language_id) FunctionDescription
       , cp.timestamp
from ContactPerson cp, Customer cu, ContactPersonFunction cpf
where cp.customer_id = cu.customer_id and cp.contactpersonfunction_id = cpf.contactpersonfunction_id

/
create or replace view DW_CPL
 (CUSTOMER_ID, CUSTOMERNUMBER, DEPARTMENT_ID, DEPARTMENTNUMBER, DISTRIBUTIONPOINT_ID, DISTRIBUTIONPOINTNUMBER, PRODUCTCODE, SIZECODE, DATEACTIVE, DATEINACTIVE, DELIVERYSCHEME, FREQUENCY, RENEWAL)
as SELECT
        dep.customer_id,
        cust.customernumber,
        dp.department_id,
        dep.departmentnumber,
        plpd.distributionpoint_id,
        dp.distributionpointnumber,
        prod.code AS ProductCode,
        szd.code AS SizeCode,
        sdl.dateactive,
        sdl.dateinactive,
        ds.code AS DeliveryScheme,
        ds.frequency,
        sdl.renewal
FROM
     Standarddeliveryline sdl
JOIN Productlistperdistribpoint plpd ON sdl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
JOIN distributionpoint dp ON plpd.distributionpoint_id = dp.distributionpoint_id
JOIN department dep ON dp.department_id = dep.department_id
JOIN customer cust ON dep.customer_id = cust.customer_id
JOIN product prod ON plpd.product_id = prod.product_id
JOIN sizedefinition szd ON plpd.sizedefinition_id = szd.sizedefinition_id
JOIN deliveryscheme ds ON sdl.deliveryscheme_id = ds.deliveryscheme_id

/
create or replace view DW_CUSTOMER
 (CUSTOMER_ID, CUSTOMERNUMBER, BU_CODE, BU_DESC, PLANT_CODE, LEGACYCUSTOMERNUMBER, NAME, SEARCHNAME, LEGALNAME, MAILADDRESS, MAILZIPCODE, MAILCITY, VISITADDRESS, VISITZIPCODE, VISITCITY, STATE, INVOICEADDRESS, INVOICEZIPCODE, INVOICECITY, COUNTRYCODE, PHONENO, FAXNO, EMAIL, MARKETSEGMENTCODE, REMARK, DATEACTIVE, DATEINACTIVE, ACTIVE, QUALITYGRADECODE, FIRSTISSUEGRADE, SERVICETEAMCODE, SALESAREACODE, CONCERNCODE, PAYMENTTERMSCODE, DEBTOR_ID, DEBTORNUMBER, VATNUMBER, INVOICECOUPLINGCODE
, CLUSTER_ID, CLUSTERCODE, MASTERACCOUNT, MASTERACCOUNT_ID, MASTERACCOUNTNUMBER, PLANTDEPARTMENTCODE, CHAINCODE, CURRENCYCODE, LANGUAGECODE, SERVICEEMPLOYEENUMBER, SERVICEEMPLOYEENAME, SALESEMPLOYEENUMBER, SALESEMPLOYEENAME, ACCOUNTMANAGERNUMBER, ACCOUNTMANAGERNAME, CONTACTPERSON_ID, LOSTREASON_ID, TIMESTAMP, SICCODE, INVOICEFREQUENCY, INVOICEFREQUENCYDESCRIPTION, INVOICEREMARK, LOSTREASONCODE, LOSTREASONDESCRIPTION)
as select cu.customer_id, cu.customernumber, bu.code bu_code, bu.description bu_desc, pl.code plant_code,
       cu.legacycustomernumber, cu.name, cu.searchname, cu.legalname,
       mad.street MailAddress, mad.zipcode MailZipcode, mad.city MailCity,
       vad.street VisitAddress, vad.zipcode VisitZipcode, vad.city VisitCity, vad.state State,
       iad.street InvoiceAddress, iad.zipcode InvoiceZipcode, iad.city InvoiceCity,
       (select co.code from Country co where co.country_id = cu.country_id) CountryCode,
       cu.phoneno, cu.faxno, cu.email,
       (select ms.code from Marketsegment ms where cu.marketsegment_id = ms.marketsegment_id) MarketSegmentCode,
       cu.remark, cu.dateactive, cu.dateinactive, cu.active,
       (select qg.code from QualityGrade qg where qg.qualitygrade_id = cu.qualitygrade_id) QualityGradeCode,
       (select fg.code from QualityGrade fg where fg.qualitygrade_id = cu.firstissuegrade_id) FirstIssueGrade,
       (select st.code from ServiceTeam st where cu.serviceteam_id = st.serviceteam_id) ServiceTeamCode,
       (select sa.code from SalesArea sa where cu.salesarea_id = sa.salesarea_id) SalesAreaCode,
       cu.priceconcerncode ConcernCode,
       (select pt.code from customerbillinginfo cbi, paymentterms pt where cu.customer_id=cbi.customer_id and cbi.paymentterms_id=pt.paymentterms_id) PaymentTermsCode,
       cu.debtor_id, (select deb.customernumber from customer deb where cu.debtor_id = deb.customer_id) DebtorNumber,
       cu.vatnumber, cu.invoicecouplingcode, --cu.cluster_id,
       (select  min (cc.cluster_id) from customer cn left outer join customerspercluster cpc on cn.customer_id=cpc.customer_id,
        CustomerCluster cc where cpc.cluster_id = cc.cluster_id and cn.customer_id=cu.customer_id)cluster_id,
       --(select cc.code from CustomerCluster cc where cu.cluster_id = cc.cluster_id) ClusterCode,
       (select min(cc.code) from customer cn left outer join customerspercluster cpc on cn.customer_id=cpc.customer_id,
        CustomerCluster cc where cpc.cluster_id = cc.cluster_id and cn.customer_id=cu.customer_id) ClusterCode,
       cu.masteraccount, cu.masteraccount_id,
       (select ma.customernumber from customer ma where cu.masteraccount_id = ma.customer_id) MasterAccountNumber,
       (select pd.code from PlantDepartment pd where cu.plantdepartment_id = pd.plantdepartment_id) PlantDepartmentCode,
       (select ch.code from Chain ch where cu.chain_id = ch.chain_id) ChainCode,
       (select crr.code from Currency crr where cu.currency_id = crr.currency_id) CurrencyCode,
       lan.code LanguageCode, emp.employeenumber ServiceEmployeeNumber, emp.name ServiceEmployeeName,
       sem.employeenumber SalesEmployeeNumber, sem.name SalesEmployeeName,
       acm.employeenumber AccountManagerNumber, acm.name AccountManagerName,
       cpc.contactperson_id, cpc.lostreason_id, cu.timestamp
       , cu.siccode,
       ifq.invoicefrequencynumber AS InvoiceFrequency, ifqd.DESCRIPTION InvoiceFrequencyDescription,
       (SELECT cbic.DESCRIPTION FROM customerbillingcomment cbic WHERE cbic.customer_id = cu.customer_id AND cbic.type = 1 AND cbic.startdate <= getcurrentdate AND cbic.enddate>=getcurrentdate AND Rownum = 1) InvoiceRemark,
       glr.code AS LostReasonCode,
       (select glrd.description from gainlostreason_desc glrd where glr.gainlostreason_id = glrd.gainlostreason_id AND glrd.language_id = cu.language_id) LostReasonDescription
from Customer cu
              left outer join address iad on iad.address_id = cu.invoiceaddress_id
              left outer join Employee emp on cu.serviceemployee_id = emp.employee_id
              LEFT OUTER JOIN invoicefrequency ifq ON cu.invoicefrequency_id = ifq.Invoicefrequency_Id
              LEFT OUTER JOIN invoicefrequency_desc ifqd ON cu.invoicefrequency_id = ifqd.invoicefrequency_id AND cu.language_id = ifqd.language_id
     , BusinessUnit bu, Plant pl, Address mad, Address vad,
     Languages lan, ContractsPerCustomer cpc
              left outer join Employee sem on cpc.salesemployee_id = sem.employee_id
              left outer join Employee acm on cpc.accountmanager_id = acm.employee_id
              LEFT OUTER JOIN gainlostreason glr ON cpc.gainreason_id = glr.gainlostreason_id
where cu.defaultbusinessunit_id = bu.businessunit_id and bu.plant_id = pl.plant_id and
      cu.mailaddress_id = mad.address_id and cu.visitaddress_id = vad.address_id and
      cpc.customer_id = cu.customer_id and
      cu.language_id = lan.language_id

/
create or replace view DW_CUSTOMERCHARGE
 (CUSTOMER_ID, CUSTOMERNUMBER, SPECIALCHARGE_ID, SPECIALCHARGECODE, PERCENTAGE)
as SELECT
       css.customer_id,
       c.customernumber,
       css.specialcharge_id,
       csp.code AS SpecialChargeCode,
       /*SSB modified for order 20010986 new Special Charge calculation using functions in PACK_PRICE
			 (
        CASE WHEN css.overruled = 'Y' THEN
             CASE WHEN css.startdate <= getcurrentdate THEN
             css.newspecificpercentage
             ELSE
             css.oldspecificpercentage
             END
        ELSE
             CASE WHEN css.startdate <= getcurrentdate THEN
             csp.Newpercentage
             ELSE
             csp.Oldpercentage
             END
        END
       )
			 */
			 pack_price.SpecialCharge_Percentage(css.customer_id, css.specialcharge_id, getcurrentdate()) Percentage
FROM
       Customerspecialcharge css
LEFT JOIN Customer c ON css.customer_id = c.customer_id
JOIN specialcharge csp ON css.specialcharge_id = csp.specialcharge_id

/
create or replace view DW_CUSTOMERSPERCONTACTPERSON
 (CUSTOMER_ID, CUSTOMERNUMBER, EMPLOYEENUMBER, NAME)
as select cu.customer_id, cu.customernumber, emp.employeenumber, emp.name
from Customer cu, Employee emp, Contractspercustomer cpc
where cu.customer_id = cpc.customer_id and cpc.salesemployee_id = emp.employee_id

/
create or replace view DW_DELIVERYHISTORY
 (BUSINESSUNITCODE, CUSTOMER_ID, CUSTOMERNUMBER, DEPARTMENT_ID, DEPARTMENTNUMBER, PRODUCTCODE, SIZECODE, FINISHINGMETHODCODE, DELIVERYDATE, YEAR, WEEK, DAYNUMBER, AMOUNTDELIVERED, TIMESTAMP)
as select bu.code BusinessUnitCode, dh.customer_link_id Customer_ID,
       (select cu.customernumber from customer cu where dh.customer_link_id = cu.customer_id) CustomerNumber,
       dh.department_link_id Department_ID,
       (select dep.departmentnumber from department dep where dh.department_link_id = dep.department_id) DepartmentNumber,
       (select p.code from product p where dh.product_link_id = p.product_id) ProductCode,
       (select sd.code from sizedefinition sd where dh.sizedefinition_link_id = sd.sizedefinition_id) SizeCode,
       (select fm.code from finishingmethod fm where dh.finishingmethod_id = fm.finishingmethod_id) FinishingMethodCode,
       dh.deliverydate, dh.year, dh.week, dh.daynumber, dh.amountdelivered, dh.timestamp
from DeliveryHistory dh, businessunit bu
where dh.processbusinessunit_id = bu.businessunit_id

/
create or replace view DW_DELIVERYNOTE
 (BUSINESSUNITCODE, CUSTOMER_ID, CUSTOMERNUMBER, DEPARTMENT_ID, DEPARTMENTNUMBER, PACKINGNOTE_ID, NOTENUMBER, DELIVERYDATE, YEAR, WEEK, DAYNUMBER, TIMESTAMP)
as select bu.code BusinessUnitCode, dep.customer_id, cu.customernumber, dp.department_id, dep.departmentnumber,
       pn.packingnote_id, pn.notenumber, pn.deliverydate, pn.year, pn.week, pn.daynumber, pn.timestamp
from PackingNote pn, businessunit bu, distributionpoint dp, department dep, customer cu, status st
where pn.processbusinessunit_id = bu.businessunit_id and pn.distributionpoint_id = dp.distributionpoint_id and
      dp.department_id = dep.department_id and dep.customer_id = cu.customer_id
      and pn.status_id = st.status_id and st.statustype = 'PN' and st.code = '30'

/
create or replace view DW_DELIVERYNOTELINE
 (PACKINGNOTELINE_ID, PACKINGNOTE_ID, PRODUCTCODE, SIZECODE, FINISHINGMETHODCODE, DELIVEREDAMOUNT, TIMESTAMP)
as select pnl.packingnoteline_id, pnl.packingnote_id, p.code ProductCode, sd.code SizeCode, fm.code FinishingMethodCode,
       pnl.deliveredamount, pnl.timestamp
from PackingNoteLine pnl, product p, sizedefinition sd, finishingmethod fm
where pnl.product_id = p.product_id and pnl.sizedefinition_id = sd.sizedefinition_id and pnl.finishingmethod_id = fm.finishingmethod_id

/
create or replace view DW_DEPARTMENT
 (CUSTOMER_ID, CUSTOMERNUMBER, DEPARTMENT_ID, DEPARTMENTNUMBER, DESCRIPTION, OCCUPANCY, STANDARDPACKAMOUNT, LEGACYDEPARTMENTCODE, TIMESTAMP)
as select dep.customer_id, cu.customernumber, dep.department_id, dep.departmentnumber, dep.description,
       dep.occupancy, dep.standardpackamount, dep.legacydepartmentcode, dep.timestamp
from Customer cu, Department dep
where cu.customer_id = dep.customer_id

/
create or replace view DW_EMBLEMTEMPLATE
 (EMBLEMTEMPLATE_ID, CUSTOMER_ID, CUSTOMERNUMBER, CODE, DESCRIPTION, TIMESTAMP)
as select et.emblemtemplate_id, et.customer_id, cu.customernumber, et.code, et.description, et.timestamp
from EmblemTemplate et, customer cu
where et.customer_id = cu.customer_id

/
create or replace view DW_EMBLEMTEMPLATELINE
 (EMBLEMTEMPLATE_ID, EMBLEMTEMPLATECODE, EMBLEMTEMPLATELINE_ID, PRODUCTCODE, SIZECODE, DESCRIPTION, PLACEMENTCODE, PLACEMENTDESCRIPTION, EMBLEMTYPE, TIMESTAMP)
as select etl.emblemtemplate_id, et.code EmblemTemplateCode, etl.emblemtemplateline_id,
       (select p.code from product p where etl.product_id = p.product_id) ProductCode,
       (select sd.code from sizedefinition sd where etl.sizedefinition_id = sd.sizedefinition_id) SizeCode,
       etl.description,
       (select pl.code from Placement pl where etl.placement_id = pl.placement_id) PlacementCode,
       (select pld.description from Placement_Desc pld, customer cu where etl.placement_id = pld.placement_id
                            and et.customer_id = cu.customer_id and pld.language_id = cu.language_id) PlacementDescription,
       etl.emblemtype, etl.timestamp
from EmblemTemplateLine etl, EmblemTemplate et
where et.emblemtemplate_id = etl.emblemtemplate_id

/
create or replace view DW_GAINLOSSREASON
 (GAINLOSTREASON_ID, CODE, TIMESTAMP)
as select glr.gainlostreason_id, glr.code, glr.timestamp
from GainLostReason glr

/
create or replace view DW_LOCKER
 (CUSTOMER_ID, CUSTOMERNUMBER, LOCKER_ID, BANK, LOCKER, LOCKERSTATUS, WEAREREMPLOYMENT_ID, WEARERNUMBER, TIMESTAMP)
as select lo.customer_id,
       (select cu.customernumber from customer cu where cu.customer_id = lo.customer_id) CustomerNumber,
       lo.locker_id, lo.bank, lo.locker, lo.lockerstatus,
       we.weareremployment_id, w.wearernumber, lo.timestamp
from Locker lo
            left outer join weareremployment we
                                    join wearer w on we.wearer_id = w.wearer_id
            on we.locker_id = lo.locker_id

/
create or replace view DW_PATIENTDAY
 (CUSTOMER_ID, CUSTOMERNUMBER, DEPARTMENT_ID, DEPARTMENTNUMBER, YEAR, MONTH, WEEK, PATIENTS, PATIENTDAYS)
as select dep.Customer_ID, cu.customernumber, dep.Department_Id, dep.departmentnumber, pd.year,
       pd.month, pd.week, pd.patients, pd.patientdays
from Patientday pd, Distributionpoint dp, Department dep, Customer cu
where pd.distributionpoint_link_id = dp.distributionpoint_id and dp.department_id = dep.department_id
      and dep.customer_id = cu.customer_id

/
create or replace view DW_PLPC
 (CUSTOMER_ID, CUSTOMERNUMBER, PRODUCTCODE, SIZECODE, FINISHINGMETHODCODE, DATEACTIVE, DATEINACTIVE, PRODUCTLISTPERCUSTOMER_ID, EMBLEMTEMPLATE_ID, WASHPRICE, WASHPRICESTARTDATE, RENTPRICE, RENTPRICESTARTDATE, SALESPRICE, SALESPRICESTARTDATE, BILLINGMETHOD, TYPEOFMERCHANDISE, SOILWEIGHT, SOILCOUNTMETHOD, CLEANCOUNT, TIMESTAMP, WASHDISCOUNT, WASHDISCOUNTSTARTDATE, RENTDISCOUNT, RENTDISCOUNTSTARTDATE)
as select plpc.customer_id--, cu.customernumber
       , (select cu.customernumber from customer cu where plpc.customer_id = cu.customer_id) customernumber
       , p.code ProductCode
       --, sd.code SizeCode, fm.code FinishingMethodCode
       , (select sd.code from sizedefinition sd where plpc.sizedefinition_id = sd.sizedefinition_id) SizeCode
       , (select fm.code from finishingmethod fm where plpc.finishingmethod_id = fm.finishingmethod_id) FinishingMethodCode
       , plpc.dateactive, plpc.dateinactive, plpc.productlistpercustomer_id, plpc.emblemtemplate_id
       , (select cwp.price from customerwashprice cwp
                      where cwp.productlistpercustomer_id = plpc.productlistpercustomer_id
                            and cwp.pricetype = 1
                            and cwp.startdate = (select max(cwp2.startdate) from customerwashprice cwp2
                                                      where cwp2.productlistpercustomer_id = plpc.productlistpercustomer_id
                                                            and cwp2.pricetype = 1 and cwp2.startdate <= GETCURRENTDATE())) WashPrice
       , (select max(cwp3.startdate) from customerwashprice cwp3
                                     where cwp3.productlistpercustomer_id = plpc.productlistpercustomer_id
                                           and cwp3.pricetype = 1 and cwp3.startdate <= GETCURRENTDATE()) WashPriceStartDate
       , (select crp.price from customerrentprice crp
                      where crp.productlistpercustomer_id = plpc.productlistpercustomer_id and crp.typeofrent = 1
                            and crp.startdate = (select max(crp2.startdate) from customerrentprice crp2
                                                  where crp2.productlistpercustomer_id = plpc.productlistpercustomer_id
                                                        and crp2.typeofrent = 1 and crp2.startdate <= GETCURRENTDATE())) RentPrice
       , (select max(crp3.startdate) from customerrentprice crp3
                                     where crp3.productlistpercustomer_id = plpc.productlistpercustomer_id
                                           and crp3.typeofrent = 1 and crp3.startdate <= GETCURRENTDATE()) RentPriceStartDate
       , (select csp.price from customersalesprice csp
                      where csp.customer_id = plpc.customer_id and csp.product_id = plpc.product_id and csp.sizedefinition_id = plpc.sizedefinition_id
                            and csp.startdate = (select max(csp2.startdate) from customersalesprice csp2
                                                      where csp2.customer_id = plpc.customer_id and csp2.product_id = plpc.product_id and csp2.sizedefinition_id = plpc.sizedefinition_id
                                                            and csp2.startdate <= GETCURRENTDATE())) SalesPrice
       , (select max(csp3.startdate) from customersalesprice csp3
                                     where csp3.customer_id = plpc.customer_id and csp3.product_id = plpc.product_id and csp3.sizedefinition_id = plpc.sizedefinition_id
                                           and csp3.startdate <= GETCURRENTDATE()) SalesPriceStartDate
       , plpc.billingmethod, p.typeofmerchandise, plpc.soilweight, plpc.soilcountmethod, plpc.cleancount, plpc.timestamp,
       cwd.discount AS WashDiscount, cwd.startdate AS WashDiscountStartDate, crd.discount AS RentDiscount, crd.Startdate AS RentDiscountStartDate
from ProductListPerCustomer plpc
LEFT OUTER JOIN customerwashdiscount cwd ON plpc.productlistpercustomer_id = cwd.productlistpercustomer_id
LEFT OUTER JOIN customerrentdiscount crd ON plpc.productlistpercustomer_id = crd.productlistpercustomer_id
,product p--, Customer cu, sizedefinition sd, finishingmethod fm
where plpc.product_id = p.product_id
      --and plpc.customer_id = cu.customer_id and plpc.sizedefinition_id = sd.sizedefinition_id and plpc.finishingmethod_id = fm.finishingmethod_id

/
create or replace view DW_ROUTE
 (PLANT_ID, PLANTCODE, ROUTE_ID, ROUTENUMBER, DESCRIPTION, DRIVINGDAY, DRIVERNUMBER, DRIVERNAME, TRUCKCODE, TRUCKDESCRIPTION, STARTTIME, ENDTIME, TIMESTAMP, ACTIVE)
as select ro.plant_id,
       (select pl.code from Plant pl where ro.plant_id = pl.plant_id) PlantCode,
       ro.route_id, ro.routenumber, ro.description,
       (select d.daynumber from Day d where d.day_id = ro.drivingday_id) DrivingDay,
       dr.employeenumber DriverNumber, dr.name DriverName,
       tr.code TruckCode, tr.description TruckDescription,
       ro.starttime, ro.endtime, ro.timestamp, ro.active
from Route ro
           left outer join Employee dr on ro.driver_id = dr.employee_id
           left outer join Truck tr on ro.truck_id = tr.truck_id

/
create or replace view DW_ROUTESTOP
 (ROUTE_ID, ROUTENUMBER, ROUTESTOP_ID, STOPNUMBER, CUSTOMER_ID, CUSTOMERNUMBER, DELIVERYPOINTCODE, STOPTYPE, TRAVELMINUTES, SERVICEMINUTES, ROUTELISTINSTRUCTIONS, RETURNROUTE_ID, RETURNROUTENUMBER, RETURNSTOP_ID, RETURNSTOPNUMBER, DELIVERYSCHEMECODE, FREQUENCY, OFFSETWEEK, CONTACTPERSON_ID, CONTACTPERSONNUMBER, TIMESTAMP)
as select rs.route_id, ro.routenumber, rs.routestop_id, rs.stopnumber, rs.customer_id, --cu.customernumber,
       (select cu.customernumber from customer cu where rs.customer_id = cu.customer_id) customernumber,
       (select dp.code from DeliveryPoint dp where rs.deliverypoint_id = dp.deliverypoint_id) DeliveryPointCode,
       rs.stoptype, rs.travelminutes, rs.serviceminutes, rs.routelistinstructions, rs.returnroute_id,
       --rr.routenumber ReturnRouteNumber,
       (select rr.routenumber from Route rr where rs.returnroute_id = rr.route_id) ReturnRouteNumber,
       rrs.routestop_id ReturnStop_ID, rrs.stopnumber ReturnStopNumber,
       (select min(ds.code) from deliveryscheme ds, deliveryschemesperstop dss
        where ds.deliveryscheme_id = dss.deliveryscheme_id and dss.routestop_id = rs.routestop_id and dss.customer_id = rs.customer_id
              and ro.drivingday_id = dss.day_id and ds.frequency = (select min(ds1.frequency)
                                   from deliveryscheme ds1, deliveryschemesperstop dss1
                                   where ds1.deliveryscheme_id = dss1.deliveryscheme_id and dss1.routestop_id = rs.routestop_id
                                         and dss1.customer_id = rs.customer_id and ro.drivingday_id = dss1.day_id
                                 )) DeliverySchemeCode,
       (select min(ds2.frequency) from deliveryscheme ds2, deliveryschemesperstop dss2
                                   where ds2.deliveryscheme_id = dss2.deliveryscheme_id and dss2.routestop_id = rs.routestop_id
                                         and dss2.customer_id = rs.customer_id and ro.drivingday_id = dss2.day_id
                                 ) Frequency,
       (select min(ds3.offsetweek) from deliveryscheme ds3, deliveryschemesperstop dss3
        where ds3.deliveryscheme_id = dss3.deliveryscheme_id and dss3.routestop_id = rs.routestop_id and dss3.customer_id = rs.customer_id
              and dss3.day_id = ro.drivingday_id and ds3.code =
                                 (select min(ds4.code) from deliveryscheme ds4, deliveryschemesperstop dss4
                                  where ds4.deliveryscheme_id = dss4.deliveryscheme_id and dss4.routestop_id = rs.routestop_id
                                         and dss4.customer_id = rs.customer_id and dss4.day_id = ro.drivingday_id and ds4.frequency =
                                         (select min(ds5.frequency)
                                          from deliveryscheme ds5, deliveryschemesperstop dss5
                                          where ds5.deliveryscheme_id = dss5.deliveryscheme_id and dss5.routestop_id = rs.routestop_id
                                                and dss5.customer_id = rs.customer_id and ro.drivingday_id = dss5.day_id
                                 )
                                 )) OffsetWeek,
       rs.contactperson_id,
       (select cp.contactpersonnumber from ContactPerson cp where rs.contactperson_id = cp.contactperson_id) ContactPersonNumber,
       rs.timestamp
from RouteStop rs, Route ro, --Route rr, Customer cu,
     RouteStop rrs
where rs.route_id = ro.route_id and --rs.customer_id = cu.customer_id --and rs.returnroute_id = rr.route_id and
      rrs.route_id = rs.returnroute_id and rrs.customer_id = rs.customer_id
      and ((rs.deliverypoint_id is null and rrs.routestop_id in (select min(rrs1.routestop_id) from routestop rrs1 where rrs1.route_id = rs.returnroute_id and rrs1.customer_id = rs.customer_id))
          or (rrs.deliverypoint_id = rs.deliverypoint_id))

/
create or replace view DW_SQITEMSINCIRCULATION
 (BUSINESSUNITCODE, YEAR, WEEK, CUSTOMER_ID, CUSTOMERNUMBER, DEPARTMENT_ID, DEPARTMENTNUMBER, WEAREREMPLOYMENT_ID, WEARERNUMBER, PRODUCTCODE, SIZECODE, FINISHINGCODE, TOTALCIRCINV, QTYRENTEDPERPIECE, TIMESTAMP)
as select bu.code BusinessUnitCode, sqh.year, sqh.week, sq.customer_link_id Customer_ID,
       (select cu.customernumber from Customer cu where sq.customer_link_id = cu.customer_id) CustomerNumber,
       sq.department_link_id department_id,
       (select dep.departmentnumber from Department dep where sq.department_link_id = dep.department_id) DepartmentNumber,
       sq.weareremployment_link_id WearerEmployment_ID,
       (select w.wearernumber from weareremployment we, wearer w where sq.weareremployment_link_id = we.weareremployment_id and we.wearer_id = w.wearer_id) WearerNumber,
       (select p.code from Product p where sq.product_link_id = p.product_id) ProductCode,
       (select sd.code from Sizedefinition sd where sq.sizedefinition_link_id = sd.sizedefinition_id) SizeCode,
       (select fm.code from Finishingmethod fm where sq.finishingmethod_id = fm.finishingmethod_id) FinishingCode,
       sq.totalcircinv, sq.qtyrentedperpiece, sq.timestamp
from SQItemInCirculation sq, StatusQuoHeader sqh, businessunit bu
where sq.statusquoheader_id = sqh.statusquoheader_id and sqh.processbusinessunit_id = bu.businessunit_id

/
create or replace view DW_WEARER
 (CUSTOMER_ID, CUSTOMERNUMBER, WEARER_ID, WEARERNUMBER, WEAREREMPLOYMENT_ID, SEQUENCENUMBER, FULLNAME, SEARCHNAME, FIRSTNAME, ADMINNUMBER, GENDER, DATEACTIVE, DATEINACTIVE, REMARK, DEPARTMENT_ID, DEPARTMENTNUMBER, WEARERFUNCTIONCODE, LOCKER_ID, BANK, LOCKER, CASE)
as select w.customer_id,
       (select cu.customernumber from customer cu where w.customer_id = cu.customer_id) CustomerNumber,
       we.wearer_id, w.wearernumber, we.weareremployment_id, we.sequencenumber,
       w.fullname, w.searchname, w.firstname, w.customeremployeenumber AdminNumber,
       w.sex Gender, w.dateactive, w.dateinactive, w.remark,
       dp.department_id, dep.departmentnumber,
       (select wf.code from wearerfunction wf where we.wearerfunction_id = wf.wearerfunction_id) WearerFunctionCode,
       we.locker_id, l.bank, l.locker,
       case
       when w.timestamp > we.timestamp then w.timestamp
       else we.timestamp
       end case
from Wearer w, WearerEmployment we
     left outer join Locker l on we.locker_id = l.locker_id
     , DistributionPoint dp, Department dep
where we.wearer_id = w.wearer_id and we.distributionpoint_id = dp.distributionpoint_id and dp.department_id = dep.department_id

/
create or replace view DW_WEARERINVENTORY
 (WEAREREMPLOYMENT_ID, WEARERINVENTORY_ID, PRODUCTCODE, SIZECODE, FINISHINGMETHODCODE, EMBLEMTEMPLATE_ID, SPECIALGRADECODE, DATEACTIVE, DATEINACTIVE, MAXINVENTORY, TIMESTAMP)
as select wi.weareremployment_id, wi.wearerinventory_id,
       ( select p.code from product p where wi.product_id = p.product_id ) ProductCode,
       ( select sd.code from sizedefinition sd where wi.sizedefinition_id = sd.sizedefinition_id ) SizeCode,
       ( select fm.code from finishingmethod fm where wi.finishingmethod_id = fm.finishingmethod_id ) FinishingMethodCode,
       wi.emblemtemplate_id,
       ( select qg.code from qualitygrade qg where wi.specialgrade_id = qg.qualitygrade_id ) SpecialGradeCode,
       wi.dateactive, wi.dateinactive, wi.maxinventory, wi.timestamp
from WearerInventory wi

/
create or replace view DW_WORKORDER
 (WORKORDER_ID, WORKORDERNUMBER, WEAREREMPLOYMENT_ID, CUSTOMER_ID, CUSTOMERNUMBER, WEARERNUMBER, BUSINESSUNITCODE, STATUSCODE, ENTRYDATE, REQUESTDATE, NEEDEDDATE, COMPLETIONDATE, REASONCODE, REFERENCENUMBER, TIMESTAMP)
as select wo.workorder_id, wo.workordernumber, wo.weareremployment_link_id WearerEmployment_ID,
       w.customer_id, cu.customernumber, w.wearernumber,
       (select bu.code from businessunit bu where wo.businessunit_id = bu.businessunit_id) BusinessUnitCode,
       (select st.code from status st where wo.status_id = st.status_id) StatusCode,
       wo.entrydate, wo.requestdate, wo.neededdate, wo.completiondate,
       (select rc.code from reasoncode rc where wo.reasoncode_id = rc.reasoncode_id) ReasonCode,
       wo.referencenumber, wo.timestamp
from WorkOrder wo, Weareremployment we, wearer w, customer cu
where w.customer_id = cu.customer_id and we.wearer_id = w.wearer_id
      and wo.weareremployment_link_id = we.weareremployment_id
      and wo.origin not in (6, 7)

/
create or replace view DW_WORKORDERLINE
 (WORKORDER_ID, WORKORDERNUMBER, WORKORDERLINE_ID, PRODUCTCODE, SIZECODE, FINISHINGMETHODCODE, REQUESTEDGRADECODE, EMBLEMTEMPLATE_ID, QUANTITYORDERED, QUANTITYFILLED, QUANTITYCANCELLED, COMPLETIONDATE, TIMESTAMP)
as select wol.workorder_id, wo.workordernumber,
       wol.workorderline_id,
       (select p.code from product p where wol.product_link_id = p.product_id) ProductCode,
       (select sd.code from sizedefinition sd where wol.sizedefinition_link_id = sd.sizedefinition_id) SizeCode,
       (select fm.code from finishingmethod fm where wol.finishingmethod_id = fm.finishingmethod_id) FinishingMethodCode,
       (select qg.code from qualitygrade qg where wol.requestedgrade_id = qg.qualitygrade_id) RequestedGradeCode,
       wol.emblemtemplate_id, wol.quantityordered, wol.quantityfilled, wol.quantitycancelled, wol.completiondate, wol.timestamp
from WorkOrderLine wol, WorkOrder wo
where wol.workorder_id = wo.workorder_id and wo.weareremployment_link_id is not null and wo.origin not in (6, 7)

/
create or replace view DW_WORKORDERLINEEMBLEM
 (WORKORDER_ID, WORKORDERNUMBER, WORKORDERLINE_ID, WORKORDERLINEEMBLEM_ID, EMBLEMTEMPLATELINE_ID, EMBLEMTEMPLATECODE, PRODUCTCODE, SIZECODE, EMBLEMPRODUCTCODE, EMBLEMSIZECODE, PLACEMENTCODE, PLACEMENTDESCRIPTION, TIMESTAMP)
as select wol.workorder_id, wo.workordernumber, wole.workorderline_id, wole.workorderlineemblem_id, wole.emblemtemplateline_id,
       (select et.code from emblemtemplate et, emblemtemplateline etl where wole.emblemtemplateline_id = etl.emblemtemplateline_id and etl.emblemtemplate_id = et.emblemtemplate_id) EmblemTemplateCode,
       (select p.code from product p where wol.product_link_id = p.product_id) ProductCode,
       (select sd.code from sizedefinition sd where wol.sizedefinition_link_id = sd.sizedefinition_id) SizeCode,
       coalesce((select pe.code from product pe where wole.product_id = pe.product_id),
                (select p.code from product p, emblemtemplateline etl where wole.Emblemtemplateline_Id = etl.emblemtemplateline_id and etl.product_id = p.product_id)) EmblemProductCode,
       coalesce((select sde.code from sizedefinition sde where wole.sizedefinition_id = sde.sizedefinition_id),
                (select sde2.code from sizedefinition sde2, emblemtemplateline etl where wole.Emblemtemplateline_Id = etl.emblemtemplateline_id and etl.sizedefinition_id = sde2.sizedefinition_id)) EmblemSizeCode,
       (select pl.code from placement pl where wole.placement_id = pl.placement_id) PlacementCode,
       (select pld.description from customer cu, placement_desc pld where wole.placement_id = pld.placement_id and pld.language_id = cu.language_id and wo.customer_link_id = cu.customer_id) PlacementDescription,
       wole.timestamp
from workorder wo, WorkOrderLine wol, Workorderlineemblem wole
where wo.workorder_id = wol.workorder_id and wol.workorderline_id = wole.workorderline_id
      and wo.weareremployment_link_id is not null and wo.origin not in (6, 7)

/
create or replace view ERP_TRANSACTION_LOG
 (ERP_TABLENAME, TRANSFER_ID, TRANSFER_STATUS, TEXT, PROCESS_STATUS, TIMESTAMP)
as select 'ERP_I_AR_BALANCES_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_i_ar_balances_log
union all
select 'ERP_I_CONSUMPTIONPOINT_LOG' erp_tablename, transfer_id, transfer_status, text,
       process_status, timestamp
from   erp_i_consumptionpoint_log
union all
select 'ERP_I_CONTACTPERSON_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_i_contactperson_log
union all
select 'ERP_I_COSTCENTER_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_i_costcenter_log
union all
select 'ERP_I_CUSTOMER_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_i_customer_log
union all
select 'ERP_I_DC_ISSUE_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_i_dc_issue_log
union all
select 'ERP_I_DELIVERYPOINT_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_i_deliverypoint_log
union all
select 'ERP_I_DEPARTMENT_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_i_department_log
union all
select 'ERP_I_EMPLOYEE_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_i_employee_log
union all
select 'ERP_I_LEDGERPRODUCT_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_i_ledgerproduct_log
union all
select 'ERP_I_PRODUCT_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_i_product_log
union all
select 'ERP_I_PURCHASEORDER_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_i_purchaseorder_log
union all
select 'ERP_I_SIZE_LOG' erp_tablename, transfer_id, transfer_status, text, process_status, timestamp
from   erp_i_size_log
union all
select 'ERP_I_STOCKDEFPERITEM_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_i_stockdefperitem_log
union all
select 'ERP_I_SUPPLIER_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_i_supplier_log
union all
select 'ERP_I_SUPPLIERPRODUCT_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_i_supplierproduct_log
union all
select 'ERP_I_WEIGHINGCATEGORY_LOG' erp_tablename, transfer_id, transfer_status, text,
       process_status, timestamp
from   erp_i_weighingcategory_log
union all
select 'ERP_O_CUSTOMER_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_o_customer_log
union all
select 'ERP_O_INTERNALCALCULATION_LOG' erp_tablename, transfer_id, transfer_status, text,
       process_status, timestamp
from   erp_o_internalcalculation_log
union all
select 'ERP_O_INVOICE_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_o_invoice_log
union all
select 'ERP_O_PACKINGNOTE_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_o_packingnote_log
union all
select 'ERP_O_PURCHASEORDER_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_o_purchaseorder_log
union all
select 'ERP_O_QUANTITYCUSTOMER_LOG' erp_tablename, transfer_id, transfer_status, text,
       process_status, timestamp
from   erp_o_quantitycustomer_log
union all
select 'ERP_O_ROUTE_EXPENSES_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_o_route_expenses_log
union all
select 'ERP_O_STOCKTRANSACTION_LOG' erp_tablename, transfer_id, transfer_status, text,
       process_status, timestamp
from   erp_o_stocktransaction_log
union all
select 'ERP_O_STOCKTRANS_LEDGERAMT_LOG' erp_tablename, transfer_id, transfer_status, text,
       process_status, timestamp
from   erp_o_stocktrans_ledgeramt_log
union all
select 'ERP_O_WORKORDER_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_o_workorder_log
union all
select 'ERP_I_SHIPMENTNOTIFICATION_LOG' erp_tablename, transfer_id, transfer_status, text,
       process_status, timestamp
from   erp_i_shipmentnotification_log
union all
select 'ABSLOG' erp_tablename, l.abslog_id transfer_id, 0 transfer_status, l.message text,
       case
         when l.priority > 1 then
          1
         else
          0
       end process_status, l.timestamp
from   abslog l
where  l.logtype = 5
and    l.logsource = 'ERP_Interface'
union all
select 'ERP_I_SUPPLIERMODEL_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_i_supplier_log
union all
select 'ERP_I_SUPPLIERMODELPRICE_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_i_supplier_log
union all
select 'ERP_I_SUPPLIERMODELORDER_LOG' erp_tablename, transfer_id, transfer_status, text, process_status,
       timestamp
from   erp_i_supplier_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
 (REPORTPARAM_ID, BUSINESSUNIT_ID, 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 1.0  union split for packingnote*/
 rp.reportparam_id, b.businessunit_id businessunit_id,
 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
 END "STAY",
 b.primaryid idcode, languages.code languagecode,
 case when c.staynr = 36 then GETABSMINDATE()  else b.planneddeliverydate end planneddeliverydate,
 b.lastinscandate, b.status_id, re.code productcode,
 (SELECT w.description FROM product_DESC w WHERE w.product_id = re.product_id AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 ro.routenumber, ro.description routedesc, rg.customernumber, rg.name customername, rh.departmentnumber, rh.description departmentdesc,
 cast(CONCATENATEWITHBLANK3(ri.street, ri.zipcode, ri.city) as varchar2(255)) customeraddres,
 rc.route_id, ro.drivingday_id day_id, 0 FLAG_NO, GETDATEDIFF(GETCURRENTDATE(), B.LASTINSCANDATE) MAXCOMPLETENESSDAYS,
 coalesce((select ca.internalprocessingbu_id from customeractivities ca, productgroup pg
 where ca.customer_id = rg.customer_id and re.productgroup_id = pg.productgroup_id
 and pg.activity_id = ca.activity_id and b.businessunit_id = ca.processbusinessunit_id), -1) internalBu, rc.drivingdate
from stay c, 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 re, department rh, address ri, languages, customer rg, route ro, routecontrol rc
, STOP
  LEFT OUTER JOIN DELIVERYPOINT ON STOP.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  LEFT outer JOIN ROUTESTOP ON STOP.ROUTESTOP_ID = ROUTESTOP.ROUTESTOP_ID,
  reportparam rp
where b.poolitem = 2
 and b.stay_id = c.stay_id
 and c.staytype = 1
 and b.uniqueitem_id = e.uniqueitem_id
 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 = re.product_id
 and h.customer_id = rg.customer_id
 and g.department_id = rh.department_id
 and rg.visitaddress_id = ri.address_id
 and (b.planneddeliverydate <= rc.drivingdate or c.staynr = 36)
 and ro.active = 'Y'
 and c.staynr not in (20,22,23,24,25)
 and ( f1.flag_id is null or h.flagstartdate > rc.drivingdate)
 and ( f2.flag_id is null or f.flagstartdate > rc.drivingdate)
 and not exists ( select ui.uniqueitem_id, min(uf.startdate) uniqueitemflagdate
                from uniqueitem ui, uniqueitemflag uf, flag fl
                where ui.uniqueitem_id = uf.uniqueitem_id
                and uf.flag_id = fl.flag_id
                and fl.includeincompletnesscheck = 'N'
                and ui.uniqueitem_id = b.uniqueitem_id
                group by ui.uniqueitem_id
                having min(uf.startdate) < rp.date_value1)
 and (( rp.number_value2=1 and c.staynr <>'37') or rp.number_value2=0)
 and STOP.CUSTOMER_LINK_ID = rg.CUSTOMER_ID
 and (nvl(STOP.DELIVERYPOINT_ID, 0) = 0 OR
         (( select locker.DELIVERYPOINT_ID from locker where locker.locker_id = f.locker_id)  = STOP.DELIVERYPOINT_ID) OR
        f.DELIVERYPOINT_ID = STOP.DELIVERYPOINT_ID)
 and STOP.ROUTECONTROL_ID = rc.routecontrol_id
 and stop.customer_link_id = h.customer_id
 and rc.route_id = ro.route_id
 and STOP.STATUS IN (0, 3)
 and (( exists (select 1 from customerdeliveryday cdd where cdd.customer_id=rg.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 customerdeliveryday cdd where cdd.customer_id=rg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
                  and cdd.day_id=ro.drivingday_id))
        or (exists (select 1 from routecontrol rc, stop where stop.customer_link_id = rg.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))))
--      and rp.number_value=rc.routecontrol_id
 and ro.routenumber >= rp.number_value8 and ro.routenumber <= rp.number_value9
 and rp.date_value1 = rc.originaldrivingdate
union all
select rp.reportparam_id, b.businessunit_id businessunit_id, 7 "STAY", b.primaryid idcode, languages.code languagecode,
 GETABSMINDATE() planneddeliverydate, b.lastinscandate, b.status_id, re.code productcode,
 (SELECT w.description FROM product_DESC w WHERE w.product_id = re.product_id AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 ro.routenumber, ro.description routedesc, rg.customernumber, rg.name customername, rh.departmentnumber, rh.description departmentdesc,
 cast(CONCATENATEWITHBLANK3(ri.street, ri.zipcode, ri.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 distributionpoint g, uniqueitem b, product re, department rh, address ri, languages, customer rg, route ro, routecontrol rc
, 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
, routecontrol rc1, STOP
  LEFT OUTER JOIN DELIVERYPOINT ON STOP.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  LEFT outer JOIN ROUTESTOP ON STOP.ROUTESTOP_ID = ROUTESTOP.ROUTESTOP_ID,
  reportparam rp
where b.stay_id = (select c.stay_id from stay c where c.staytype = 1 and c.staynr = 20)
 and (f.distributionpoint_id = g.distributionpoint_id or (h.customer_id is null and b.poolitem <> 2))
 and b.status_id in ( select st.status_id from status st  where st.statustype='UI' and (st.code = '20' or st.code = '30'))
 and b.product_id = re.product_id
 and (h.customer_id = rg.customer_id or (h.customer_id is null and b.poolitem <> 2))
 and g.department_id = rh.department_id
 and rg.visitaddress_id = ri.address_id
 and ro.active = 'Y'
 and ds.uniqueitem_link_id = b.uniqueitem_id
 and ds.businessunit_id = b.businessunit_id
 and ds.distributionpoint_link_id = g.distributionpoint_id
 and (nvl(f.deliverypoint_id, ds.deliverypoint_link_id) = ds.deliverypoint_link_id or (h.customer_id is null and b.poolitem <> 2 and g.deliverypoint_id = ds.deliverypoint_link_id))
 and rc1.routecontrol_id = ds.routecontrol_id
 and ds.customer_link_id = rg.customer_id
 and rc1.drivingdate <= rc.drivingdate
 and rc.route_id = ro.route_id
 and NVL(ds.PACKINGNOTE_ID,0) = 0
 and STOP.CUSTOMER_LINK_ID = rg.CUSTOMER_ID
 and (nvl(STOP.DELIVERYPOINT_ID, 0) = 0 OR
         (( select locker.DELIVERYPOINT_ID from locker where locker.locker_id = f.locker_id) = STOP.DELIVERYPOINT_ID) OR
        f.DELIVERYPOINT_ID = STOP.DELIVERYPOINT_ID or (h.customer_id is null and b.poolitem<> 2 and STOP.DELIVERYPOINT_ID=ds.deliverypoint_link_id))
 and STOP.ROUTECONTROL_ID = rc.routecontrol_id
 and stop.customer_link_id = rg.customer_id
 and rc.route_id = ro.route_id
 and STOP.STATUS IN (0, 3)
 and (( exists (select 1 from customerdeliveryday cdd where cdd.customer_id = rg.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 customerdeliveryday cdd where cdd.customer_id=rg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
                  and cdd.day_id=ro.drivingday_id))
        or (exists (select 1 from routecontrol rc, stop where stop.customer_link_id = rg.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))))
 and ds.outscannodelivery in (0,2)
-- and rp.number_value=rc.routecontrol_id
 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 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
select rp.reportparam_id,  b.businessunit_id businessunit_id, 7 "STAY", b.primaryid idcode, languages.code languagecode,
  GETABSMINDATE() planneddeliverydate, b.lastinscandate, b.status_id, re.code productcode,
 (SELECT w.description FROM product_DESC w WHERE w.product_id = re.product_id AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 ro.routenumber, ro.description routedesc,
 rg.customernumber, rg.name customername, rh.departmentnumber, rh.description departmentdesc,
 cast(CONCATENATEWITHBLANK3(ri.street, ri.zipcode, ri.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  distributionpoint g, uniqueitem b, product re, department rh, address ri, languages, customer rg, route ro, routecontrol rc
, 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
, routecontrol rc1, STOP
  LEFT OUTER JOIN DELIVERYPOINT ON STOP.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  LEFT outer JOIN ROUTESTOP ON STOP.ROUTESTOP_ID = ROUTESTOP.ROUTESTOP_ID,
  reportparam rp
where b.stay_id = (select c.stay_id from stay c where c.staytype = 1 and c.staynr = 20)
 and (f.distributionpoint_id = g.distributionpoint_id or (h.customer_id is null and b.poolitem <> 2))
 and b.status_id in ( select st.status_id from status st  where st.statustype = 'UI' and (st.code = '20' or st.code = '30'))
 and b.product_id = re.product_id
 and (h.customer_id = rg.customer_id or h.customer_id is null)
 and g.department_id = rh.department_id
 and rg.visitaddress_id = ri.address_id
 and ro.active = 'Y'
 and ds.uniqueitem_link_id = b.uniqueitem_id
 and ds.businessunit_id = b.businessunit_id
 and ds.distributionpoint_link_id = g.distributionpoint_id
 and ( nvl(f.deliverypoint_id, ds.deliverypoint_link_id) = ds.deliverypoint_link_id or (h.customer_id is null and b.poolitem <> 2 and g.deliverypoint_id = ds.deliverypoint_link_id))
 and rc1.routecontrol_id = ds.routecontrol_id
 and ds.customer_link_id = rg.customer_id
 and rc1.drivingdate <= rc.drivingdate
 and rc.route_id = ro.route_id
 and (nvl(STOP.DELIVERYPOINT_ID, 0) = 0 OR
         (( select locker.DELIVERYPOINT_ID from locker where locker.locker_id = f.locker_id)  = STOP.DELIVERYPOINT_ID) OR
        f.DELIVERYPOINT_ID = STOP.DELIVERYPOINT_ID)
 and STOP.CUSTOMER_LINK_ID = rg.CUSTOMER_ID
 and (nvl(STOP.DELIVERYPOINT_ID, 0) = 0 OR
         (( select locker.DELIVERYPOINT_ID from locker where locker.locker_id = f.locker_id)  = STOP.DELIVERYPOINT_ID) OR
        f.DELIVERYPOINT_ID = STOP.DELIVERYPOINT_ID or  (h.customer_id is null and b.poolitem<> 2 and STOP.DELIVERYPOINT_ID=ds.deliverypoint_link_id))
 and STOP.ROUTECONTROL_ID = rc.routecontrol_id
 and stop.customer_link_id = rg.customer_id
 and rc.route_id = ro.route_id
 and STOP.STATUS IN (0, 3)
 and (( exists (select 1 from customerdeliveryday cdd where cdd.customer_id=rg.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 customerdeliveryday cdd where cdd.customer_id=rg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
                  and cdd.day_id=ro.drivingday_id))
        or (exists (select 1 from routecontrol rc, stop where stop.customer_link_id = rg.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))))
 and ds.outscannodelivery in (0,2)
-- and rp.number_value=rc.routecontrol_id
 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 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_COMPLETENESSROUTE_PCO
 (REPORTPARAM_ID, BUSINESSUNIT_ID, 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 rp.reportparam_id,
 b.businessunit_id businessunit_id,
 /*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
 END*/1 "STAY",
 b.primaryid idcode,
 languages.code languagecode,
 case
   when c.staynr = 36 then GETABSMINDATE()
  else b.planneddeliverydate
 end planneddeliverydate,
 b.lastinscandate, b.status_id, re.code productcode,
 (SELECT description FROM product_DESC w WHERE w.product_id = re.product_id
    AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 ro.routenumber, ro.description routedesc,
 rg.customernumber, rg.name customername, rh.departmentnumber, rh.description departmentdesc,
 cast(CONCATENATEWITHBLANK3(ri.street, ri.zipcode, ri.city) as varchar2(255)) customeraddres,
 rc.route_id, ro.drivingday_id day_id, 0 FLAG_NO,
 GETDATEDIFF(GETCURRENTDATE(), B.LASTINSCANDATE) MAXCOMPLETENESSDAYS, coalesce((select ca.internalprocessingbu_id from customeractivities ca, productgroup pg
 where ca.customer_id=rg.customer_id and re.productgroup_id=pg.productgroup_id
 and pg.activity_id=ca.activity_id and b.businessunit_id=ca.processbusinessunit_id) ,-1)internalBu, rc.drivingdate
from stay c, 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 re, department rh, address ri, languages, customer rg, route ro,routecontrol rc
 ,STOP
  LEFT OUTER JOIN DELIVERYPOINT ON STOP.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  LEFT outer JOIN ROUTESTOP ON STOP.ROUTESTOP_ID = ROUTESTOP.ROUTESTOP_ID,
  reportparam rp
where b.poolitem = 2
 and b.stay_id = c.stay_id
 and c.staytype = 1
 and b.uniqueitem_id = e.uniqueitem_id
 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 = re.product_id
 and h.customer_id = rg.customer_id
 and g.department_id = rh.department_id
 and rg.visitaddress_id = ri.address_id
 and (b.planneddeliverydate <= rc.drivingdate or c.staynr = 36)
 and ro.active = 'Y'
 and c.staynr not in (20,22,23,24,25)
 and ( f1.flag_id is null or h.flagstartdate > rc.drivingdate)
 and ( f2.flag_id is null or f.flagstartdate > rc.drivingdate)
 and not exists ( select ui.uniqueitem_id, min(uf.startdate) uniqueitemflagdate
                from uniqueitem ui, uniqueitemflag uf, flag fl
                where ui.uniqueitem_id = uf.uniqueitem_id
                and uf.flag_id = fl.flag_id
                and fl.includeincompletnesscheck = 'N'
                and ui.uniqueitem_id = b.uniqueitem_id
                group by ui.uniqueitem_id
                having min(uf.startdate) < rp.date_value1)
 and (( rp.number_value2=1 and c.staynr <>'37') or rp.number_value2=0)
 and STOP.CUSTOMER_LINK_ID = rg.CUSTOMER_ID
 and (nvl(STOP.DELIVERYPOINT_ID, 0) = 0 OR
         (( select locker.DELIVERYPOINT_ID from locker where locker.locker_id = f.locker_id)  = STOP.DELIVERYPOINT_ID) OR
        f.DELIVERYPOINT_ID = STOP.DELIVERYPOINT_ID)
 and STOP.ROUTECONTROL_ID = rc.routecontrol_id
 and stop.customer_link_id=h.customer_id
 and rc.route_id=ro.route_id
 and STOP.STATUS IN (0, 3)
 and (( exists (select 1 from customerdeliveryday cdd where cdd.customer_id=rg.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 customerdeliveryday cdd where cdd.customer_id=rg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
                  and cdd.day_id=ro.drivingday_id))
        or (exists (select 1 from routecontrol rc, stop   where stop.customer_link_id=rg.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))))
      and rp.number_value = rc.routecontrol_id
   and rp.date_value1 = rc.originaldrivingdate
   and c.staynr = 30 and (st.code = '20' or st.code = '30')
   and re.typeofmerchandise = 2--20308 - rework to exclude non-garments
/*union
select rp.reportparam_id,
  b.businessunit_id businessunit_id,
  7 "STAY", b.primaryid idcode,
 languages.code languagecode,
  GETABSMINDATE() planneddeliverydate,
 b.lastinscandate, b.status_id, re.code productcode,
 (SELECT description FROM product_DESC w WHERE w.product_id = re.product_id AND w.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdesc,
 ro.routenumber, ro.description routedesc,
 rg.customernumber, rg.name customername, rh.departmentnumber, rh.description departmentdesc,
 cast(CONCATENATEWITHBLANK3(ri.street, ri.zipcode, ri.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  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,
  product re, department rh, address ri, languages, customer rg, route ro,routecontrol rc
 , deliveryscan ds,routecontrol rc1,STOP
  LEFT OUTER JOIN DELIVERYPOINT  ON STOP.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  LEFT outer JOIN ROUTESTOP ON STOP.ROUTESTOP_ID = ROUTESTOP.ROUTESTOP_ID,
  reportparam rp
where b.poolitem = 2
 and b.stay_id = (select c.stay_id from stay c where  c.staytype = 1 and c.staynr = 20)
 and f.distributionpoint_id = g.distributionpoint_id
 and f.wearer_id = h.wearer_id
 and b.status_id in ( select st.status_id from status st  where st.statustype='UI' and (st.code = '20' or st.code = '30'))
 and b.product_id = re.product_id
 and h.customer_id = rg.customer_id
 and g.department_id = rh.department_id
 and rg.visitaddress_id = ri.address_id
 and ro.active = 'Y'
 and ds.uniqueitem_link_id = b.uniqueitem_id
 and ds.businessunit_id = b.businessunit_id
 and ds.distributionpoint_link_id=g.distributionpoint_id
 and ds.weareremployment_link_id=f.weareremployment_id
 and  ( nvl( f.deliverypoint_id,0)=0 or ds.deliverypoint_link_id=f.deliverypoint_id)
 and rc1.routecontrol_id = ds.routecontrol_id
 and ds.customer_link_id=rg.customer_id
 and rc1.drivingdate<=rc.drivingdate
 and rc.route_id=ro.route_id
 and (ds.packingnote_id is null
           or (ds.packingnote_id is not null and (( select s.code from packingnote pn, status s
               where pn.packingnote_id=ds.packingnote_id  and pn.routecontrol_id=rc.routecontrol_id
               and pn.status_id=s.status_id and s.statustype='PN') ='20')) )
 and STOP.CUSTOMER_LINK_ID = rg.CUSTOMER_ID
 and (nvl(STOP.DELIVERYPOINT_ID, 0) = 0 OR
         (( select locker.DELIVERYPOINT_ID from locker where locker.locker_id = f.locker_id)  = STOP.DELIVERYPOINT_ID) OR
        f.DELIVERYPOINT_ID = STOP.DELIVERYPOINT_ID)
 and STOP.ROUTECONTROL_ID = rc.routecontrol_id
 and stop.customer_link_id=h.customer_id
 and rc.route_id=ro.route_id
 and STOP.STATUS IN (0, 3)
 and (( exists (select 1 from customerdeliveryday cdd where cdd.customer_id=rg.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 customerdeliveryday cdd where cdd.customer_id=rg.customer_id and cdd.deliverytype <> 'P' and cdd.typeofmerchadise = 2
                  and cdd.day_id=ro.drivingday_id))
        or (exists (select 1 from routecontrol rc, stop   where stop.customer_link_id=rg.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))))
 and ds.outscannodelivery in (0,2)
 and rp.number_value=rc.routecontrol_id
 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 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_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_COMPLETENESSWEARERDET_PCO
 (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*/1 "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
 and s.staynr = 30 and (st.code = '20' or st.code = '30')
 and pr.typeofmerchandise = 2--20308 - rework to exclude non-garments

/
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, TYPE, INVOICEHEADER_ID, REMARK, SHOWONINVOICEAPPENDIX)
as select distinct "NOTENUMBER","DELIVERYDATE","ORIGIN","TYPE","INVOICEHEADER_ID","REMARK","SHOWONINVOICEAPPENDIX" from
(
select distinct
cast(LEFTPAD(b.notenumber,22,' ') as varchar2(255)) notenumber,b.deliverydate, b.origin,1 type, l.INVOICEHEADER_ID, b.remark
, b.showoninvoiceappendix
from packingnote b, packingnoteline l
where b.packingnote_id = l.packingnote_id and b.origin in (0,1,2) and b.freeofchargereason_id is null
union all
select distinct
cast(LEFTPAD(b.notenumber,22,' ') as varchar2(255)) notenumber,b.deliverydate, b.origin,2 type, l.INVOICEHEADER_ID, b.remark
, b.showoninvoiceappendix
from packingnote b, packingnoteline l
where b.packingnote_id = l.packingnote_id and b.origin = 6 and b.freeofchargereason_id is null
union all
select distinct
cast(LEFTPAD(b.notenumber,22,' ') as varchar2(255)) notenumber,b.deliverydate, b.origin, 3 type, l.INVOICEHEADER_ID, b.remark
, b.showoninvoiceappendix
from packingnote b, packingnoteline l
where b.packingnote_id = l.packingnote_id and b.origin = 3 and b.freeofchargereason_id is null
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
from packingnote b, packingnotecontainer l
where b.packingnote_id = l.packingnote_id  and b.freeofchargereason_id is null
union all
select distinct
cast(LEFTPAD(b.notenumber,22,' ') as varchar2(255)) notenumber,b.deliverydate, b.origin, 4 type , l.INVOICEHEADER_ID, b.remark
, b.showoninvoiceappendix
from packingnote b, packingnoteline l
where b.packingnote_id = l.packingnote_id and b.origin = 4 and b.freeofchargereason_id is null
union all
select distinct
cast(LEFTPAD(c.ticketnumber,22,' ') as varchar2(255)) notenumber,c.weighingdate, c.origin, 5 type, t.INVOICEHEADER_ID, c.remark
, 'Y'
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, c.remark
, 'Y'
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, c.remark
, 'Y'
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, c.remark
, 'Y'
from weighingticket c, weighingticketline t
where c.weighingticket_id = t.weighingticket_id and origin = 2
and soilticket ='N'
)

/
create or replace view VR_NOTESDETAIL_DFD
 (NOTENUMBER, NOTEDATE, ORIGIN, TYPE, INVOICEHEADER_ID, REMARK, SHOWONINVOICEAPPENDIX, PRODUCTCODE, PRODUCTDESC, DELIVEREDAMOUNT, PRICE, INVPRICE)
as select distinct "NOTENUMBER",
                "DELIVERYDATE",
                "ORIGIN",
                "TYPE",
                "INVOICEHEADER_ID",
                "REMARK",
                "SHOWONINVOICEAPPENDIX",
                "PRODUCTCODE",
                "PRODUCTDESC",
                "DELIVEREDAMOUNT",
                "PRICE",
                "INVPRICE"
  from (select distinct --cast(LEFTPAD(b.notenumber, 22, ' ') as varchar2(255)) notenumber,
                        b.notenumber notenumber,
                        b.deliverydate,
                        b.origin,
                        case
                          when b.origin in (0, 1, 2) then
                           1
                          when b.origin = 6 then
                           2
                          when b.origin = 3 then
                           3
                          else
                           b.origin
                        end type,
                        l.INVOICEHEADER_ID,
                        b.remark,
                        b.showoninvoiceappendix,
                        (select prdl.code from product_link prdl where prdl.product_id = l.product_id) productcode,
                        (select prdesc.description
                         from product_link_desc prdesc, invoiceheader ih, customer_link custl, languages lng
                         where prdesc.product_link_id = l.product_id
                               and prdesc.language_id = lng.language_id
                               and l.invoiceheader_id = ih.invoiceheader_id
                               and ih.billtocustomer_link_id = custl.customer_link_id
                               and custl.languagecode = lng.code
                               ) productdesc,
                        l.deliveredamount,
                        l.price,
                        (select il.price
                         from invoiceline il, product prd
                         where il.invoiceheader_id = l.invoiceheader_id
                               and prd.product_id = l.product_id
                               and prd.code = il.code
                               and il.invoicelinetype_id = 2) invprice
                         --(select ih.invoicenumber from invoiceheader ih where ih.invoiceheader_id = l.invoiceheader_id) invnumber, b.origin
          from packingnote b, packingnoteline l
         where b.packingnote_id = l.packingnote_id
           and b.freeofchargereason_id is null
           and b.origin in (0, 1, 2, 3, 4, 6)
        /*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,
                        (select c.primaryid from container c where l.container_id = c.container_id) productcode,
                        null productdesc,
                        (l.grossweight - l.tareweight) deliveredamount,
                        l.price,
                        (select il.price
                         from invoiceline il, product prd
                         where il.invoiceheader_id = l.invoiceheader_id
                               and prd.product_id = l.product_id
                               and prd.code = il.code
                               and il.invoicelinetype_id in (3, 4)) invprice
          from packingnote b, packingnotecontainer l
         where b.packingnote_id = l.packingnote_id
           and b.freeofchargereason_id is null
        union all
        select distinct cast(LEFTPAD(c.ticketnumber, 22, ' ') as
                             varchar2(255)) notenumber,
                        c.weighingdate,
                        c.origin,
                        case
                          when c.origin = 1 and c.soilticket = 'Y' then
                           5
                          when c.origin = 1 and c.soilticket = 'N' then
                           6
                          when c.origin = 2 and c.soilticket = 'Y' then
                           7
                          when c.origin = 2 and c.soilticket = 'N' then
                           8
                          else
                           9
                        end type,
                        t.INVOICEHEADER_ID,
                        c.remark,
                        'Y'
          from weighingticket c, weighingticketline t
         where c.weighingticket_id = t.weighingticket_id
           and c.origin in (1, 2)*/)

/
create or replace view VR_NOTES_BUT
 (NOTENUMBER, NOTEDATE, ORIGIN, TYPE, INVOICEHEADER_ID, REMARK, SHOWONINVOICEAPPENDIX)
as select distinct
cast(LEFTPAD(b.notenumber||COALESCE((SELECT ' (' ||max(dv.reference)||')' FROM deliveryvariations dv WHERE dv.packingnote_id = b.packingnote_id), ''),22,' ') as varchar2(255)) notenumber,b.deliverydate, b.origin,1 type, l.INVOICEHEADER_ID, b.remark
, b.showoninvoiceappendix
from packingnote b, packingnoteline l
where b.packingnote_id = l.packingnote_id and b.origin in (0,1,2) and b.freeofchargereason_id is null
union all
select distinct
cast(LEFTPAD(b.notenumber||COALESCE((SELECT ' (' ||max(dv.reference)||')' FROM deliveryvariations dv WHERE dv.packingnote_id = b.packingnote_id), ''),22,' ') as varchar2(255)) notenumber,b.deliverydate, b.origin,2 type, l.INVOICEHEADER_ID, b.remark
, b.showoninvoiceappendix
from packingnote b, packingnoteline l
where b.packingnote_id = l.packingnote_id and b.origin = 6 and b.freeofchargereason_id is null
union all
select distinct
cast(LEFTPAD(b.notenumber||COALESCE((SELECT ' (' ||max(dv.reference)||')' FROM deliveryvariations dv WHERE dv.packingnote_id = b.packingnote_id), ''),22,' ') as varchar2(255)) notenumber,b.deliverydate, b.origin, 3 type, l.INVOICEHEADER_ID, b.remark
, b.showoninvoiceappendix
from packingnote b, packingnoteline l
where b.packingnote_id = l.packingnote_id and b.origin = 3 and b.freeofchargereason_id is null
union all
select distinct
cast(LEFTPAD(b.notenumber||COALESCE((SELECT ' (' ||max(dv.reference)||')' FROM deliveryvariations dv WHERE dv.packingnote_id = b.packingnote_id), ''),22,' ') as varchar2(255)) notenumber,b.deliverydate, b.origin, 4 type , l.INVOICEHEADER_ID, b.remark
, b.showoninvoiceappendix
from packingnote b, packingnoteline l
where b.packingnote_id = l.packingnote_id and b.origin = 4 and b.freeofchargereason_id is null
union all
select distinct
cast(LEFTPAD(c.ticketnumber,22,' ') as varchar2(255)) notenumber,c.weighingdate, c.origin, 5 type, t.INVOICEHEADER_ID, c.remark
, 'Y'
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, c.remark
, 'Y'
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, c.remark
, 'Y'
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, c.remark
, 'Y'
from weighingticket c, weighingticketline t
where c.weighingticket_id = t.weighingticket_id and origin = 2
and soilticket ='N'

/
create or replace view VR_NOTES_DFD
 (NOTENUMBER, NOTEDATE, ORIGIN, TYPE, INVOICEHEADER_ID, REMARK, SHOWONINVOICEAPPENDIX)
as select distinct "NOTENUMBER","DELIVERYDATE","ORIGIN","TYPE","INVOICEHEADER_ID","REMARK","SHOWONINVOICEAPPENDIX" from
(
select distinct
b.notenumber, b.deliverydate, b.origin,1 type, l.INVOICEHEADER_ID, b.remark
, b.showoninvoiceappendix
from packingnote b, packingnoteline l
where b.packingnote_id = l.packingnote_id and b.origin in (0,1,2) and b.freeofchargereason_id is null
union all
select distinct
b.notenumber, b.deliverydate, b.origin,2 type, l.INVOICEHEADER_ID, b.remark
, b.showoninvoiceappendix
from packingnote b, packingnoteline l
where b.packingnote_id = l.packingnote_id and b.origin = 6 and b.freeofchargereason_id is null
union all
select distinct
b.notenumber, b.deliverydate, b.origin, 3 type, l.INVOICEHEADER_ID, b.remark
, b.showoninvoiceappendix
from packingnote b, packingnoteline l
where b.packingnote_id = l.packingnote_id and b.origin = 3 and b.freeofchargereason_id is null
union all
select distinct
b.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
from packingnote b, packingnotecontainer l
where b.packingnote_id = l.packingnote_id  and b.freeofchargereason_id is null
union all
select distinct
b.notenumber, b.deliverydate, b.origin, 4 type , l.INVOICEHEADER_ID, b.remark
, b.showoninvoiceappendix
from packingnote b, packingnoteline l
where b.packingnote_id = l.packingnote_id and b.origin = 4 and b.freeofchargereason_id is null
union all
select distinct
c.ticketnumber notenumber,c.weighingdate, c.origin, 5 type, t.INVOICEHEADER_ID, c.remark
, 'Y'
from weighingticket c, weighingticketline t
where c.weighingticket_id = t.weighingticket_id and origin = 1
and soilticket ='Y'
union all
select distinct
c.ticketnumber notenumber,c.weighingdate, c.origin, 6 type, t.INVOICEHEADER_ID, c.remark
, 'Y'
from weighingticket c, weighingticketline t
where c.weighingticket_id = t.weighingticket_id and origin = 1
and soilticket ='N'
union all
select distinct
c.ticketnumber notenumber,c.weighingdate, c.origin, 7 type, t.INVOICEHEADER_ID, c.remark
, 'Y'
from weighingticket c, weighingticketline t
where c.weighingticket_id = t.weighingticket_id and origin = 2
and soilticket ='Y'
union all
select distinct
c.ticketnumber notenumber,c.weighingdate, c.origin, 8 type, t.INVOICEHEADER_ID, c.remark
, 'Y'
from weighingticket c, weighingticketline t
where c.weighingticket_id = t.weighingticket_id and origin = 2
and soilticket ='N'
)

/
create or replace view VR_NOTES_LTS
 (NOTENUMBER, NOTEDATE, ORIGIN, TYPE, INVOICEHEADER_ID, REMARK, SHOWONINVOICEAPPENDIX)
as select distinct
cast(LEFTPAD(b.notenumber,22,' ') as varchar2(255)) notenumber,b.deliverydate, b.origin,1 type, l.INVOICEHEADER_ID, b.remark
, b.showoninvoiceappendix
from packingnote b, packingnoteline l
where b.packingnote_id = l.packingnote_id and b.origin in (0,1,2) and b.freeofchargereason_id is null
union all
select distinct
cast(LEFTPAD(b.notenumber,22,' ') as varchar2(255)) notenumber,b.deliverydate, b.origin,2 type, l.INVOICEHEADER_ID, b.remark
, b.showoninvoiceappendix
from packingnote b, packingnoteline l
where b.packingnote_id = l.packingnote_id and b.origin = 6 and b.freeofchargereason_id is null
union all
select distinct
cast(LEFTPAD(b.notenumber,22,' ') as varchar2(255)) notenumber,b.deliverydate, b.origin, 3 type, l.INVOICEHEADER_ID, b.remark
, b.showoninvoiceappendix
from packingnote b, packingnoteline l
where b.packingnote_id = l.packingnote_id and b.origin = 3 and b.freeofchargereason_id is null
union all
select distinct
cast(LEFTPAD(b.notenumber,22,' ') as varchar2(255)) notenumber,b.deliverydate, b.origin, 4 type , l.INVOICEHEADER_ID, b.remark
, b.showoninvoiceappendix
from packingnote b, packingnoteline l
where b.packingnote_id = l.packingnote_id and b.origin = 4 and b.freeofchargereason_id is null
union all
select distinct
cast(LEFTPAD(c.ticketnumber,22,' ') as varchar2(255)) notenumber,c.weighingdate, c.origin, 5 type, t.INVOICEHEADER_ID, c.remark
, 'Y'
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, c.remark
, 'Y'
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, c.remark
, 'Y'
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, c.remark
, 'Y'
from weighingticket c, weighingticketline t
where c.weighingticket_id = t.weighingticket_id and origin = 2
and soilticket ='N'
union all
select distinct
cast(LEFTPAD(cn.consignmentnotenumber,22,' ') as varchar2(255)) notenumber,cn.deliverydate, cn.daynumber, 9 type, pnl.INVOICEHEADER_ID, ''
, 'Y'
from consignmentnote cn, packingnote pn, packingnoteline pnl
where cn.consignmentnote_id = pn.consignmentnote_id
and pn.packingnote_id = pnl.packingnote_id

/
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_NOTES_SNG
 (NOTENUMBER, NOTEDATE, ORIGIN, TYPE, INVOICEHEADER_ID, REMARK, SHOWONINVOICEAPPENDIX)
as select distinct
cast(LEFTPAD(b.notenumber,22,' ') as varchar2(255)) notenumber,b.deliverydate, b.origin,1 type, l.INVOICEHEADER_ID, b.remark
, b.showoninvoiceappendix
from packingnote b, packingnoteline l
where b.packingnote_id = l.packingnote_id and b.origin in (0,1,2) and b.freeofchargereason_id is null
union all
select distinct
cast(LEFTPAD(b.notenumber,22,' ') as varchar2(255)) notenumber,b.deliverydate, b.origin,2 type, l.INVOICEHEADER_ID, b.remark
, b.showoninvoiceappendix
from packingnote b, packingnoteline l
where b.packingnote_id = l.packingnote_id and b.origin = 6 and b.freeofchargereason_id is null
union all
select distinct
cast(LEFTPAD(b.notenumber,22,' ') as varchar2(255)) notenumber,b.deliverydate, b.origin, 3 type, l.INVOICEHEADER_ID, b.remark
, b.showoninvoiceappendix
from packingnote b, packingnoteline l
where b.packingnote_id = l.packingnote_id and b.origin = 3 and b.freeofchargereason_id is null
union all
select distinct
cast(LEFTPAD(b.notenumber,22,' ') as varchar2(255)) notenumber,b.deliverydate, b.origin, 4 type , l.INVOICEHEADER_ID, b.remark
, b.showoninvoiceappendix
from packingnote b, packingnoteline l
where b.packingnote_id = l.packingnote_id and b.origin = 4 and b.freeofchargereason_id is null
union all
select distinct
cast(LEFTPAD(c.ticketnumber,22,' ') as varchar2(255)) notenumber,c.weighingdate, c.origin, 5 type, t.INVOICEHEADER_ID, c.remark
, 'Y'
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, c.remark
, 'Y'
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, c.remark
, 'Y'
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, c.remark
, 'Y'
from weighingticket c, weighingticketline t
where c.weighingticket_id = t.weighingticket_id and origin = 2
and soilticket ='N'
union all
select distinct
cast(LEFTPAD(cn.consignmentnotenumber,22,' ') as varchar2(255)) notenumber,cn.deliverydate, cn.daynumber, 9 type, pnl.INVOICEHEADER_ID, ''
, 'Y'
from consignmentnote cn, packingnote pn, packingnoteline pnl
where cn.consignmentnote_id = pn.consignmentnote_id
and pn.packingnote_id = pnl.packingnote_id

/
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, CITY, DEPARTMENTNUMBER, DEPARTMENTDESC, PRODUCTCODE, PRODUCTDESC, SIZECODE, FINMETHODCODE, FINMETHODDESC, QRENTPIECES, QBEYONDLIFETIME, QRENTCHANGES, QMAXINV, QTOTALINCIRC, QFREEISSUED, QFREECUSTOMEROWNED, QFREESEASON, QTYWEARERRENTSTOP, QTYCUSTOMERRENTSTOP, QTYRENTOTHERS, QTYASSIGNED, QTYREPLACEMENT, QALLFREEQTY, VRENTPIECES, VBEYONDLIFETIME, VRENTCHANGES, VMAXINV, VTOTALINCIRC, VFREEISSUED, VFREECUSTOMEROWNED, VFREESEASON
, VWEARERRENTSTOP, VCUSTOMERRENTSTOP, VRENTOTHERS, VASSIGNED, VREPLACEMENT, VALLFREEQTY, CHARGEAFTERDEPRECIATION, EMPLOYMENT_NR, WEARERNUMBER, WEARER_FULL_NAME, LANGUAGECODE, MIN_ACTIVITY_ID, ACTIVITYBUSINESSUNIT_ID, DEFAULTBUSINESSUNIT_ID, INVOICEBUSINESSUNIT_ID, QTYRENTEDRETURNRENT, QTYRENTEDMINRENT, QTYFULLYAMORTIZED, VQTYFULLYAMORTIZED)
as select --+index(d XPKCUSTOMER) index(k XPKFINISHINGMETHOD) index(i XPKSIZEDEFINITION_LINK) index(g XPKPRODUCT_LINK) index(e XPKDEPARTMENT_LINK)
  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, 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
, case b.chargeafterdepreciation when 'Y' then ( b.qtyrentedperpiece + b.beyondlifetimecirc )
       else b.qtyrentedperpiece end qrentpieces
, case b.chargeafterdepreciation when 'Y' then 0 else b.beyondlifetimecirc end qbeyondlifetime
, b.changesperweek qrentchanges, b.maxinv qmaxinv, b.totalcircinv qtotalincirc, b.freeissuedcircinv qfreeissued
, b.cogcircinv qfreecustomerowned, b.freeseasoncircinv qfreeseason, b.qtyrentstop qtywearerrentstop
, b.qtycustomerrentstop, b.qtyrentedother qtyrentothers, b.qtyassigned, b.qtyreplacement
, case ss.value when 'N' then
  ( b.qtyassigned + b.freeissuedcircinv + b.beyondlifetimecirc + b.qtyrentstop + b.qtycustomerrentstop + b.cogcircinv + b.freeseasoncircinv + b.qtyreplacement )
  else ( b.qtyassigned + b.freeissuedcircinv + b.beyondlifetimecirc + b.qtyrentstop + b.qtycustomerrentstop + b.cogcircinv + b.freeseasoncircinv )
  end qAllFreeQty
, case b.chargeafterdepreciation when 'Y' then ( b.variationrentedperpiece + b.variationbeyondlifetimecirc )
       else b.variationrentedperpiece end vrentpieces
, case b.chargeafterdepreciation when 'Y' then 0 else b.variationbeyondlifetimecirc end vbeyondlifetime
, b.variationchangesperweek vrentchanges, b.variationmaxinv vmaxinv, b.variationtotalcircinv vtotalincirc
, b.variationfreeissuedcircinv vfreeissued, b.variationcogcircinv vfreecustomerowned
, b.variationfreeseasoncircinv vfreeseason, b.variationqtyrentstop vwearerrentstop
, b.variationqtycustomerrentstop vcustomerrentstop, b.variationrentedother vrentothers
, b.variationqtyassigned vassigned, b.variationqtyreplacement vreplacement
, case ss.value when 'N' then
  ( b.variationqtyassigned + b.variationfreeissuedcircinv + b.variationbeyondlifetimecirc + b.variationqtyrentstop + b.variationqtycustomerrentstop + b.variationcogcircinv + b.variationfreeseasoncircinv + b.variationqtyreplacement )
  else ( b.variationqtyassigned + b.variationfreeissuedcircinv + b.variationbeyondlifetimecirc + b.variationqtyrentstop + b.variationqtycustomerrentstop + b.variationcogcircinv + b.variationfreeseasoncircinv )
  end vAllFreeQty
, b.chargeafterdepreciation
, we.sequencenumber employment_Nr,
we.wearernumber wearernumber, we.wearername wearer_full_name
, 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
, b.qtyrentedreturnrent
, b.qtyrentedminrent
, b.qtyfullyamortized
, b.variationqtyfullyamortized vqtyfullyamortized
from statusquoheader a,
     sqitemincirculation b left outer join weareremployment_link we
                                         on we.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
, businessunit processBU, plant, systemsetting ss
, languages
, businessunit abu
where
    a.statusquotype = 1
and a.statusquoheader_id = b.statusquoheader_id
and b.customer_link_id = d.customer_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.processbusinessunit_id = processBU.Businessunit_Id
    and processBU.Plant_Id = plant.plant_id
        and plant.plant_id = ss.plant_id
            and ss.name = 'INVOICEREPLACEMENTS'
and a.subtype in (0, 2)
and d.dateinactive>sysdate

/
create or replace view VR_STATUSQUOITEMSINCIRCHISTORY
 (YEARWEEK, YEAR, WEEK, CUSTOMERNUMBER, CUSTOMERNAME, CITY, DEPARTMENTNUMBER, DEPARTMENTDESC, PRODUCTCODE, PRODUCTDESC, SIZECODE, PRODUCTGROUPCODE, PRODUCTGROUPDESC, QRENTPIECES, QBEYONDLIFETIME, QRENTCHANGES, QMAXINV, QTOTALINCIRC, QFREEISSUED, QFREECUSTOMEROWNED, QFREESEASON, QTYWEARERRENTSTOP, QTYCUSTOMERRENTSTOP, QTYRENTOTHERS, QTYASSIGNED, QTYREPLACEMENT, QALLFREEQTY, VRENTPIECES, VRENTCHANGES, VMAXINV, VTOTALINCIRC, VFREEISSUED, VFREECUSTOMEROWNED, VFREESEASON, VBEYONDLIFETIME
, VWEARERRENTSTOP, VCUSTOMERRENTSTOP, VRENTOTHERS, VASSIGNED, VREPLACEMENT, VALLFREEQTY, EMPLOYMENT_NR, WEARERNUMBER, WEARER_FULL_NAME, LANGUAGECODE, VARIATIONQTYRENTEDRETURNRENT, VARIATIONQTYRENTEDMINRENT, QTYRENTEDRETURNRENT, QTYRENTEDMINRENT, QTYFULLYAMORTIZED, VQTYFULLYAMORTIZED)
as select
  a.year*100 + a.week yearweek, a.year, a.week, d.customernumber, d.name customername,
  case
    when ((d.customer_id <> d.debtor_id) and (d.invoiceaddress_id is null)) then
      (select adr.city from address adr, customer bc where bc.customer_id = d.debtor_id and
         bc.invoiceaddress_id = adr.address_id)
    else
      (select adr.city from address adr where d.invoiceaddress_id = adr.address_id)
    end city,
  e.departmentnumber, e.description departmentdesc, 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,
  g.productgroupcode,
  (select pgd.description from productgroup_desc pgd, productgroup pg where pgd.productgroup_id = pg.productgroup_id
    and pg.code = g.productgroupcode and pgd.language_id = LANGUAGES.LANGUAGE_ID) productgroupdesc,
  case b.chargeafterdepreciation when 'Y' then ( b.qtyrentedperpiece + b.beyondlifetimecirc )
       else b.qtyrentedperpiece end qrentpieces,
  case b.chargeafterdepreciation when 'Y' then 0 else b.beyondlifetimecirc end qbeyondlifetime,
  b.changesperweek qrentchanges, b.maxinv qmaxinv, b.totalcircinv qtotalincirc, b.freeissuedcircinv qfreeissued,
  b.cogcircinv qfreecustomerowned, b.freeseasoncircinv qfreeseason, b.qtyrentstop qtywearerrentstop,
  b.qtycustomerrentstop, b.qtyrentedother qtyrentothers, b.qtyassigned, b.qtyreplacement
, case ss.value when 'N' then
  ( b.qtyassigned + b.freeissuedcircinv + b.beyondlifetimecirc + b.qtyrentstop + b.qtycustomerrentstop + b.cogcircinv + b.freeseasoncircinv + b.qtyreplacement )
  else ( b.qtyassigned + b.freeissuedcircinv + b.beyondlifetimecirc + b.qtyrentstop + b.qtycustomerrentstop + b.cogcircinv + b.freeseasoncircinv )
  end qAllFreeQty
, case b.chargeafterdepreciation when 'Y' then ( b.variationrentedperpiece + b.variationbeyondlifetimecirc )
       else b.variationrentedperpiece end vrentpieces,
  b.variationchangesperweek vrentchanges,
  b.variationmaxinv vmaxinv, b.variationtotalcircinv vtotalincirc,
  b.variationfreeissuedcircinv vfreeissued, b.variationcogcircinv vfreecustomerowned,
  b.variationfreeseasoncircinv vfreeseason, b.variationbeyondlifetimecirc vbeyondlifetime,
  b.variationqtyrentstop vwearerrentstop, b.variationqtycustomerrentstop vcustomerrentstop,
  b.variationrentedother vrentothers, b.variationqtyassigned vassigned
, b.variationqtyreplacement vreplacement
, case ss.value when 'N' then
  ( b.variationqtyassigned + b.variationfreeissuedcircinv + b.variationbeyondlifetimecirc + b.variationqtyrentstop + b.variationqtycustomerrentstop + b.variationcogcircinv + b.variationfreeseasoncircinv + b.variationqtyreplacement )
  else ( b.variationqtyassigned + b.variationfreeissuedcircinv + b.variationbeyondlifetimecirc + b.variationqtyrentstop + b.variationqtycustomerrentstop + b.variationcogcircinv + b.variationfreeseasoncircinv )
  end vAllFreeQty
, we.sequencenumber employment_Nr,
(select w.wearernumber from wearer w, weareremployment wem  where w.wearer_id=wem.wearer_id and wem.weareremployment_id=we.weareremployment_id) wearernumber,
 we.wearername wearer_full_name
, languages.code languagecode
, b.variationqtyrentedreturnrent
, b.variationqtyrentedminrent
, b.qtyrentedreturnrent
, b.qtyrentedminrent
, b.qtyfullyamortized
, b.variationqtyfullyamortized vqtyfullyamortized
from statusquoheader a,
     sqitemincirculation b left outer join weareremployment_link we
                                         on we.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
, businessunit processBU, plant, systemsetting ss
, languages
where
    a.statusquotype = 1
and 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 a.processbusinessunit_id = processBU.Businessunit_Id
    and processBU.Plant_Id = plant.plant_id
        and plant.plant_id = ss.plant_id
            and ss.name = 'INVOICEREPLACEMENTS'
and a.subtype in (0, 2)

/
create or replace view VR_STATUSQUOWEARERS
 (YEARWEEK, YEAR, WEEK, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERCITY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, ACTIVEWEARERS, ACTIVEWEARERSWITHGARM, INACTIVEWEARERS, ACTIVEEMPLOYMENTS, ACTIVEEMPLOYMENTSWITHGARM, INACTIVEEMPLOYMENTS, ACTIVEWEARERSWITHFUNCTION, LOCKERSINUSE, VARIATIONACTIVEWEARERS, VARIATIONACTIVEWEARERSWITHFUNC, VARIATIONACTIVEWEARERSWITHGARM, VARIATIONINACTIVEWEARERS, VARIATIONACTIVEEMPLOYMENTS, VARIATIONACTIVEEMPLOYWITHGARM, VARIATIONINACTIVEEMPLOYMENTS
, VARIATIONLOCKERSINUSE, LANGUAGECODE, INVOICEBUSINESSUNIT_ID, DEFAULTBUSINESSUNIT_ID, MIN_ACTIVITY_ID, ACTIVITYBUSINESSUNIT_ID)
as select (sqh.year*100+sqh.week) yearweek, sqh.year, sqh.week,
 cu.customernumber CustomerNumber, cu.name CustomerName,
 (select adr.city from address adr where cu.mailaddress_id = adr.address_id) CustomerCity,
 de.departmentnumber 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,
 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, sqwearer sqw,
     customer_link culk
     left outer join customer cu on culk.customer_id = cu.customer_id ,
     department_link delk
     left outer join department de on delk.department_id = de.department_id,
     languages
, businessunit abu
where sqh.statusquoheader_id = sqw.statusquoheader_id
 and sqw.customer_link_id = culk.customer_link_id
 and sqw.department_link_id = delk.department_link_id
 and 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_ACCEPTGIRO_PAYBY_BDE
 (INVOICEHEADER_ID, INVOICEDATE, INVOICENUMBER, PAYTHISAMOUNT, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME2, BILLTOCOUNTRYCODE, INV_STREET, INV_ZIPCODE, INV_CITY, INV_BU_CODE, INV_BU_DESC, PLANT_ID, PLANT_CODE, PLANT_NAME, PLANT_STREET, PLANT_CITY, PLANT_ZIPCODE, ACCEPTGIROREFERENCE, ACCEPTGIROCODELINE, PBCUSTNO_FORGIRO, LNDRY_BNK_DESC, LNDRY_BNK_INTERNID, LNDRY_BNK_ZIPCODE, LNDRY_BNK_STREET, LNDRY_BNK_CITY, BNK_IDCODE, BNK_DESC, BNK_INTERNID, BNK_IBANNO, ACCEPTGIROFORMAT
, CREDITSQUEEZEPERC, INVOICELAYOUTCODE, PAYMENTDISCOUNT, PAYMENTDISCOUNT2, PAYMENTTERMSDESCRIPTION, DISCOUNTDAYS, DISCOUNTDAYS2, NETPAYMENTDAYS, CREDITSQUEEZEAMOUNT, PAYBYCUSTOMER_ID, PAYBY_NO, PAYBY_NAME, TOTALAMOUNTEXCLVAT, PREBILLAMOUNT, INVOICEAMOUNTDECIMALS, DECIMALS, BILLTOCOUNTRYDESCRIPTION, CONTACTPERSONNAME, NEXTPERIODSTARTDATE, INVOICEFREQUENCYNUMBER, PARENTINVOICEHEADER_ID, DUEDATE, IS_IN_ADVANCE)
as select h.invoiceheader_id, h.invoicedate, h.invoicenumber, h.paythisamount,
       h.billtocustomernumber, h.billtocustomername, h.extraname2,
--(select co.code from customer bc, country co where h.billtocustomer_link_id = bc.customer_id and bc.country_id = co.country_id ) billtocountrycode,
(select co.code from country co where PBCust.country_id = co.country_id ) billtocountrycode,
--       h.street inv_street, h.zipcode inv_zipcode, h.city inv_city,
       va.street inv_street, va.zipcode inv_zipcode, va.city inv_city,
       bu.code Inv_bu_code, bu.description Inv_bu_desc,
       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,
       to_char(PBCust.Customernumber, '00000000000000') PBCustNo_ForGiro,
       lbi.description lndry_bnk_desc, lbi.internalidcode lndry_bnk_internID, 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,
       ss.value ACCEPTGIROFORMAT
       , h.creditsqueezeperc
       , ihe.formlayoutcode INVOICELAYOUTCODE --todo 4799
       , ihe.paymentdiscount, ihe.paymentdiscount2, ihe.paymenttermsdescription
       , ihe.discountdays, ihe.discountdays2
       , h.netpaymentdays, h.creditsqueezeamount --end todo 4799
, PBCust.Customer_Id PayByCustomer_ID, PBCust.Customernumber PayBy_No , PBCust.Name PayBy_Name
, h.totalamountexclvat, h.prebillamount, b.invoiceamountdecimals, b.decimals
, ihe.billtocountrydescription, h.contactpersonname, h.nextperiodstartdate, h.invoicefrequency_id invoicefrequencynumber
, h.parentinvoiceheader_id, ihe.paymenttermsduedate DueDate
, case h.parentinvoiceheader_id
  when null then (case h.nextperiodstartdate when null then 0 else 1 end)
  else ( select count(cih.nextperiodstartdate) from invoiceheader cih
  where cih.parentinvoiceheader_id = h.invoiceheader_id and cih.parentinvoiceheader_id <> cih.invoiceheader_id
        and cih.nextperiodstartdate is not null )
  end  Is_in_advance
from invoiceheader h, businessunit bu, plant pl, address pa, systemsetting ss, currency b, status s,
     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
         left outer join --customer_link PBCust
              (customer PBCust left outer join address va on va.address_id = PBCust.Visitaddress_Id)
         ON ihe.paybycustomer_link_id = PBCust.Customer_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'
      and b.currency_id = h.currency_id
      and h.status_id = s.status_id
      and s.statustype = 'IN'
          and s.code = 2
      and (h.parentinvoiceheader_id is null or h.parentinvoiceheader_id = h.invoiceheader_id)

/
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 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 bu.businessunit_id = bug.businessunit_id
       on     bug.usergroup_id = ug.usergroup_id
       , menu m
        join   plant pt     on     pt.plant_id = m.plant_id
        join   menugroup mg
                    join   menuitem mi    on     mi.menugroup_id = mg.menugroup_id
        on     mg.menu_id = m.menu_id
        , menusperusergroup mpu, languages lan
where mpu.menu_id = m.menu_id and mpu.usergroup_id = ug.usergroup_id

/
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, LASTLOGINATWORKSTATION_CODE, LASTINCORRECTLOGINTIMESTAMP, INCORRECTLOGINSSINCEPWCHANGE
)
as select 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,
       (select wo.code from workstation wo where wo.workstation_id = su.lastloginatworkstation) lastloginatworkstation_code,
       su.lastincorrectlogintimestamp, su.incorrectloginssincepwchange
from systemuser su left outer 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 su.usergroup_id, su.username, su.fullname, lan.code language_code, su.active, su.sysadmin
from systemuser su, languages lan
where 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, PROFILE, LANGUAGE_ID, LANGUAGE_CODE)
as select 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,
     (select ugda.profile from usergroupdialogaccess ugda where ugda.usergroup_id = nvl(y.arpgus,y.mgpus )
                             and ugda.dialog_id = y.dialog_id) profile, y.language_id, y.language_code
  from (select x.groupname,
               x.groupdesc,
               x.plantcode,
               x.plant_id,
               x.menudesc,
               x.menugroupdesc,
               x.dialogdesc, --mgpu.visible
               coalesce(mgpu.visible, (case when mpu.systemuser_id is null then 'N' else 'Y' end), 'N')
               mgpu_visible, --arpg.visible
               coalesce(arpg.visible, mgpu.visible, (case when mpu.systemuser_id is null then 'N' else 'Y' end), 'N')
               arpg_visible,
               coalesce(arpg.readonly, '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
                                   dg.gedescription
                                    when 'NL' then
                                      dg.nldescription
                                         else
                                             dg.endescription
                                                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 usergroup ug, languages l
                  , menu_desc md, menugroup_desc mgd, menu m
                  join plant pt
                    on pt.plant_id = m.plant_id
                  join menugroup mg
                    on mg.menu_id = m.menu_id
                  join menuitem mi
                    on mi.menugroup_id = mg.menugroup_id
                  join dialogs dg
                    on dg.dialog_id = mi.dialog_id
                 where md.menu_id = m.menu_id and md.language_id = l.language_id
                       and mgd.menugroup_id = mg.menugroup_id and mgd.language_id = l.language_id ) x
          left outer join accessrightsperusergroup arpg
            on (arpg.menuitem_id = x.menuitem_id and
               arpg.usergroup_id = x.usergroup_id)
          left outer join menugroupsperusergroup mgpu
            on (mgpu.menugroup_id = x.menugroup_id and
               mgpu.usergroup_id = x.usergroup_id)
          left outer join Menusperusergroup mpu
            on (mpu.menu_id = x.menu_id and
               mpu.usergroup_id = x.usergroup_id)) y
   --where (y.mgpu_visible = 'Y' or y.arpg_visible = 'Y')

/
create or replace view V_ACLMONITOR_DV_LLG
 (CUSTOMER_ID, CUSTOMERNUMBER, DISTRIBUTIONPOINT_ID, DISTRIBUTIONPOINTNUMBER, PRODUCT_ID, PRODUCTCODE, SIZEDEFINITION_ID, SIZECODE, FINISHINGMETHOD_ID, FMCODE, PICKUPDATE, DELIVERYDATE, NOTDELIVERED, SOILCOUNT, DIFFERENCE)
as select
c.customer_id,
c.customernumber,
dp.distributionpoint_id,
dp.distributionpointnumber,
p.product_id,
p.code productcode,
sd.sizedefinition_id,
sd.code sizecode,
fm.finishingmethod_id,
fm.code fmcode,
(select max(bt.pickupdate) from soilhistory sh
 inner join bagtag bt on sh.bagtag_id = bt.bagtag_id
 where sh.customer_link_id = c.customer_id
 and sh.product_link_id = p.product_id
 and sh.sizedefinition_link_id = sd.sizedefinition_id
 and sh.distributionpoint_link_id = dp.distributionpoint_id
 and to_date(bt.planneddeliverydate,'dd-mm-yy') = to_date(dv.deliverydate,'dd-mm-yy')) pickupdate,
dv.deliverydate,
count(case when dv.packingnote_id is null then 1 else 0 end) notdelivered,
sum(case when dv.origin = 1 and dv.soilcountsubtype in (1, 4,5) then dv.amount else 0 end) soilcount,
sum(case when dv.origin = 3 and dv.reasoncode_id = (select rc.reasoncode_id from reasoncode rc where rc.code = 'ACL') then dv.amount else 0 end) difference
from deliveryvariations dv
inner join product p on dv.product_id = p.product_id
inner join sizedefinition sd on dv.sizedefinition_id = sd.sizedefinition_id
inner join finishingmethod fm on dv.finishingmethod_id = fm.finishingmethod_id
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
where ((dv.origin = 1 and dv.soilcountsubtype in (1, 4, 5))
or
(dv.origin = 3 and dv.reasoncode_id = (select rc.reasoncode_id from reasoncode rc where rc.code = 'ACL'))
)
group by c.customer_id, c.customernumber, dp.distributionpoint_id, dp.distributionpointnumber,
p.product_id, p.code, sd.sizedefinition_id, sd.code, fm.finishingmethod_id, fm.code, dv.deliverydate

/
create or replace view V_ACLMONITOR_LLG
 (BUSINESSUNIT_ID, BU_CODE, CUSTOMER_ID, CUSTOMERNUMBER, DISTRIBUTIONPOINT_ID, CUSTOMERNAME, PRODUCT_ID, PRODUCTCODE, PRODUCTDESC, SIZEDEFINITION_ID, SIZECODE, FINISHINGMETHOD_ID, FMCODE, PICKUPDATE, SOILEDQTY, DELIVERYDATE, LANGUAGECODE, ACLCOUNT)
as select bu.businessunit_id,
bu.code bu_code,
c.customer_id,
c.customernumber,
dp.distributionpoint_id,
c.name customername,
p.product_id,
p.code productcode,
(select pd.description from product_desc pd where pd.language_id = l.language_id and pd.product_id = p.product_id) productdesc,
sd.sizedefinition_id,
sd.code sizecode,
fm.finishingmethod_id,
fm.code fmcode,
(select /*+ ordered bt, sh*/ max(bt.pickupdate) from bagtag bt
 inner join soilhistory sh on bt.bagtag_id = sh.bagtag_id
 where bt.planneddeliverydate = dv.deliverydate
 and bt.distributionpoint_id = dv.distributionpoint_id
 and sh.customer_link_id = c.customer_id
 and sh.product_link_id = p.product_id
 and sh.sizedefinition_link_id = sd.sizedefinition_id
 and sh.distributionpoint_link_id = dv.distributionpoint_id
 and sh.processbusinessunit_id = bu.businessunit_id) pickupdate,
(select /*+ ordered bt, sh*/ sum(sh.quantitysoil) from bagtag bt
 inner join soilhistory sh on bt.bagtag_id = sh.bagtag_id
 where bt.planneddeliverydate = dv.deliverydate
 and bt.distributionpoint_id = dv.distributionpoint_id
 and sh.customer_link_id = c.customer_id
 and sh.product_link_id = p.product_id
 and sh.sizedefinition_link_id = sd.sizedefinition_id
 and sh.distributionpoint_link_id = dv.distributionpoint_id
 and sh.processbusinessunit_id = bu.businessunit_id) soiledqty,
dv.deliverydate,
l.code languagecode,
sum(dv.amount) aclcount
from productlistpercustomer plpc
inner join product p on plpc.product_id = p.product_id
inner join sizedefinition sd on plpc.sizedefinition_id = sd.sizedefinition_id
inner join finishingmethod fm on plpc.finishingmethod_id = fm.finishingmethod_id
inner join customer c on plpc.customer_id = c.customer_id
inner join businessunit bu on c.defaultbusinessunit_id = bu.businessunit_id
inner join department d on c.customer_id = d.customer_id
inner join distributionpoint dp on d.department_id = dp.department_id,
languages l,
deliveryvariations dv
where plpc.delayedevenexchange = 0
and plpc.product_id = dv.product_id
and plpc.sizedefinition_id = dv.sizedefinition_id
and plpc.finishingmethod_id = dv.finishingmethod_id
and dp.distributionpoint_id = dv.distributionpoint_id
and dv.origin = 3 and dv.reasoncode_id = (select rc.reasoncode_id from reasoncode rc where rc.code = 'ACL')
group by c.customer_id, c.customernumber, c.name, dv.distributionpoint_id, dp.distributionpoint_id, dp.distributionpointnumber,
p.product_id, p.code, sd.sizedefinition_id, sd.code, fm.finishingmethod_id, fm.code, dv.deliverydate
,bu.businessunit_id,bu.code,l.language_id,l.code

/
create or replace view V_ACTIVEPRODUCTSWITHNOINV_LLG
 (CUSTOMERNUMBER, CUSTOMERSEARCHNAME, CUSTOMERNAME, BUCODE, PRODUCTCODE, PRODUCT_DESCRIPTION, SIZEDEFINITION_CODE, FM_CODE, LANGUAGECODE, CIRCINVENT, DISTRIBUTIONPOINT_ID, LASTDELIVERYDATE)
as select c.customernumber,
c.searchname customersearchname,
c.name customername,
(select bu.code from businessunit bu where bu.businessunit_id = c.defaultbusinessunit_id) bucode,
(select p.code from product p where p.product_id = plpc.product_id) productcode,
(select pd.description from product_desc pd, product p where p.product_id = plpc.product_id and p.product_id = pd.product_id and pd.language_id = l.language_id) product_description,
(select sd.code from sizedefinition sd where sd.sizedefinition_id = plpc.sizedefinition_id) sizedefinition_code,
(select fm.code from finishingmethod fm where fm.finishingmethod_id = plpc.finishingmethod_id) fm_code,
l.code languagecode,
0 circinvent,
dp.distributionpoint_id,
(select max(dv.deliverydate) from deliveryvariations dv where dv.product_id = plpc.product_id
                                  and dv.sizedefinition_id = plpc.sizedefinition_id
                                  and dv.finishingmethod_id = plpc.finishingmethod_id
                                  and dv.distributionpoint_id = dp.distributionpoint_id) lastdeliverydate
from
productlistpercustomer plpc,
distributionpoint dp,
productlistperdistribpoint plpd,
--product p,
customer c,
department d,
languages l
where plpc.customer_id = c.customer_id
and c.customer_id = d.customer_id
and d.department_id = dp.department_id
--and plpc.product_id = p.product_id
and plpc.dateactive <= sysdate
and plpc.dateinactive >= sysdate
and plpc.product_id = plpd.product_id
and plpc.sizedefinition_id = plpd.sizedefinition_id
and plpc.finishingmethod_id = plpd.finishingmethod_id
and plpd.distributionpoint_id = dp.distributionpoint_id
and plpd.productlistperdistribpoint_id
    not in (select rqa.productlistperdistribpoint_id
                   from rentalqtyadjustment rqa
            where rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id)
union
select c.customernumber,
c.searchname customersearchname,
c.name customername,
(select bu.code from businessunit bu where bu.businessunit_id = c.defaultbusinessunit_id) bucode,
(select p.code from product p where p.product_id = plpc.product_id) productcode,
(select pd.description from product_desc pd, product p where p.product_id = plpc.product_id and p.product_id = pd.product_id and pd.language_id = l.language_id) product_description,
(select sd.code from sizedefinition sd where sd.sizedefinition_id = plpc.sizedefinition_id) sizedefinition_code,
(select fm.code from finishingmethod fm where fm.finishingmethod_id = plpc.finishingmethod_id) fm_code,
l.code languagecode,
coalesce((select sum(rqa.quantity) from rentalqtyadjustment rqa
        where rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
        /*group by c.customernumber, c.searchname, c.name, p.product_id, plpc.product_id, p.code, plpc.sizedefinition_id, plpc.finishingmethod_id, plpd.distributionpoint_id,
        l.language_id, l.code having sum(rqa.quantity) = 0*/), 0)
 circinvent,
dp.distributionpoint_id,
(select max(dv.deliverydate) from deliveryvariations dv where dv.product_id = plpc.product_id
                                  and dv.sizedefinition_id = plpc.sizedefinition_id
                                  and dv.finishingmethod_id = plpc.finishingmethod_id
                                  and dv.distributionpoint_id = dp.distributionpoint_id) lastdeliverydate
from
productlistpercustomer plpc,
distributionpoint dp,
productlistperdistribpoint plpd,
--product p,
customer c,
department d,
languages l/*,
rentalqtyadjustment rqa*/
where plpc.customer_id = c.customer_id
and c.customer_id = d.customer_id
and d.department_id = dp.department_id
--and plpc.product_id = p.product_id
and plpc.dateactive <= sysdate
and plpc.dateinactive >= sysdate
and plpc.product_id = plpd.product_id
and plpc.sizedefinition_id = plpd.sizedefinition_id
and plpc.finishingmethod_id = plpd.finishingmethod_id
and plpd.distributionpoint_id = dp.distributionpoint_id
--and plpd.productlistperdistribpoint_id = rqa.productlistperdistribpoint_id

/
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
  RC.ROUTECONTROL_ID
, ( select rs.stopnumber from routestop rs where rs.route_id = route.route_id
  and rs.customer_id = cu.customer_id ) stopNumber
, cu.customerNumber, cu.name customerName, address.street, address.zipcode, address.city
, route.routenumber, route.description routeDesc, route.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 = languages.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 = languages.language_id ) sizeDesc
, askd.uniqueid uniqueid_askd
, uq.lastscandate
, askl.section, askl.location, askl.uniqueid uniqueid_askl
, askd.timestamp, systemuser.username
, languages.code languageCode
from
  activestockdelivery ask
    left outer join
      ( customer cu join address on cu.visitaddress_id = address.address_id )
         on ask.customer_link_id = cu.customer_id
    left outer join
      ( packingnoteline pnl join packingnote pn on pnl.packingnote_id = pn.packingnote_id )
         on pnl.packingnoteline_id = ask.packingnoteline_id
, activestockdeliverydetail askd
    left outer join activestocklocation askl on askd.activestocklocation_id = askl.activestocklocation_id
, routecontrol rc, route
, product_link prdlk, sizedefinition_link szlk
, uniqueitem uq, systemuser
, languages
where
    ask.activestockdelivery_id = askd.activestockdelivery_id
and askd.detailinfo = 4 -- emergency procedure
and ask.routecontrol_id = rc.routecontrol_id
    and rc.route_id = route.route_id
and ask.product_link_id = prdlk.product_link_id
and ask.sizedefinition_link_id = szlk.sizedefinition_link_id
    and askd.uniqueid = uq.primaryid
    and askd.systemuser_id = systemuser.systemuser_id
    -- and ask.product_link_id = uq.product_id and ask.sizedefinition_link_id = uq.sizedefinition_id and ask.finishingmethod_id = uq.finishingmethod_id

/
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
  businessunit.code businessunitCode, businessunit.description businessunitDescription
, ih.invoicedate, route.routeNumber, route.description routeDescription , ih.deltocustomernumber
, ih.deltocustomername, ih.invoicenumber, il.linenumber, ilp.wearernumber
, ( select description from invoicelinetype_desc z where z.invoicelinetype_id = ilt.invoicelinetype_id
  and z.language_id = languages.language_id) invoicelineTypeDesc
, il.description invoicelineDesc, il.code invoicelineCode, reasoncode.code adjustmentCode
, ( select description from reasoncode_desc y where y.reasoncode_id = reasoncode.reasoncode_id
  and y.language_id = languages.language_id) adjustmentDesc
, il.adjustedamount, il.amount, il.adjustmentbilledqty
, currency.code currencyCode, currency.invoiceamountdecimals, languages.code languageCode
, (select d.code from district d where route.district_id = d.district_id) districtcode
, (select e.employeenumber from employee e where route.routemanager_id = e.employee_id) routemanagernr
, ih.route_id
, il.timestamp chtimestamp
, (select su.username from  systemuser su where il.systemuser_id=su.systemuser_id) chuser
from
  invoiceline il
    left outer join invoicelineproduct ilp on il.invoiceline_id = ilp.invoiceline_id
, invoicelinetype ilt
, invoiceheader ih
    left outer join route on ih.route_id = route.route_id and route.active = 'Y'
, status, reasoncode, businessunit, currency, languages --, route route
where
    ih.invoiceheader_id = il.invoiceheader_id
and ih.status_id = status.status_id
    and status.statustype = 'IN'
        -- and status.code = '2'
and il.adjustmentreason_id = reasoncode.reasoncode_id
and ih.invoicebusinessunit_id = businessunit.businessunit_id
and il.invoicelinetype_id = ilt.invoicelinetype_id
and ih.currency_id = currency.currency_id
--and ih.route_id = route.route_id

/
create or replace view V_ADJUSTMENTVERIF_AUJ
 (PR, 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
 '1'  pr,
  businessunit.code businessunitCode, businessunit.description businessunitDescription
, ih.invoicedate, route.routeNumber, route.description routeDescription , ih.deltocustomernumber
, ih.deltocustomername, ih.invoicenumber, il.linenumber, ilp.wearernumber
, ( select description from invoicelinetype_desc z where z.invoicelinetype_id = ilt.invoicelinetype_id
  and z.language_id = languages.language_id) invoicelineTypeDesc
, il.description invoicelineDesc, il.code invoicelineCode, reasoncode.code adjustmentCode
, ( select description from reasoncode_desc y where y.reasoncode_id = reasoncode.reasoncode_id
  and y.language_id = languages.language_id) adjustmentDesc
, il.adjustedamount, il.amount, il.adjustmentbilledqty
, currency.code currencyCode, currency.invoiceamountdecimals, languages.code languageCode
, (select d.code from district d where route.district_id = d.district_id) districtcode
, (select e.employeenumber from employee e where route.routemanager_id = e.employee_id) routemanagernr
, ih.route_id
, il.timestamp chtimestamp
, (select su.username from  systemuser su where il.systemuser_id=su.systemuser_id) chuser
from
  invoiceline il
    left outer join invoicelineproduct ilp on il.invoiceline_id = ilp.invoiceline_id
, invoicelinetype ilt
, invoiceheader ih
    left outer join route on ih.route_id = route.route_id and route.active = 'Y'
, status, reasoncode, businessunit, currency, languages
where
    ih.invoiceheader_id = il.invoiceheader_id
and ih.status_id = status.status_id
    and status.statustype = 'IN'
   and il.adjustmentreason_id = reasoncode.reasoncode_id
and ih.invoicebusinessunit_id = businessunit.businessunit_id
and il.invoicelinetype_id = ilt.invoicelinetype_id
and ih.currency_id = currency.currency_id
union
select
 '2' pr,
  businessunit.code businessunitCode, businessunit.description businessunitDescription
, ih.invoicedate, route.routeNumber, route.description routeDescription , ih.deltocustomernumber
, ih.deltocustomername, ih.invoicenumber, il.linenumber, ilp.wearernumber
, ( select description from invoicelinetype_desc z where z.invoicelinetype_id = ilt.invoicelinetype_id
  and z.language_id = languages.language_id) invoicelineTypeDesc
, il.description invoicelineDesc, il.code invoicelineCode, reasoncode.code adjustmentCode
, ( select description from reasoncode_desc y where y.reasoncode_id = reasoncode.reasoncode_id
  and y.language_id = languages.language_id) adjustmentDesc
,  0 adjustedamount, 0 amount, ila.quantity
, currency.code currencyCode, currency.invoiceamountdecimals, languages.code languageCode
, (select d.code from district d where route.district_id = d.district_id) districtcode
, (select e.employeenumber from employee e where route.routemanager_id = e.employee_id) routemanagernr
, ih.route_id
, ila.timestamp chtimestamp
, (select su.username from  systemuser su where ila.systemuser_id=su.systemuser_id) chuser
from
  invoiceline il, invoicelineproduct ilp
, invoicelinetype ilt,invoicelineadjust ila, invoiceheader ih
    left outer join route on ih.route_id = route.route_id and route.active = 'Y'
, status, reasoncode, businessunit, currency, languages
where
    ih.invoiceheader_id = il.invoiceheader_id
and ih.status_id = status.status_id
    and status.statustype = 'IN'
    and il.invoiceline_id = ilp.invoiceline_id
    and il.invoiceline_id=ila.invoiceline_id
    and ila.reasoncode_id = reasoncode.reasoncode_id
and ih.invoicebusinessunit_id = businessunit.businessunit_id
and il.invoicelinetype_id = ilt.invoicelinetype_id
and ih.currency_id = currency.currency_id

/
create or replace view V_ADJUSTMENTVERIF_CASHDELAY
 (DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICENUMBER, INVOICEDATE, ROUTE_ID, ROUTENUMBER, OPENAMOUNT)
as select 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 ih.deltocustomernumber, ih.deltocustomername, ih.invoicenumber,
       ih.invoicedate, ih.routenumber, ih.route_id,
       ih.paythisamount openamount, languages.code languageCode,
			 (select description from reasoncode_desc y where y.reasoncode_id = rc.reasoncode_id
       and y.language_id = languages.language_id) adjustmentDesc
from invoiceheader ih, reasoncode rc, languages
where ih.adjustmentreason_id is not null
			and ih.adjustmentreason_id = rc.reasoncode_id

/
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 CS.CUSTOMER_ID, CS.CUSTOMERNUMBER, CS.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 = languages.language_id) productdesc,
  sz.code sizecode,  --LK.BANK WEARERBANK, LK.LOCKER WEARERLOCKER,
  (select sdd.description from sizedefinition_desc sdd
    where sdd.sizedefinition_id = sz.sizedefinition_id and sdd.language_id = languages.language_id) sizedesc,
  P.DAYSINCIRCPREVISSUE, P.LASTISSUEDATE,
  h.uniqueitem_id,
  languages.code languagecode
from weareremployment c--    left outer join locker lk on (lk.locker_id = c.locker_id),
    LEFT OUTER JOIN WEARERFUNCTION WF ON WF.WEARERFUNCTION_ID = C.WEARERFUNCTION_ID,
  uniqueitemnonpool g, uniqueitem h, uniqueitemfixedinfo p,
  PRODUCT PR, PRODUCTGROUP PG, sizedefinition sz, wearerinventory wi,
  WEARER W, CUSTOMER CS, DEPARTMENT DP, status st, distributionpoint DSP, address adr, languages
where --c.weareremployment_id = g.weareremployment_id
  c.weareremployment_id = wi.weareremployment_id
  and wi.wearerinventory_id = g.wearerinventory_id
  and g.uniqueitem_id = h.uniqueitem_id -- non-pool
  and h.uniqueitem_id = p.uniqueitem_id--  AND H.PRODUCT_ID = PR.PRODUCT_ID
  AND wi.PRODUCT_ID = PR.PRODUCT_ID
  and wi.sizedefinition_id = sz.sizedefinition_id
  AND PR.PRODUCTGROUP_ID = PG.PRODUCTGROUP_ID
  AND C.WEARER_ID = W.WEARER_ID
  AND W.CUSTOMER_ID = CS.CUSTOMER_ID
  and h.status_id = st.status_id
  and st.code = 20 -- in circulation
  and st.statustype = 'UI' -- unique items
  AND C.DISTRIBUTIONPOINT_ID = DSP.DISTRIBUTIONPOINT_ID
  AND DSP.DEPARTMENT_ID = DP.DEPARTMENT_ID
  AND PR.TYPEOFMERCHANDISE = 2 -- garments
  and cs.mailaddress_id = adr.address_id

/
create or replace view V_AGEANALYSISGARMENTSPRODUCT
 (CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, PRODUCTGROUPCODE, PRODUCTCODE, PRODUCTDESC, SIZECODE, SIZEDESC, DAYSINCIRCPREVISSUE, LASTISSUEDATE, CITY, LANGUAGECODE)
as SELECT /*+ RULE */ cs.customer_id,
  CS.CUSTOMERNUMBER, CS.NAME CUSTOMERNAME, PG.CODE PRODUCTGROUPCODE, PR.CODE PRODUCTCODE,
  (SELECT X.DESCRIPTION FROM PRODUCT_DESC X
     WHERE X.PRODUCT_ID = PR.PRODUCT_ID AND X.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,
  P.DAYSINCIRCPREVISSUE, P.LASTISSUEDATE,
  AD.CITY,
  LANGUAGES.CODE LANGUAGECODE
FROM UNIQUEITEMNONPOOL G, UNIQUEITEM H, UNIQUEITEMFIXEDINFO P, PRODUCT PR, PRODUCTGROUP PG,
  CUSTOMER CS, STATUS ST, SIZEDEFINITION SZ, ADDRESS AD, WEAREREMPLOYMENT WE, WEARER W,
  LANGUAGES
WHERE G.UNIQUEITEM_ID = H.UNIQUEITEM_ID -- NON-POOL
  AND H.UNIQUEITEM_ID = P.UNIQUEITEM_ID
  AND H.PRODUCT_ID = PR.PRODUCT_ID
  AND PR.PRODUCTGROUP_ID = PG.PRODUCTGROUP_ID
  AND H.STATUS_ID = ST.STATUS_ID
  AND ST.CODE = 20 -- IN CIRCULATION
  AND ST.STATUSTYPE = 'UI' -- UNIQUE ITEMS
  AND PR.TYPEOFMERCHANDISE = 2 -- GARMENTS
  AND H.SIZEDEFINITION_ID = SZ.SIZEDEFINITION_ID
  AND CS.VISITADDRESS_ID = AD.ADDRESS_ID
  AND G.WEAREREMPLOYMENT_ID = WE.WEAREREMPLOYMENT_ID
  AND WE.WEARER_ID = W.WEARER_ID
  AND W.CUSTOMER_ID = CS.CUSTOMER_ID

/
create or replace view V_AGEANALYSISGARMPERWEARER_AMM
 (CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, CITY, DEPARTMENTNUMBER, DEPARTMENTDESC, WEARERNUMBER, WEARERNAME, WEAREREDATEACTIVE, CIRCINVENTORY, WEARERFUNCTIONCODE, PRODUCTGROUPCODE, PRODUCTCODE, PRODUCTDESC, SIZECODE, DAYSINCIRCPREVISSUE, LASTISSUEDATE, UNIQUEITEM_ID, LANGUAGECODE, DEPTPLANT)
as select CS.CUSTOMER_ID, CS.CUSTOMERNUMBER, CS.NAME CUSTOMERNAME, adr.city,
  DP.DEPARTMENTNUMBER, DP.DESCRIPTION DEPARTMENTDESC, W.WEARERNUMBER,
  W.FULLNAME WEARERNAME, W.DATEACTIVE WEAREREDATEACTIVE, wi.circinventory, --  WF.CODE WEARERFUNCTIONCODE,
  ( select wf.code
    from   wearerfunction wf
    where  wf.wearerfunction_id = c.wearerfunction_id ) 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 = languages.language_id) productdesc,
  sz.code sizecode,
  P.DAYSINCIRCPREVISSUE, P.LASTISSUEDATE,
  h.uniqueitem_id,
  languages.code languagecode,
  ( select pl.name
    from   plant pl
    where  pl.plant_id = bu.plant_id) deptplant
from weareremployment c
, --    LEFT OUTER JOIN WEARERFUNCTION WF ON WF.WEARERFUNCTION_ID = C.WEARERFUNCTION_ID,
  uniqueitemnonpool g, uniqueitem h, uniqueitemfixedinfo p,
  PRODUCT PR, PRODUCTGROUP PG, sizedefinition sz, wearerinventory wi,
  WEARER W,
  CUSTOMER CS, businessunit bu, status st, distributionpoint DSP, address adr, languages,
  department dp
where
  c.weareremployment_id = wi.weareremployment_id
  and wi.wearerinventory_id = g.wearerinventory_id
  and g.uniqueitem_id = h.uniqueitem_id -- non-pool
  and h.uniqueitem_id = p.uniqueitem_id
  AND wi.PRODUCT_ID = PR.PRODUCT_ID
  and wi.sizedefinition_id = sz.sizedefinition_id
  AND PR.PRODUCTGROUP_ID = PG.PRODUCTGROUP_ID
  AND C.WEARER_ID = W.WEARER_ID
  AND W.CUSTOMER_ID = CS.CUSTOMER_ID
  and cs.defaultbusinessunit_id = bu.businessunit_id
  and h.status_id = st.status_id
  and st.code = 20 -- in circulation
  and st.statustype = 'UI' -- unique items
  AND C.DISTRIBUTIONPOINT_ID = DSP.DISTRIBUTIONPOINT_ID
  AND DSP.DEPARTMENT_ID = DP.DEPARTMENT_ID
  AND PR.TYPEOFMERCHANDISE = 2 -- garments
  and cs.mailaddress_id = adr.address_id

/
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)
as select q.reportparam_id,--q.businessunit_id, q.businessunit_code, q.businessunit_desc,
       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,
       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 = languages.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 = languages.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,
       languages.code languagecode
          from (select x.reportparam_id,--x.businessunit_id, x.businessunit_code, x.businessunit_desc,
                       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
                  from (select rp.reportparam_id, rp.string_value8 ShowAgeByWeeks, --uq.businessunit_id, bu.code businessunit_code, bu.description businessunit_desc,
                               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
                          from uniqueitem        uq,
                               uniqueitemfixedinfo uf,
                               businessunit      bu,
                               product           prd,
                               productgroup      pg,
                               systemuser        su,
                               reportparam       rp
                         where 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)) x
                 group by x.reportparam_id, x.ShowAgeByWeeks, --x.businessunit_id, x.businessunit_code, x.businessunit_desc,
                          x.product_id,
                          x.sizedefinition_id) q,
       sizedefinition s,
       product p, productgroup pg,
       languages
 where p.product_id = q.product_id
   and pg.productgroup_id = p.productgroup_id
   and s.sizedefinition_id = q.sizedefinition_id

/
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, STOPNUMBER, DEPOT_CODE, DEPOT_DESC, BU_CODE, BU_DESC, BUSINESSUNIT_ID, REPORTPARAM_ID, MONTH_AR, YEAR_AR)
as SELECT DISTINCT
  F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 0, REPORTPARAM.DATE_VALUE1, REPORTPARAM.DATE_VALUE2, REPORTPARAM.DATE_VALUE3, REPORTPARAM.DATE_VALUE4, A.ROUTE_ID) CURRENT_AMOUNT,
  F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 1, REPORTPARAM.DATE_VALUE1, REPORTPARAM.DATE_VALUE2, REPORTPARAM.DATE_VALUE3, REPORTPARAM.DATE_VALUE4, A.ROUTE_ID) AMOUNT_30,
  F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 2, REPORTPARAM.DATE_VALUE1, REPORTPARAM.DATE_VALUE2, REPORTPARAM.DATE_VALUE3, REPORTPARAM.DATE_VALUE4, A.ROUTE_ID) AMOUNT_60,
  F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 3, REPORTPARAM.DATE_VALUE1, REPORTPARAM.DATE_VALUE2, REPORTPARAM.DATE_VALUE3, REPORTPARAM.DATE_VALUE4, A.ROUTE_ID) AMOUNT_90,
  F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 4, REPORTPARAM.DATE_VALUE1, REPORTPARAM.DATE_VALUE2, REPORTPARAM.DATE_VALUE3, REPORTPARAM.DATE_VALUE4, A.ROUTE_ID) AMOUNT_120, /*
COALESCE(GET_AR_AMOUNT_FOR_DELTO_ROUTE(A.BUSINESSUNIT_ID,C.CUSTOMER_ID, 0,   REPORTPARAM.DATE_VALUE1, REPORTPARAM.DATE_VALUE1, A.ROUTE_ID),0) CURRENT_AMOUNT,
COALESCE(GET_AR_AMOUNT_FOR_DELTO_ROUTE(A.BUSINESSUNIT_ID,C.CUSTOMER_ID, 30,  REPORTPARAM.DATE_VALUE2, REPORTPARAM.DATE_VALUE1, A.ROUTE_ID),0) AMOUNT_30,
COALESCE(GET_AR_AMOUNT_FOR_DELTO_ROUTE(A.BUSINESSUNIT_ID,C.CUSTOMER_ID, 60,  REPORTPARAM.DATE_VALUE3, REPORTPARAM.DATE_VALUE2, A.ROUTE_ID),0) AMOUNT_60,
COALESCE(GET_AR_AMOUNT_FOR_DELTO_ROUTE(A.BUSINESSUNIT_ID,C.CUSTOMER_ID, 90,  REPORTPARAM.DATE_VALUE4, REPORTPARAM.DATE_VALUE3, A.ROUTE_ID),0) AMOUNT_90,
COALESCE(GET_AR_AMOUNT_FOR_DELTO_ROUTE(A.BUSINESSUNIT_ID,C.CUSTOMER_ID, 120, REPORTPARAM.DATE_VALUE5, REPORTPARAM.DATE_VALUE4, A.ROUTE_ID),0) 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,
(SELECT MIN(RS.STOPNUMBER) FROM ROUTESTOP RS WHERE RS.ROUTE_ID = R.ROUTE_ID AND RS.CUSTOMER_ID = C.CUSTOMER_ID ) STOPNUMBER,
D.CODE DEPOT_CODE, D.DESCRIPTION DEPOT_DESC
, BU.CODE BU_CODE, BU.DESCRIPTION BU_DESC, BU.BUSINESSUNIT_ID
, REPORTPARAM.REPORTPARAM_ID
,MONTH(A.ARTRANSACTIONDATE) MONTH_AR
,YEAR(A.ARTRANSACTIONDATE) YEAR_AR
FROM ARTRANSACTION A, ARTRANSACTIONTYPE AT, CUSTOMER_LINK C,
       ROUTE R LEFT OUTER JOIN DEPOT D ON R.DEPOT_ID = D.DEPOT_ID AND R.PLANT_ID = D.PLANT_ID
     , BUSINESSUNIT BU, REPORTPARAM
WHERE --A.CLOSINGTRANSACTION_ID IS NULL AND
A.DEBITCREDIT = 'D'
AND A.ARTRANSACTIONTYPE_ID = AT.ARTRANSACTIONTYPE_ID
AND AT.TYPENUMBER IN (1,3)
AND A.DELTOCUSTOMER_LINK_ID = C.CUSTOMER_ID
AND A.BUSINESSUNIT_ID = BU.BUSINESSUNIT_ID
----AND R.DEPOT_ID = D.DEPOT_ID AND R.PLANT_ID = D.PLANT_ID
AND A.ROUTE_ID = R.ROUTE_ID

/
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 distinct
  F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 0, REPORTPARAM.DATE_VALUE1, REPORTPARAM.DATE_VALUE2, REPORTPARAM.DATE_VALUE3, REPORTPARAM.DATE_VALUE4) CURRENT_AMOUNT,
  F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 1, REPORTPARAM.DATE_VALUE1, REPORTPARAM.DATE_VALUE2, REPORTPARAM.DATE_VALUE3, REPORTPARAM.DATE_VALUE4) AMOUNT_30,
  F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 2, REPORTPARAM.DATE_VALUE1, REPORTPARAM.DATE_VALUE2, REPORTPARAM.DATE_VALUE3, REPORTPARAM.DATE_VALUE4) AMOUNT_60,
  F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 3, REPORTPARAM.DATE_VALUE1, REPORTPARAM.DATE_VALUE2, REPORTPARAM.DATE_VALUE3, REPORTPARAM.DATE_VALUE4) AMOUNT_90,
  F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 4, REPORTPARAM.DATE_VALUE1, REPORTPARAM.DATE_VALUE2, REPORTPARAM.DATE_VALUE3, REPORTPARAM.DATE_VALUE4) AMOUNT_120,
  F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 0, REPORTPARAM.DATE_VALUE1, REPORTPARAM.DATE_VALUE2, REPORTPARAM.DATE_VALUE3, REPORTPARAM.DATE_VALUE4) +--CURRENT_AMOUNT,
  F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 1, REPORTPARAM.DATE_VALUE1, REPORTPARAM.DATE_VALUE2, REPORTPARAM.DATE_VALUE3, REPORTPARAM.DATE_VALUE4) +-- AMOUNT_30,
  F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 2, REPORTPARAM.DATE_VALUE1, REPORTPARAM.DATE_VALUE2, REPORTPARAM.DATE_VALUE3, REPORTPARAM.DATE_VALUE4) +-- AMOUNT_60,
  F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 3, REPORTPARAM.DATE_VALUE1, REPORTPARAM.DATE_VALUE2, REPORTPARAM.DATE_VALUE3, REPORTPARAM.DATE_VALUE4) +-- AMOUNT_90,
  F_GETARAGINGAMOUNT(C.CUSTOMER_ID, REPORTPARAM.NUMBER_VALUE, 4, REPORTPARAM.DATE_VALUE1, REPORTPARAM.DATE_VALUE2, REPORTPARAM.DATE_VALUE3, REPORTPARAM.DATE_VALUE4) OutstandingBalance--AMOUNT_120,
/*coalesce(GET_AR_AMOUNT_for_delto(a.businessunit_id,c.customer_id, 0,   REPORTPARAM.DATE_VALUE1, REPORTPARAM.DATE_VALUE1),0) current_amount,
coalesce(GET_AR_AMOUNT_for_delto(a.businessunit_id,c.customer_id, 30,  REPORTPARAM.DATE_VALUE2, REPORTPARAM.DATE_VALUE1),0) amount_30,
coalesce(GET_AR_AMOUNT_for_delto(a.businessunit_id,c.customer_id, 60,  REPORTPARAM.DATE_VALUE3, REPORTPARAM.DATE_VALUE2),0) amount_60,
coalesce(GET_AR_AMOUNT_for_delto(a.businessunit_id,c.customer_id, 90,  REPORTPARAM.DATE_VALUE4, REPORTPARAM.DATE_VALUE3),0) amount_90,
coalesce(GET_AR_AMOUNT_for_delto(a.businessunit_id,c.customer_id, 120, REPORTPARAM.DATE_VALUE5, REPORTPARAM.DATE_VALUE4),0) amount_120,
-----
coalesce(GET_AR_AMOUNT_for_delto(a.businessunit_id,a.deltocustomer_link_id, 0,  REPORTPARAM.DATE_VALUE1, REPORTPARAM.DATE_VALUE1),0)+-- current_amount,
coalesce(GET_AR_AMOUNT_for_delto(a.businessunit_id,a.deltocustomer_link_id, 30, REPORTPARAM.DATE_VALUE2, REPORTPARAM.DATE_VALUE1),0)+-- amount_30,
coalesce(GET_AR_AMOUNT_for_delto(a.businessunit_id,a.deltocustomer_link_id, 60, REPORTPARAM.DATE_VALUE3, REPORTPARAM.DATE_VALUE2),0)+-- amount_60,
coalesce(GET_AR_AMOUNT_for_delto(a.businessunit_id,a.deltocustomer_link_id, 90, REPORTPARAM.DATE_VALUE4, REPORTPARAM.DATE_VALUE3),0)+-- amount_90,
coalesce(GET_AR_AMOUNT_for_delto(a.businessunit_id,a.deltocustomer_link_id, 120,REPORTPARAM.DATE_VALUE5, REPORTPARAM.DATE_VALUE4),0) OutstandingBalance*/
, c.customernumber, c.name customername, c.customer_id, chain.code Chain_code, chain.name Chain_name
, bu.code BU_code, bu.description BU_desc, bu.businessunit_id
, reportparam.reportparam_id
,month(a.artransactiondate) month_ar
,year(a.artransactiondate) year_ar
from artransaction a, artransactiontype at, customer c
     LEFT OUTER JOIN chain on c.chain_id = chain.chain_id
    , businessunit bu, reportparam
where a.closingtransaction_id is null and
a.debitcredit = 'D'
and a.artransactiontype_id = at.artransactiontype_id
and at.typenumber in (1,3)
and a.deltocustomer_link_id = c.customer_id
and a.businessunit_id = bu.businessunit_id
and a.route_id is not null

/
create or replace view V_AGREEMENTREPORTS_CUS
 (LINETYPE, CUSTOMERNUMBER, CONTRACTCODE, CONTRACTOWNER, PHONENUMBER, FAXNUMBER, CONTRACTSTREET, CONTRACTCITY, CONTRACTSTATE, CONTRACTZIP)
as select 1 linetype, --owner = 1 (customer)
       c.customernumber, ct.code contractcode, c.legalname contractowner,
       c.phoneno phonenumber, c.faxno faxnumber,
       ad.street contractstreet, ad.city contractcity,
       ad.state contractstate, ad.zipcode contractzip
from customer c,
     contract ct, address ad
where ct.customer_link_id = c.customer_id
      and c.mailaddress_id = ad.address_id
      and ct.owner is null
union all
select 2 linetype, --owner = 2 (external)
       c.customernumber, ct.code contractcode, ct.owner contractowner,
       ct.phonenumber, ' ' faxnumber,
       ad.street contractstreet, ad.city contractcity,
       ad.state contractstate, ad.zipcode contractzip
from customer c, contractcustomer ctcus,
     contract ct, address ad
where ctcus.contract_id = ct.contract_id
      and ctcus.customer_link_id = c.customer_id
      and ct.address_id = ad.address_id
      and ct.owner is not null

/
create or replace view V_AGREEMENTREPTABLE_CUS
 (NR)
as select rownum nr
from (select 1 just_a_column from dual connect by level <= 15)

/
create or replace view V_ALLDELIVERIES_LTS
 (BUSINESSUNIT_ID, BUSINESSUNITCODE, CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, PRODUCTCODE, PRODUCTDESCRIPTION, SIZECODE, FINISHINGMETHODCODE, YEAR, WEEK, DAYNUMBER, DELIVERYNOTENUMBER, OCCUPANCY, CORRECTEDNOTENUMBER, STANDARDAMOUNT, STOCKCOUNT, VARIATIONMANUALENTRY, TOBEDELIVEREDAMOUNT, DELIVEREDAMOUNT)
as select pn.processbusinessunit_id businessunit_id, bu.code businessunitcode, c.customernumber,
       c.name customername, t.departmentnumber, t.description departmentdescription,
       dp.distributionpointnumber, dp.description distributionpointdescription, p.code productcode,
       (select pd.description
         from   product_desc pd
         where  pd.product_id = pnl.product_id
         and    pd.language_id = pt.language_id) productdescription, s.code sizecode,
       f.code finishingmethodcode, pn.year, pn.week, pn.daynumber, pn.notenumber deliverynotenumber,
       pn.occupancy, pn.correctednotenumber, pnl.standardamount,/*
       (select sum(iol.normstockamount)
         from   internetorder io, internetorderline iol, deliveryvariations dv
         where  io.distributionpoint_link_id = pldp.distributionpoint_id
         and    io.internetorder_id = iol.internetorder_id
         and    iol.product_link_id = pldp.product_id
         and    iol.sizedefinition_link_id = pldp.sizedefinition_id
         and    iol.finishingmethod_id = pldp.finishingmethod_id
         and    iol.type = 1 --stock count
         and    dv.deliveryvariations_id = iol.deliveryvariations_id
         and    dv.packingnote_id = pn.packingnote_id) normstockamount,*/
       (select sum(iol.quantity)
         from   internetorder io, internetorderline iol, deliveryvariations dv
         where  io.distributionpoint_link_id = pldp.distributionpoint_id
         and    io.internetorder_id = iol.internetorder_id
         and    iol.product_link_id = pldp.product_id
         and    iol.sizedefinition_link_id = pldp.sizedefinition_id
         and    iol.finishingmethod_id = pldp.finishingmethod_id
         and    iol.type = 1 --stock count
         and    dv.deliveryvariations_id = iol.deliveryvariations_id
         and    dv.packingnote_id = pn.packingnote_id) stockcount,/*
       (select sum(dv.amount)
         from   deliveryvariations dv
         where  dv.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.origin = 1) variationsoilcount,
       (select sum(dv.amount)
         from   deliveryvariations dv
         where  dv.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.origin = 2) variationstockcount,*/
       (select sum(dv.amount)
         from   deliveryvariations dv
         where  dv.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.origin = 3) variationmanualentry,/*
       (select sum(dv.amount)
         from   deliveryvariations dv
         where  dv.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.origin = 4) variationpackingnote,
       (select sum(dv.amount)
         from   deliveryvariations dv
         where  dv.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.origin = 5) variationdeliverynote,
       (select sum(dv.amount)
         from   deliveryvariations dv
         where  dv.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.origin = 6) variationelectronicorder,
       (select sum(dv.amount)
         from   deliveryvariations dv
         where  dv.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.origin = 7) variationreplacement,
       (select sum(dv.amount)
         from   deliveryvariations dv
         where  dv.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.origin = 8) variationsettlement,*/
       pnl.tobedeliveredamount, pnl.deliveredamount
from   packingnote pn, packingnoteline pnl, productlistperdistribpoint pldp, businessunit bu,
       plant pt, distributionpoint dp, product p, sizedefinition s, finishingmethod f, customer c,
       department t
where  pn.packingnote_id = pnl.packingnote_id
and    pn.status_id in (select st.status_id
                        from   status st
                        where  st.statustype = 'PN'
                        and    st.code <> '40'
                        and    st.code <> '60')
and    pn.distributionpoint_id = pldp.distributionpoint_id
and    pnl.product_id = pldp.product_id
and    pnl.sizedefinition_id = pldp.sizedefinition_id
and    pnl.finishingmethod_id = pldp.finishingmethod_id
and    pn.processbusinessunit_id = bu.businessunit_id
and    bu.plant_id = pt.plant_id
and    pn.distributionpoint_id = dp.distributionpoint_id
and    pnl.product_id = p.product_id
and    pnl.sizedefinition_id = s.sizedefinition_id
and    pnl.finishingmethod_id = f.finishingmethod_id
and    dp.department_id = t.department_id
and    t.customer_id = c.customer_id

/
create or replace view V_ALT_SUPLIER_PRODUCTS
 (PRIO, SUPPLIERNUMBER, SUPPLIERNAME, PURCHASEPRICE, CURRENCY_ID, DELIVERYDAYS, MINORDERQTY, BOXQUANTITY, CALCULATEDQTY, PRODUCT_CODE, PROD_DESC, SIZEDEFINITION_CODE, PRODUCT_ID, SIZEDEFINITION_ID, SUPPLIERTYPE, SUPPLIER_ID, SUPPLIERPRODUCT_ID, STOCKROOM_ID)
as SELECT 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.Currency_Id,
Supplierproduct.Deliverydays,
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
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,
--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 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
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_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, cast
(DECODE(bu.code, 'SMZL' , cl.customernumber || ' ' || cl.name, bu.code) as varchar2(60)
) 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, -- sum(st.quantity) total_quantity,
(case when tt.transactiontype_id in (10,12,13,15,16,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, stockreservationpergrade sg, stockdefinitionperitem sd, qualitygrade q ,
      stockroom sr, workorder wo, customer_link cl,  businessunit bu,
      product p, productgroup pg, sizedefinition s, reasoncode r,  transactiontype tt, languages lan
where st.stockreservationpergrade_id = sg.stockreservationpergrade_id
and sg.stockdefinitionperitem_id = sd.stockdefinitionperitem_id
and sg.qualitygrade_id = q.qualitygrade_id
and p.product_id = sd.product_id
and p.productgroup_id = pg.productgroup_id
and s.sizedefinition_id = sd.sizedefinition_id
and r.reasoncode_id = st.reasoncode_id
and wo.workordernumber = st.documentnumber
and cl.customer_link_id = wo.customer_link_id
and bu.businessunit_id = wo.businessunit_id
and sr.stockroom_id = sd.stockroom_id
and st.transactiontype_id=tt.transactiontype_id
and q.defectitem = 'N'
and st.documenttype in (3,6,7,8,9,10,11,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, cast
(DECODE(bu.code,  'SMZL', bu.code, bu.code) as varchar2(60)
) 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,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, stockreservationpergrade sg, stockdefinitionperitem sd, qualitygrade q ,
      stockroom sr, businessunit bu, product p, productgroup pg, sizedefinition s, reasoncode r, transactiontype tt, languages lan
where st.stockreservationpergrade_id = sg.stockreservationpergrade_id
and sg.stockdefinitionperitem_id = sd.stockdefinitionperitem_id
and sg.qualitygrade_id = q.qualitygrade_id
and p.product_id = sd.product_id
and p.productgroup_id = pg.productgroup_id
and s.sizedefinition_id = sd.sizedefinition_id
and r.reasoncode_id = st.reasoncode_id
and bu.businessunit_id = sr.managedbybu_id
and sr.stockroom_id = sd.stockroom_id
and st.transactiontype_id=tt.transactiontype_id
and 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,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_ANALYSISSTOCKTRANSACTION_AUS
 (LINETYPE, LINETEXT, TRANSACTIONTYPE_ID, STOCKTRANSACTION_ID, BUSINESSUNITCODE, STOCKROOMCODE, STOCKROOMNAME, TRANSACTIONDATE, PRODUCTCODE, SIZECODE, PRICE, QUANTITY, ACCOUNTNUMBER, AMOUNT, TRANSACT, LATCODE, DEBITCREDIT)
as select 1 linetype,
       '4.4.1 Collect Merchandise Issue - transaction types (30, 31, 32, 33)' linetext,
       st.transactiontype_id,
       st.stocktransaction_id,
       bu.code businessunitcode,
       sr.code stockroomcode,
       sr.name stockroomname,
       st.transactiondate,
       p.code productcode,
       sizedf.code sizecode,
       st.calculationprice price,
       st.quantity,
       coalesce(lpad(la.exportcode, 5, '0'), '00000') || '.' ||
       (select substr(tg.code, -4)
          from turnovergroup tg
         where tg.turnovergroup_id = p.rentturnovergroup_id) accountnumber,
       abs(st.calculationprice * st.quantity) amount,
       'Merchandise Issue' transact,
       lat.code latcode,
       case
         when --(st.calculationprice * st.quantity) <> 0 and
              lat.code = 'SHLFST' then
          'CREDIT'
         when --(st.calculationprice * st.quantity) <> 0 and
              lat.code = 'INSERV' then
          'DEBIT'
         else
          'DEBITCREDIT'
       end debitcredit
  from stocktransaction         st,
       stockreservationpergrade str,
       stockdefinitionperitem   sdi,
       businessunit             bu,
       stockroom                sr,
       ledgeraccntsperproduct   lap,
       ledgeraccnttype          lat,
       ledgeraccounts           la,
       product                  p,
       sizedefinition           sizedf,
       product                  p2,
       qualitygrade             q
 where st.stockreservationpergrade_id = str.stockreservationpergrade_id
   and str.stockdefinitionperitem_id = sdi.stockdefinitionperitem_id
   and sdi.stockroom_id = sr.stockroom_id
   and bu.businessunit_id = sr.managedbybu_id
   and sdi.product_id = p.product_id
   and sdi.sizedefinition_id = sizedf.sizedefinition_id
   and ((p.typeofmerchandise = 1 and p2.code = 'ZZ1') or
       (p.typeofmerchandise = 2 and p2.code = 'ZZ2') or
       (p.typeofmerchandise = 3 and p2.code = 'ZZ3') or
       (p.typeofmerchandise > 3 and p2.code = 'ZZ4'))
   and lap.product_id = p2.product_id
   and lap.ledgeraccnttype_id = lat.ledgeraccnttype_id
   and lap.ledgeraccounts_id = la.ledgeraccounts_id
   and lat.code in ('INSERV', 'SHLFST')
   and st.transactiontype_id in (30, 31, 32, 33)
   and str.qualitygrade_id = q.qualitygrade_id
   and q.newgarment = 'Y'
   and st.erpexport = 'Y'
union all
select 2 linetype,
       '4.4.2 Collect Merchandise Issue - transaction types (50)' linetext,
       st.transactiontype_id,
       st.stocktransaction_id,
       bu.code businessunitcode,
       sr.code stockroomcode,
       sr.name stockroomname,
       st.transactiondate,
       p.code productcode,
       sizedf.code sizecode,
       st.calculationprice price,
       st.quantity,
       coalesce(lpad(la.exportcode, 5, '0'), '00000') || '.' ||
       (select substr(tg.code, -4)
          from turnovergroup tg
         where tg.turnovergroup_id = p.rentturnovergroup_id) accountnumber,
       abs(st.calculationprice * st.quantity) amount,
       --calculation price should be avgpp based on st.valuationmethod=2
       --lat.code transact --becomes merchendise issue
       'Merchandise Issue' transact,
       lat.code latcode,
       case
         when --(st.calculationprice * st.quantity) <> 0 and
              lat.code = 'SHLFST' then
          'CREDIT'
         when --(st.calculationprice * st.quantity) <> 0 and
              lat.code = 'COSTOG' then
          'DEBIT'
         else
          'DEBITCREDIT'
       end debitcredit
  from stocktransaction         st,
       stockreservationpergrade str,
       stockdefinitionperitem   sdi,
       businessunit             bu,
       stockroom                sr,
       ledgeraccntsperproduct   lap,
       ledgeraccnttype          lat,
       ledgeraccounts           la,
       product                  p,
       sizedefinition           sizedf,
       product                  p2,
       qualitygrade             q
 where st.stockreservationpergrade_id = str.stockreservationpergrade_id
   and str.stockdefinitionperitem_id = sdi.stockdefinitionperitem_id
   and sdi.stockroom_id = sr.stockroom_id
   and bu.businessunit_id = sr.managedbybu_id
   and sdi.product_id = p.product_id
   and sdi.sizedefinition_id = sizedf.sizedefinition_id
   and ((p.typeofmerchandise = 1 and p2.code = 'ZZ1') or
       (p.typeofmerchandise = 2 and p2.code = 'ZZ2') or
       (p.typeofmerchandise = 3 and p2.code = 'ZZ3') or
       (p.typeofmerchandise > 3 and p2.code = 'ZZ4'))
   and lap.product_id = p2.product_id
   and lap.ledgeraccnttype_id = lat.ledgeraccnttype_id
   and lap.ledgeraccounts_id = la.ledgeraccounts_id
   and lat.code in ('COSTOG', 'SHLFST')
   and st.transactiontype_id = 50
   and str.qualitygrade_id = q.qualitygrade_id
   and q.newgarment = 'Y'
   and st.erpexport = 'Y'
union all
select 3 linetype,
       '4.4.4 Receiving transactions' linetext,
       st.transactiontype_id,
       st.stocktransaction_id,
       bu.code businessunitcode,
       sr.code stockroomcode,
       sr.name stockroomname,
       st.transactiondate,
       p.code productcode,
       sizedf.code sizecode,
       0 price, --(st.calculationprice - pol.purchaseprice) price,
       st.quantity,
       coalesce(lpad(la.exportcode, 5, '0'), '00000') || '.' ||
       (select substr(tg.code, -4)
          from turnovergroup tg
         where tg.turnovergroup_id = p.rentturnovergroup_id) accountnumber,
       abs((sta.prevavgpurchaseprice - pol.purchaseprice) * st.quantity) amount,
       --lat.code transact --becomes Receipt PPV - Vendor
       'Receipt PPV - Vendor' transact,
       lat.code latcode,
       case  ---change wbo  ((coalesce(sta.prevavgpurchaseprice, st.calculationprice) - pol.purchaseprice) * st.quantity)
         when ((sta.prevavgpurchaseprice - pol.purchaseprice) * st.quantity) < 0 and
              lat.code = 'SHLFST' then
          'DEBIT'
         when ((sta.prevavgpurchaseprice - pol.purchaseprice) * st.quantity) < 0 and
              lat.code = 'INSERV' then
          'CREDIT'
         when ((sta.prevavgpurchaseprice - pol.purchaseprice) * st.quantity) > 0 and
              lat.code = 'SHLFST' then
          'CREDIT'
         when ((sta.prevavgpurchaseprice - pol.purchaseprice) * st.quantity) > 0 and
              lat.code = 'INSERV' then
          'DEBIT'
         when ((sta.prevavgpurchaseprice - pol.purchaseprice) * st.quantity) = 0 and
              lat.code = 'SHLFST' then
          'CREDIT'
         when ((sta.prevavgpurchaseprice - pol.purchaseprice) * st.quantity) = 0 and
              lat.code = 'INSERV' then
          'DEBIT'
         else
          'DEBITCREDIT'
       end debitcredit
  from stocktransaction              st,
       stockvalueavgpp sta,
       stockreservationpergrade      str,
       stockdefinitionperitem        sdi,
       businessunit                  bu,
       stockroom                     sr,
       ledgeraccntsperproduct        lap,
       ledgeraccnttype               lat,
       ledgeraccounts                la,
       purchaseorderstocktransaction postr,
       purchaseorderline             pol,
       product                       p,
       sizedefinition                sizedf,
       product                       p2,
       qualitygrade                  q
 where st.stockreservationpergrade_id = str.stockreservationpergrade_id
   and str.stockdefinitionperitem_id = sdi.stockdefinitionperitem_id
   and sdi.stockroom_id = sr.stockroom_id
   and bu.businessunit_id = sr.managedbybu_id
   and sdi.product_id = p.product_id
   and sdi.sizedefinition_id = sizedf.sizedefinition_id
   and ((p.typeofmerchandise = 1 and p2.code = 'ZZ1') or
       (p.typeofmerchandise = 2 and p2.code = 'ZZ2') or
       (p.typeofmerchandise = 3 and p2.code = 'ZZ3') or
       (p.typeofmerchandise > 3 and p2.code = 'ZZ4'))
   and lap.product_id = p2.product_id
   and lap.ledgeraccnttype_id = lat.ledgeraccnttype_id
   and lap.ledgeraccounts_id = la.ledgeraccounts_id
   and postr.stocktransaction_id = st.stocktransaction_id
   and pol.purchaseorderline_id = postr.purchaseorderline_id
   and lat.code in ('INSERV', 'SHLFST')
   and st.transactiontype_id = 12
   and str.qualitygrade_id = q.qualitygrade_id
   and sta.stocktransaction_id=st.stocktransaction_id
   and sta.prevstockqty > 0 and sta.prevavgpurchaseprice > 0
   and q.newgarment = 'Y'
   and st.erpexport = 'Y'
union all
select 3 linetype,
       '4.4.4 Receiving transactions' linetext,
       st.transactiontype_id,
       st.stocktransaction_id,
       bu.code businessunitcode,
       sr.code stockroomcode,
       sr.name stockroomname,
       st.transactiondate,
       p.code productcode,
       sizedf.code sizecode,
       (st.calculationprice - pol.purchaseprice) price,
       st.quantity,
       coalesce(lpad(la.exportcode, 5, '0'), '00000') || '.' ||
       (select substr(tg.code, -4)
          from turnovergroup tg
         where tg.turnovergroup_id = p.rentturnovergroup_id) accountnumber,
        abs((sta.prevavgpurchaseprice - pol.purchaseprice) * st.quantity) amount,
       --to be verif
       --lat.code transact --becomes Receipt PPV - DC
       'Receipt PPV - DC' transact,
       lat.code latcode,
      case  --((coalesce(x.prevavgpurchaseprice, st.calculationprice) - pol.purchaseprice) * coalesce(x.prevstockqty,st.quantity))
         when ((sta.prevavgpurchaseprice - pol.purchaseprice) * st.quantity) < 0 and
              lat.code = 'SHLFST' then
          'DEBIT'
         when ((sta.prevavgpurchaseprice - pol.purchaseprice) * st.quantity) < 0 and
              lat.code = 'INSERV' then
          'CREDIT'
         when ((sta.prevavgpurchaseprice - pol.purchaseprice) * st.quantity) > 0 and
              lat.code = 'SHLFST' then
          'CREDIT'
         when ((sta.prevavgpurchaseprice - pol.purchaseprice) * st.quantity) > 0 and
              lat.code = 'INSERV' then
          'DEBIT'
         when ((sta.prevavgpurchaseprice - pol.purchaseprice) * st.quantity) = 0 and
              lat.code = 'SHLFST' then
          'CREDIT'
         when ((sta.prevavgpurchaseprice - pol.purchaseprice) * st.quantity) = 0 and
              lat.code = 'INSERV' then
          'DEBIT'
         else
          'DEBITCREDIT'
       end debitcredit
  from stocktransaction              st,
       stockvalueavgpp               sta,
       stockreservationpergrade      str,
       stockdefinitionperitem        sdi,
       businessunit                  bu,
       stockroom                     sr,
       ledgeraccntsperproduct        lap,
       ledgeraccnttype               lat,
       ledgeraccounts                la,
       purchaseorderstocktransaction postr,
       purchaseorderline             pol,
       product                       p,
       sizedefinition                sizedf,
       product                       p2,
       qualitygrade                  q
 where st.stockreservationpergrade_id = str.stockreservationpergrade_id
   and str.stockdefinitionperitem_id = sdi.stockdefinitionperitem_id
   and sdi.stockroom_id = sr.stockroom_id
   and bu.businessunit_id = sr.managedbybu_id
   and sdi.product_id = p.product_id
   and sdi.sizedefinition_id = sizedf.sizedefinition_id
   and ((p.typeofmerchandise = 1 and p2.code = 'ZZ1') or
       (p.typeofmerchandise = 2 and p2.code = 'ZZ2') or
       (p.typeofmerchandise = 3 and p2.code = 'ZZ3') or
       (p.typeofmerchandise > 3 and p2.code = 'ZZ4'))
   and lap.product_id = p2.product_id
   and lap.ledgeraccnttype_id = lat.ledgeraccnttype_id
   and lap.ledgeraccounts_id = la.ledgeraccounts_id
   and postr.stocktransaction_id = st.stocktransaction_id
   and pol.purchaseorderline_id = postr.purchaseorderline_id
   and lat.code in ('INSERV', 'SHLFST')
   and st.transactiontype_id = 411
   and str.qualitygrade_id = q.qualitygrade_id
   and sta.stocktransaction_id=st.stocktransaction_id
   and sta.prevstockqty > 0 and sta.prevavgpurchaseprice > 0
   and q.newgarment = 'Y'
   and st.erpexport = 'Y'
union all
 select 3 linetype,
       '4.4.4 Receiving transactions' linetext,
       st.transactiontype_id,
       st.stocktransaction_id,
       bu.code businessunitcode,
       sr.code stockroomcode,
       sr.name stockroomname,
       st.transactiondate,
       p.code productcode,
       sizedf.code sizecode,
      (sta.prevavgpurchaseprice-st.calculationprice) price,
       st.quantity,
       coalesce(lpad(la.exportcode, 5, '0'), '00000') || '.' ||
       (select substr(tg.code, -4)
          from turnovergroup tg
         where tg.turnovergroup_id = p.rentturnovergroup_id) accountnumber,
       abs((sta.prevavgpurchaseprice-st.calculationprice) * st.quantity) amount,
       --lat.code transact --becomes Receipt PPV - IRR
       'Receipt PPV - IRR' transact,
       lat.code latcode,
       case
         when ((sta.prevavgpurchaseprice-st.calculationprice) * st.quantity) < 0 and
              lat.code = 'SHLFST' then
          'DEBIT'
         when ((sta.prevavgpurchaseprice-st.calculationprice) * st.quantity) < 0 and
              lat.code = 'INSERV' then
          'CREDIT'
         when ((sta.prevavgpurchaseprice-st.calculationprice)* st.quantity) > 0 and
              lat.code = 'SHLFST' then
          'CREDIT'
         when ((sta.prevavgpurchaseprice-st.calculationprice) * st.quantity) > 0 and
              lat.code = 'INSERV' then
          'DEBIT'
         when ((sta.prevavgpurchaseprice-st.calculationprice) * st.quantity) = 0 and
              lat.code = 'SHLFST' then
          'CREDIT'
         when ((sta.prevavgpurchaseprice-st.calculationprice)* st.quantity) = 0 and
              lat.code = 'INSERV' then
          'DEBIT'
         else
          'DEBITCREDIT'
       end debitcredit
  from stocktransaction         st,
       stockreservationpergrade str,
       stockdefinitionperitem   sdi,
       businessunit             bu,
       stockroom                sr,
       ledgeraccntsperproduct   lap,
       ledgeraccnttype          lat,
       ledgeraccounts           la,
       product                  p,
       sizedefinition           sizedf,
       product                  p2,
       qualitygrade             q
        ,stockvalueavgpp               sta
 where st.stockreservationpergrade_id = str.stockreservationpergrade_id
   and str.stockdefinitionperitem_id = sdi.stockdefinitionperitem_id
   and sdi.stockroom_id = sr.stockroom_id
   and bu.businessunit_id = sr.managedbybu_id
   and sdi.product_id = p.product_id
   and sdi.sizedefinition_id = sizedf.sizedefinition_id
   and ((p.typeofmerchandise = 1 and p2.code = 'ZZ1') or
       (p.typeofmerchandise = 2 and p2.code = 'ZZ2') or
       (p.typeofmerchandise = 3 and p2.code = 'ZZ3') or
       (p.typeofmerchandise > 3 and p2.code = 'ZZ4'))
   and lap.product_id = p2.product_id
   and lap.ledgeraccnttype_id = lat.ledgeraccnttype_id
   and lap.ledgeraccounts_id = la.ledgeraccounts_id
   and lat.code in ('INSERV', 'SHLFST')
   and st.transactiontype_id in (10, 15)
   and str.qualitygrade_id = q.qualitygrade_id
    and sta.stocktransaction_id=st.stocktransaction_id
   and sta.prevstockqty > 0 and sta.prevavgpurchaseprice>0
   and q.newgarment = 'Y'
   and st.erpexport = 'Y'
union all
select 5 linetype,
       '4.4.5  New product issued' linetext,
       st.transactiontype_id,
       st.stocktransaction_id,
       bu.code businessunitcode,
       sr.code stockroomcode,
       sr.name stockroomname,
       st.transactiondate,
       p.code productcode,
       sizedf.code sizecode,
       st.calculationprice price,
       st.quantity,
       coalesce(lpad(la.exportcode, 5, '0'), '00000') || '.' ||
       (select substr(tg.code, -4)
          from turnovergroup tg
         where tg.turnovergroup_id = p.rentturnovergroup_id) accountnumber,
       abs(st.calculationprice * st.quantity) amount,
       --lat.code transact --becomes merchendise issue
       'Merchandise Issue' transact,
       --rs.code reasoncode,
       lat.code latcode,
       case
         when /*(st.calculationprice * st.quantity) <> 0 and*/
          lat.code = 'SHLFST' then
          'CREDIT'
         when /*(st.calculationprice * st.quantity) <> 0 and*/
          lat.code = 'INSERV' then
          'DEBIT'
         else
          'DEBITCREDIT'
       end debitcredit
  from stocktransaction         st,
       stockreservationpergrade str,
       stockdefinitionperitem   sdi,
       businessunit             bu,
       stockroom                sr,
       ledgeraccntsperproduct   lap,
       ledgeraccnttype          lat,
       ledgeraccounts           la,
       reasoncode               rs,
       product                  p,
       sizedefinition           sizedf,
       product                  p2,
       qualitygrade             q
 where st.stockreservationpergrade_id = str.stockreservationpergrade_id
   and str.stockdefinitionperitem_id = sdi.stockdefinitionperitem_id
   and sdi.stockroom_id = sr.stockroom_id
   and bu.businessunit_id = sr.managedbybu_id
   and sdi.product_id = p.product_id
   and sdi.sizedefinition_id = sizedf.sizedefinition_id
   and ((p.typeofmerchandise = 1 and p2.code = 'ZZ1') or
       (p.typeofmerchandise = 2 and p2.code = 'ZZ2') or
       (p.typeofmerchandise = 3 and p2.code = 'ZZ3') or
       (p.typeofmerchandise > 3 and p2.code = 'ZZ4'))
   and lap.product_id = p2.product_id
   and lap.ledgeraccnttype_id = lat.ledgeraccnttype_id
   and lap.ledgeraccounts_id = la.ledgeraccounts_id
   and lat.code in ('INSERV', 'SHLFST')
   and st.transactiontype_id in (22, 23)
   and st.reasoncode_id = rs.reasoncode_id
   and str.qualitygrade_id = q.qualitygrade_id
   and q.newgarment = 'Y'
   and st.erpexport = 'Y'
union all
select 6 linetype,
       '4.4.6  Price adjustment' linetext,
       savg.transactiontype transactiontype_id,
       savg.stockvalueavgpp_id stocktransaction_id,
       bu.code businessunitcode,
       sr.code stockroomcode,
       sr.name stockroomname,
       savg.transactiondate,
       p.code productcode,
       sizedf.code sizecode,
       savg.avgpurchaseprice - savg.prevavgpurchaseprice price,
       savg.actualstockquantity quantity,
       coalesce(lpad(la.exportcode, 5, '0'), '00000') || '.' ||
       (select substr(tg.code, -4)
          from turnovergroup tg
         where tg.turnovergroup_id = p.rentturnovergroup_id) accountnumber,
       abs((savg.avgpurchaseprice - savg.prevavgpurchaseprice) *
       savg.actualstockquantity) amount,
       'Price Override' transact,
       lat.code latcode,
       --'DEBITCREDIT' debitcredit
       case
         when ((savg.avgpurchaseprice - savg.prevavgpurchaseprice) *
              savg.actualstockquantity) < 0 and lat.code = 'SHLFST' then
          'CREDIT'
         when ((savg.avgpurchaseprice - savg.prevavgpurchaseprice) *
              savg.actualstockquantity) < 0 and lat.code = 'INSERV' then
          'DEBIT'
         when ((savg.avgpurchaseprice - savg.prevavgpurchaseprice) *
              savg.actualstockquantity) > 0 and lat.code = 'SHLFST' then
          'DEBIT'
         when ((savg.avgpurchaseprice - savg.prevavgpurchaseprice) *
              savg.actualstockquantity) > 0 and lat.code = 'INSERV' then
          'CREDIT'
         when ((savg.avgpurchaseprice - savg.prevavgpurchaseprice) * savg.actualstockquantity) = 0 and
              lat.code = 'SHLFST' then
          'CREDIT'
         when ((savg.avgpurchaseprice - savg.prevavgpurchaseprice) * savg.actualstockquantity) = 0 and
              lat.code = 'INSERV' then
          'DEBIT'
         else
          'DEBITCREDIT'
       end debitcredit
  from stockvalueavgpp        savg,
       businessunit           bu,
       stockroom              sr,
       ledgeraccntsperproduct lap,
       ledgeraccnttype        lat,
       ledgeraccounts         la,
       product                p,
       sizedefinition         sizedf,
       product                p2,
       qualitygrade           q
 where savg.stockroom_id = sr.stockroom_id
   and bu.businessunit_id = sr.managedbybu_id
   and savg.product_link_id = p.product_id
   and savg.sizedefinition_link_id = sizedf.sizedefinition_id
   and ((p.typeofmerchandise = 1 and p2.code = 'ZZ1') or
       (p.typeofmerchandise = 2 and p2.code = 'ZZ2') or
       (p.typeofmerchandise = 3 and p2.code = 'ZZ3') or
       (p.typeofmerchandise > 3 and p2.code = 'ZZ4'))
   and lap.product_id = p2.product_id
   and lap.ledgeraccnttype_id = lat.ledgeraccnttype_id
   and lap.ledgeraccounts_id = la.ledgeraccounts_id
   and lat.code in ('INSERV', 'SHLFST')
   and savg.transactiontype = 3 --price change
   and savg.qualitygrade_id = q.qualitygrade_id
   and savg.actualstockquantity <> 0
   and q.newgarment = 'Y'
   and savg.erpexport = 'Y'
union all
select 7 linetype,
       '4.4.7  Write off' linetext,
       st.transactiontype_id,
       st.stocktransaction_id,
       bu.code businessunitcode,
       sr.code stockroomcode,
       sr.name stockroomname,
       st.transactiondate,
       p.code productcode,
       sizedf.code sizecode,
       st.calculationprice price,
       st.quantity,
       case
         when lat.code = 'OBS' then
          coalesce(lpad(la.exportcode, 5, '0'), '00000') || '.' || '0000'
         else
          coalesce(lpad(la.exportcode, 5, '0'), '00000') || '.' ||
          (select substr(tg.code, -4)
             from turnovergroup tg
            where tg.turnovergroup_id = p.rentturnovergroup_id)
       end accountnumber,
       abs(st.calculationprice * st.quantity) amount,
       'Write Off Obsolete' transact,
       lat.code latcode,
       case
         when --(st.calculationprice * st.quantity) <> 0 and
              lat.code = 'SHLFST' then
          'CREDIT'
         when --(st.calculationprice * st.quantity) <> 0 and
              lat.code = 'OBS' then
          'DEBIT'
         else
          'DEBITCREDIT'
       end debitcredit
  from stocktransaction         st,
       stockreservationpergrade str,
       stockdefinitionperitem   sdi,
       businessunit             bu,
       stockroom                sr,
       ledgeraccntsperproduct   lap,
       ledgeraccnttype          lat,
       ledgeraccounts           la,
       product                  p,
       sizedefinition           sizedf,
       product                  p2,
       qualitygrade             q
 where st.stockreservationpergrade_id = str.stockreservationpergrade_id
   and str.stockdefinitionperitem_id = sdi.stockdefinitionperitem_id
   and sdi.stockroom_id = sr.stockroom_id
   and bu.businessunit_id = sr.managedbybu_id
   and sdi.product_id = p.product_id
   and sdi.sizedefinition_id = sizedf.sizedefinition_id
   and ((p.typeofmerchandise = 1 and p2.code = 'ZZ1') or
       (p.typeofmerchandise = 2 and p2.code = 'ZZ2') or
       (p.typeofmerchandise = 3 and p2.code = 'ZZ3') or
       (p.typeofmerchandise > 3 and p2.code = 'ZZ4'))
   and lap.product_id = p2.product_id
   and lap.ledgeraccnttype_id = lat.ledgeraccnttype_id
   and lap.ledgeraccounts_id = la.ledgeraccounts_id
   and lat.code in ('OBS', 'SHLFST')
   and st.transactiontype_id in (40, 41, 42, 44)
   and str.qualitygrade_id = q.qualitygrade_id
   and q.newgarment = 'Y'
   and st.erpexport = 'Y'
union all
select 8 linetype,
       '4.4.8  Stock correction' linetext,
       st.transactiontype_id,
       st.stocktransaction_id,
       bu.code businessunitcode,
       sr.code stockroomcode,
       sr.name stockroomname,
       st.transactiondate,
       p.code productcode,
       sizedf.code sizecode,
       st.calculationprice price,
       st.quantity,
       coalesce(lpad(la.exportcode, 5, '0'), '00000') || '.' ||
       (select substr(tg.code, -4)
          from turnovergroup tg
         where tg.turnovergroup_id = p.rentturnovergroup_id) accountnumber,
       abs(st.calculationprice * st.quantity) amount,
       'Physical Adjustment' transact,
       lat.code latcode,
       case
         when (st.calculationprice * st.quantity) < 0 and
              lat.code = 'SHLFST' then
          'CREDIT'
         when (st.calculationprice * st.quantity) < 0 and
              lat.code = 'COSTOG' then
          'DEBIT'
         when (st.calculationprice * st.quantity) > 0 and
              lat.code = 'SHLFST' then
          'DEBIT'
         when (st.calculationprice * st.quantity) > 0 and
              lat.code = 'COSTOG' then
          'CREDIT'
         when (st.calculationprice * st.quantity) = 0 and
              lat.code = 'SHLFST' then
          'CREDIT'
         when (st.calculationprice * st.quantity) = 0 and
              lat.code = 'COSTOG' then
          'DEBIT'
         else
          'DEBITCREDIT'
       end debitcredit
  from stocktransaction         st,
       stockreservationpergrade str,
       stockdefinitionperitem   sdi,
       businessunit             bu,
       stockroom                sr,
       ledgeraccntsperproduct   lap,
       ledgeraccnttype          lat,
       ledgeraccounts           la,
       product                  p,
       sizedefinition           sizedf,
       product                  p2,
       qualitygrade             q
 where st.stockreservationpergrade_id = str.stockreservationpergrade_id
   and str.stockdefinitionperitem_id = sdi.stockdefinitionperitem_id
   and sdi.stockroom_id = sr.stockroom_id
   and bu.businessunit_id = sr.managedbybu_id
   and sdi.product_id = p.product_id
   and sdi.sizedefinition_id = sizedf.sizedefinition_id
   and ((p.typeofmerchandise = 1 and p2.code = 'ZZ1') or
       (p.typeofmerchandise = 2 and p2.code = 'ZZ2') or
       (p.typeofmerchandise = 3 and p2.code = 'ZZ3') or
       (p.typeofmerchandise > 3 and p2.code = 'ZZ4'))
   and lap.product_id = p2.product_id
   and lap.ledgeraccnttype_id = lat.ledgeraccnttype_id
   and lap.ledgeraccounts_id = la.ledgeraccounts_id
   and lat.code in ('COSTOG', 'SHLFST')
   and st.transactiontype_id = 84
   and str.qualitygrade_id = q.qualitygrade_id
   and q.newgarment = 'Y'
   and st.erpexport = 'Y'
union all
select 9 linetype,
       '4.4.9  Stock quantities ? relates to month end inventory' linetext,
       -1 transactiontype_id,
       -1 stocktransaction_id,
       bu.code businessunitcode,
       sr.code stockroomcode,
       sr.name stockroomname,
       sh.statusquodate transactiondate,
       p.code productcode,
       sizedf.code sizecode,
       f_getavgpurchasepricesatdate(srg.stockreservationpergrade_id,
                                    sh.statusquodate) price,
       sqq.qtynew quantity,
       coalesce(lpad(la.exportcode, 5, '0'), '00000') || '.' ||
       (select substr(tg.code, -4)
          from turnovergroup tg
         where tg.turnovergroup_id = p.rentturnovergroup_id) accountnumber,
       abs(sqq.qtynew *
       f_getavgpurchasepricesatdate(srg.stockreservationpergrade_id,
                                     sh.statusquodate)) amount,
       --'Stock quantities ? relates to Physical Adjustment' transact,
       sr.code transact,
       lat.code latcode,
       case
         when lat.code = 'SHLFST' then
          'CREDIT'
         when lat.code = 'INSERV' then
          'DEBIT'
         else
          'DEBITCREDIT'
       end debitcredit
  from sqstockquantity          sqq,
       statusquoheader          sh,
       ledgeraccntsperproduct   lap,
       ledgeraccnttype          lat,
       ledgeraccounts           la,
       stockroom                sr,
       stockreservationpergrade srg,
       stockdefinitionperitem   sdi,
       businessunit             bu,
       product                  p,
       sizedefinition           sizedf,
       product                  p2,
       qualitygrade             q
 where sqq.statusquoheader_id = sh.statusquoheader_id
   and bu.businessunit_id = sh.processbusinessunit_id
   and sdi.product_id = p.product_id
   and sdi.sizedefinition_id = sizedf.sizedefinition_id
   and ((p.typeofmerchandise = 1 and p2.code = 'ZZ1') or
       (p.typeofmerchandise = 2 and p2.code = 'ZZ2') or
       (p.typeofmerchandise = 3 and p2.code = 'ZZ3') or
       (p.typeofmerchandise > 3 and p2.code = 'ZZ4'))
   and lap.product_id = p2.product_id
   and lap.ledgeraccnttype_id = lat.ledgeraccnttype_id
   and lap.ledgeraccounts_id = la.ledgeraccounts_id
   and lat.code in ('INSERV', 'SHLFST')
   and sqq.stockroom_id = sr.stockroom_id
   and sh.statusquotype = 4 --stockquantities
   and srg.stockdefinitionperitem_id = sdi.stockdefinitionperitem_id
   and srg.qualitygrade_id =
       (select qg.qualitygrade_id from qualitygrade qg where qg.code = 'N')
   and sdi.product_id = sqq.product_link_id
   and sdi.sizedefinition_id = sqq.sizedefinition_link_id
   and sdi.stockroom_id = sqq.stockroom_id
   and srg.qualitygrade_id = q.qualitygrade_id
   and q.newgarment = 'Y'
   and sh.erpexport = 'Y'

/
create or replace view V_APPENDIXCOSTSPERCLIENT
 (LINETYPE, INVOICEHEADER_ID, INVOICENUMBER, INVOICEDATE, ENDDATE, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, DELTOSTREET, DELTOZIPCODE, DELTOCITY, CLIENTNUMBER, CLIENTNAME, CLIENTDELIVERYNOTENUMBER, DELIVERYDATE, CODE, DESCRIPTION, PRICE, DISCOUNTPERCENTAGE, VATPERC, QTYSCANNEDOUT, QTYCOUNTEDOUT, BU_CODE, BU_DESC, BU_VATNUMBER, PLANT_NAME, PLANT_STREET, PLANT_ZIPCODE, PLANT_CITY, CURRENCY_CODE, INVOICEAMOUNTDECIMALS, DECIMALS, LANGUAGECODE)
as select  --part 1 client detail
       1 linetype, 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, 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, InvoiceLine IL2 Where ILV.InvoiceLine_ID = IL2.InvoiceLine_ID
             And IL2.InvoiceLineType_ID = 18 And IL2.InvoiceHeader_ID = IH.PARENTInvoiceHeader_ID And IL2.Code = IL.TaxGroupCode)
        else (Select ILV.Percentage From InvoiceLineVarious ILV, InvoiceLine IL2 Where ILV.InvoiceLine_ID = IL2.InvoiceLine_ID
             And 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
from InvoiceHeader IH, InvoiceLine IL, ClientDeliveryNote CDN, ClientDeliveryNoteLine CDL,
     Client CL, businessunit ibu, plant pl, address pla, currency curr, languages lan
where IL.InvoiceHeader_ID = IH.InvoiceHeader_ID and ih.currency_id = curr.currency_id and
      CDL.InvoiceLine_ID = IL.InvoiceLine_ID and
      CDN.ClientDeliveryNote_ID = CDL.Clientdeliverinote_Id and
      CL.Client_ID = CDN.Client_Link_ID and
      ih.invoicebusinessunit_id = ibu.businessunit_id and
      ibu.plant_id = pl.plant_id and Pl.Address_ID = pla.address_id
      and (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
      )
union all --part 2 summary
select 2 linetype, 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, 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, InvoiceLine IL2 Where ILV.InvoiceLine_ID = IL2.InvoiceLine_ID
             And IL2.InvoiceLineType_ID = 18 And IL2.InvoiceHeader_ID = IH.PARENTInvoiceHeader_ID And IL2.Code = IL.TaxGroupCode)
        else (Select ILV.Percentage From InvoiceLineVarious ILV, InvoiceLine IL2 Where ILV.InvoiceLine_ID = IL2.InvoiceLine_ID
             And 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
from InvoiceHeader IH, InvoiceLine IL, ClientDeliveryNote CDN, ClientDeliveryNoteLine CDL,
     Client CL, businessunit ibu, plant pl, address pla, currency curr, languages lan
where IL.InvoiceHeader_ID = IH.InvoiceHeader_ID and ih.currency_id = curr.currency_id and
      CDL.InvoiceLine_ID = IL.InvoiceLine_ID and
      CDN.ClientDeliveryNote_ID = CDL.Clientdeliverinote_Id and
      CL.Client_ID = CDN.Client_Link_ID and
      ih.invoicebusinessunit_id = ibu.businessunit_id and
      ibu.plant_id = pl.plant_id and Pl.Address_ID = pla.address_id
      and (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
      )
/
create or replace view V_APPENDIXCOSTSPERCLIENT_CBD
 (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_APPENDIX_ACCEPTGIRO_BDE
 (INVOICEHEADER_ID, INVOICEDATE, INVOICENUMBER, PAYTHISAMOUNT, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME2, INV_STREET, INV_ZIPCODE, INV_CITY, INV_BU_CODE, INV_BU_DESC, PLANT_ID, PLANT_CODE, PLANT_NAME, PLANT_STREET, PLANT_CITY, PLANT_ZIPCODE, ACCEPTGIROREFERENCE, ACCEPTGIROCODELINE, LNDRY_BNK_DESC, LNDRY_BNK_INTERNID, LNDRY_BNK_ZIPCODE, LNDRY_BNK_STREET, LNDRY_BNK_CITY, BNK_IDCODE, BNK_DESC, BNK_INTERNID, BNK_IBANNO, ACCEPTGIROFORMAT, CREDITSQUEEZEPERC, INVOICELAYOUTCODE
, PAYMENTDISCOUNT, PAYMENTDISCOUNT2, PAYMENTTERMSDESCRIPTION, DISCOUNTDAYS, DISCOUNTDAYS2, NETPAYMENTDAYS, CREDITSQUEEZEAMOUNT, PAYBY_NO, PAYBY_NAME, TOTALAMOUNTEXCLVAT, PREBILLAMOUNT, INVOICEAMOUNTDECIMALS, DECIMALS, BILLTOCOUNTRYCODE, BILLTOCOUNTRYDESCRIPTION, CONTACTPERSONNAME, NEXTPERIODSTARTDATE, INVOICEFREQUENCYNUMBER, PARENTINVOICEHEADER_ID, DUEDATE)
as select h.invoiceheader_id, h.invoicedate, h.invoicenumber, h.paythisamount,
       h.billtocustomernumber, h.billtocustomername, h.extraname2,
       h.street inv_street, h.zipcode inv_zipcode, h.city inv_city, bu.code Inv_bu_code, bu.description Inv_bu_desc,
       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, lbi.internalidcode lndry_bnk_internID, 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,
       ss.value ACCEPTGIROFORMAT
       , h.creditsqueezeperc
       , ihe.formlayoutcode INVOICELAYOUTCODE --todo 4799
       , ihe.paymentdiscount, ihe.paymentdiscount2, ihe.paymenttermsdescription
       , ihe.discountdays, ihe.discountdays2
       , h.netpaymentdays, h.creditsqueezeamount --end todo 4799
, PBCust.Customernumber PayBy_No , PBCust.Name PayBy_Name
, h.totalamountexclvat, h.prebillamount, b.invoiceamountdecimals, b.decimals
, (select co.code from customer bc, country co where h.billtocustomer_link_id = bc.customer_id and bc.country_id = co.country_id ) billtocountrycode
, ihe.billtocountrydescription, h.contactpersonname, h.nextperiodstartdate, h.invoicefrequency_id invoicefrequencynumber
, h.parentinvoiceheader_id, ihe.paymenttermsduedate DueDate
from invoiceheader h, businessunit bu, plant pl, address pa, systemsetting ss,currency b,
     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
         left outer join customer_link PBCust ON ihe.paybycustomer_link_id = PBCust.Customer_Link_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'
      and b.currency_id = h.currency_id

/
create or replace view V_APPENDIX_ACCEPTGIRO_DFD
 (INVOICEHEADER_ID, INVOICEDATE, INVOICENUMBER, PAYTHISAMOUNT, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME2, INV_STREET, INV_ZIPCODE, INV_CITY, INV_BU_CODE, INV_BU_DESC, PLANT_ID, PLANT_CODE, PLANT_NAME, PLANT_STREET, PLANT_CITY, PLANT_ZIPCODE, ACCEPTGIROREFERENCE, ACCEPTGIROCODELINE, LNDRY_BNK_DESC, LNDRY_BNK_INTERNID, LNDRY_BNK_ZIPCODE, LNDRY_BNK_STREET, LNDRY_BNK_CITY, BNK_IDCODE, BNK_DESC, BNK_INTERNID, BNK_IBANNO, ACCEPTGIROFORMAT, CREDITSQUEEZEPERC, INVOICELAYOUTCODE
, PAYMENTDISCOUNT, PAYMENTDISCOUNT2, PAYMENTTERMSDESCRIPTION, DISCOUNTDAYS, DISCOUNTDAYS2, NETPAYMENTDAYS, CREDITSQUEEZEAMOUNT, PAYBY_NO, PAYBY_NAME, TOTALAMOUNTEXCLVAT, PREBILLAMOUNT, INVOICEAMOUNTDECIMALS, DECIMALS, BILLTOCOUNTRYCODE, BILLTOCOUNTRYDESCRIPTION, CONTACTPERSONNAME, NEXTPERIODSTARTDATE, INVOICEFREQUENCYNUMBER, PARENTINVOICEHEADER_ID, DUEDATE)
as select h.invoiceheader_id, h.invoicedate, h.invoicenumber, h.paythisamount,
       h.billtocustomernumber, h.billtocustomername, h.extraname2,
       h.street inv_street, h.zipcode inv_zipcode, h.city inv_city, bu.code Inv_bu_code, bu.description Inv_bu_desc,
       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, lbi.internalidcode lndry_bnk_internID, 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,
       ss.value ACCEPTGIROFORMAT
       , h.creditsqueezeperc
       , ihe.formlayoutcode INVOICELAYOUTCODE --todo 4799
       , ihe.paymentdiscount, ihe.paymentdiscount2, ihe.paymenttermsdescription
       , ihe.discountdays, ihe.discountdays2
       , h.netpaymentdays, h.creditsqueezeamount --end todo 4799
, PBCust.Customernumber PayBy_No , PBCust.Name PayBy_Name
, h.totalamountexclvat, h.prebillamount, b.invoiceamountdecimals, b.decimals
, (select co.code from customer bc, country co where h.billtocustomer_link_id = bc.customer_id and bc.country_id = co.country_id ) billtocountrycode
, ihe.billtocountrydescription, h.contactpersonname, h.nextperiodstartdate, h.invoicefrequency_id invoicefrequencynumber
, h.parentinvoiceheader_id, ihe.paymenttermsduedate DueDate
from invoiceheader h, businessunit bu, plant pl, address pa, systemsetting ss,currency b,
     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
         left outer join customer_link PBCust ON ihe.paybycustomer_link_id = PBCust.Customer_Link_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'
      and b.currency_id = h.currency_id

/
create or replace view V_APPENDIX_ACCEPTGIRO_SMG
 (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, CUSTTYPE, PARENTINVOICEHEADER_ID, LEGALENTITY_LEGALNAME, LEGALENTITY_IBANNO, LEGALENTITY_INTERNID)
as select h.invoiceheader_id, h.invoicedate
, coalesce((select ihp.invoicenumber from invoiceheader ihp where ihp.invoiceheader_id = h.parentinvoiceheader_id), h.invoicenumber) 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, --cast(
        ihe.discountdays --as varchar2(63)) 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
       , cast(F_GetCustType_smg(h.invoiceheader_id) as varchar2(63)) custtype
       , h.parentinvoiceheader_id
, (select le.legalname from legalentity le where le.legalentity_id = bu.legalentity_id) LegalEntity_LegalName
, (select bi1.ibanno from legalentity le, bankinstitution bi1 where le.legalentity_id = bu.legalentity_id
          and bi1.bankinstitution_id = le.bankinstitution_id) LegalEntity_IbanNo
, (select bi1.internalidcode from legalentity le, bankinstitution bi1 where le.legalentity_id = bu.legalentity_id
          and bi1.bankinstitution_id = le.bankinstitution_id) LegalEntity_internID
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'
      and (h.parentinvoiceheader_id is null or h.invoiceheader_id=h.parentinvoiceheader_id)

/
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,
  (GETCURRENTDATE() - ar.artransactiondate) daysno,
  (select COUNT(*) from artransaction ar2 where ar2.billtocustomer_link_id = bcu.customer_id and ar2.closingtransaction_id is null
     and GETCURRENTDATE() - 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)
as select 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,
       billaddress.city billtocity, billchain.code billtochaincode, billchain.name billtochainname,
       coalesce(ih.deltocustomernumber, ih.billtocustomernumber) deltonumber,
       coalesce(ih.deltocustomername, ih.billtocustomername) deltoname,
       coalesce(ih.deltocity, ih.city) deltocity,
       (select turnovergroup_desc.description
         from   turnovergroup_desc
         where  turnovergroup_desc.turnovergroup_id = tgr.turnovergroup_id
         and    turnovergroup_desc.language_id = languages.language_id) turnoverdesc,
       tgr.code turnovercode, coalesce(lgr.accountnumber, -1) ledgeraccountsnumber,
       lgr.description ledgeraccountsdesc, ih.invoicenumber, ih.invoicedate invoicedate,
       pih.invoicedate parentinvoicedate,
       pih.invoicenumber parentinvoicenumber,
       (select sum(artransaction.amount)
                 from   artransaction
                 where  artransaction.invoiceheader_id = ih.parentinvoiceheader_id
                 group  by artransaction.invoiceheader_id) parenttotalamount,
       pih.totalamountexclvat parenttotalamountexclvat,
       ar.amount totalamount, ih.totalamountexclvat,
       (ar.amount - ih.totalamountexclvat) totaltaxamount, ard.amount turnoveramount,
       arl.amount ledgeraccountsamount, ar.exportstatus, currency.code currencycode,
       currency.invoiceamountdecimals, languages.code languagecode,
       tgr.turnovergroup_id turnovergroup_id, lgr.ledgeraccounts_id ledgeraccounts_id
, arl.artransaction_id, arl.businessunit_id
from   artransaction ar
left   outer join(artransledgeraccounts arl
join   ledgeraccounts lgr
on     lgr.ledgeraccounts_id = arl.ledgeraccounts_id) on arl.artransaction_id = ar.artransaction_id
join   invoiceheader ih
on     ih.invoiceheader_id = ar.invoiceheader_id
join invoiceheader pih
on     pih.invoiceheader_id = ih.parentinvoiceheader_id  ---ALWAYS PARENT
join   currency
on     currency.currency_id = ar.currency_id
left   outer join customercluster clu
on     ih.cluster_id = clu.cluster_id, businessunit bu, businessunit pbu, invoicefrequency infq,
 address billaddress, customer billto
left   outer join chain billchain
on     billto.chain_id = billchain.chain_id, artransactiondetail ard, artransactiontype,
 turnovergroup tgr, languages
where  ar.businessunit_id = bu.businessunit_id
and    ar.processbusinessunit_id = pbu.businessunit_id
and    ar.artransactiontype_id = artransactiontype.artransactiontype_id
and    artransactiontype.typenumber = 1
and    artransactiontype.debitcredit = 'D'
and    ih.invoicefrequency_id = infq.invoicefrequency_id
and    ar.billtocustomer_link_id = billto.customer_id
and    billto.visitaddress_id = billaddress.address_id
and    ar.artransaction_id = ard.artransaction_id
and    ard.turnovergroup_id = tgr.turnovergroup_id
union all
select bu.code businessunitcode, pbu.code prcbusinessunitcode, infq.invoicefrequencynumber,
       ih.invoiceheader_id, ih.parentinvoiceheader_id
        -- let parentinvoiceheader_id NULL ALLOWED !!!
      , ar.artransactiondate artransactiondate,
       (case ih.parentinvoiceheader_id
          when ih.invoiceheader_id then
           'Y'
          else
           'N'
        end) consolidatedyn, coalesce(clu.code, ' ') clustercode, billto.customernumber billtonumber,
       billaddress.city billtocity, billchain.code billtochaincode, billchain.name billtochainname,
       coalesce(ih.deltocustomernumber, ih.billtocustomernumber) deltonumber,
       coalesce(ih.deltocustomername, ih.billtocustomername) deltoname,
       coalesce(ih.deltocity, ih.city) deltocity,
       (select turnovergroup_desc.description
         from   turnovergroup_desc
         where  turnovergroup_desc.turnovergroup_id = tgr.turnovergroup_id
         and    turnovergroup_desc.language_id = languages.language_id) turnoverdesc,
       tgr.code turnovercode, coalesce(lgr.accountnumber, -1) ledgeraccountsnumber,
       lgr.description ledgeraccountsdesc, ih.invoicenumber, ih.invoicedate invoicedate,
       ih.invoicedate parentinvoicedate,
       ih.invoicenumber parentinvoicenumber,
       ar.amount parenttotalamount,
       ih.totalamountexclvat parenttotalamountexclvat,
       ar.amount totalamount, ih.totalamountexclvat,
       (ar.amount - ih.totalamountexclvat) totaltaxamount, ard.amount turnoveramount,
       arl.amount ledgeraccountsamount, ar.exportstatus, currency.code currencycode,
       currency.invoiceamountdecimals, languages.code languagecode,
       tgr.turnovergroup_id turnovergroup_id, lgr.ledgeraccounts_id ledgeraccounts_id
, arl.artransaction_id, arl.businessunit_id
from   artransaction ar
left   outer join(artransledgeraccounts arl
join   ledgeraccounts lgr
on     lgr.ledgeraccounts_id = arl.ledgeraccounts_id) on arl.artransaction_id = ar.artransaction_id
join   invoiceheader ih
on     ih.invoiceheader_id = ar.invoiceheader_id
left   outer join invoiceheader pih
on     pih.invoiceheader_id = ih.parentinvoiceheader_id
join   currency
on     currency.currency_id = ar.currency_id
left   outer join customercluster clu
on     ih.cluster_id = clu.cluster_id, businessunit bu, businessunit pbu, invoicefrequency infq,
 address billaddress, customer billto
left   outer join chain billchain
on     billto.chain_id = billchain.chain_id, artransactiondetail ard, artransactiontype,
 turnovergroup tgr, languages
where  ar.businessunit_id = bu.businessunit_id
and ih.parentinvoiceheader_id is null ----> NO PARENT
and    ar.processbusinessunit_id = pbu.businessunit_id
and    ar.artransactiontype_id = artransactiontype.artransactiontype_id
and    artransactiontype.typenumber = 1
and    artransactiontype.debitcredit = 'D'
and    ih.invoicefrequency_id = infq.invoicefrequency_id
and    ar.billtocustomer_link_id = billto.customer_id
and    billto.visitaddress_id = billaddress.address_id
and    ar.artransaction_id = ard.artransaction_id
and    ard.turnovergroup_id = tgr.turnovergroup_id

/
create or replace view V_ARINVOICEDETAILS_SGS
 (TYPE, TAXABLE, BUSINESSUNITCODE, PRCBUSINESSUNITCODE, INVOICEFREQUENCYNUMBER, INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, ARTRANSACTIONDATE, CONSOLIDATEDYN, CLUSTERCODE, BILLTONUMBER, BILLTOCUSTOMERNAME, BILLTOCITY, BILLTOCHAINCODE, BILLTOCHAINNAME, LEGACYCUSTOMERNUMBER, 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, TAXGROUP_ID, TAX23_DESC, TAX13_5_DESC, TAX13_5_ID, TAXB_DESC, TAXA_DESC, PARENTNET1, PARENTNET2, PARENTNET0, PARENTNETA, PARENTNETB)
as select  --Turnover Group Parent
        1 type, billto.taxable, 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, ih.billtocustomername,
       billaddress.city billtocity, billchain.code billtochaincode, billchain.name billtochainname, billto.legacycustomernumber,
       coalesce(ih.deltocustomernumber, ih.billtocustomernumber) deltonumber,
       coalesce(ih.deltocustomername, ih.billtocustomername) deltoname,
       coalesce(ih.deltocity, ih.city) deltocity,
       (select turnovergroup_desc.description
         from   turnovergroup_desc
         where  turnovergroup_desc.turnovergroup_id = tgr.turnovergroup_id
         and    turnovergroup_desc.language_id = languages.language_id) turnoverdesc,
       tgr.code turnovercode,  -1 ledgeraccountsnumber,
       null ledgeraccountsdesc, ih.invoicenumber, ih.invoicedate invoicedate,
       pih.invoicedate parentinvoicedate,
       pih.invoicenumber parentinvoicenumber,
       (select sum(artransaction.amount)
                 from   artransaction
                 where  artransaction.invoiceheader_id = ih.parentinvoiceheader_id
                 group  by artransaction.invoiceheader_id) parenttotalamount,
       pih.totalamountexclvat parenttotalamountexclvat,
       ar.amount totalamount, ih.totalamountexclvat,
       (ar.amount - ih.totalamountexclvat) totaltaxamount, ard.amount turnoveramount,
       0 ledgeraccountsamount, ar.exportstatus, currency.code currencycode,
       currency.invoiceamountdecimals, languages.code languagecode,
       tgr.turnovergroup_id turnovergroup_id, null ledgeraccounts_id
, ar.artransaction_id, ar.businessunit_id
, coalesce(tgr.taxgroup_id, 0) taxgroup_id
, (select max(tg1.description) from taxgroup tg1 where tg1.code = '2') Tax23_desc
, (select max(tg2.description) from taxgroup tg2 where tg2.code = '1') Tax13_5_desc
, (select max(tg2.taxgroup_id) from taxgroup tg2 where tg2.code = '1') Tax13_5_ID
, (select max(tgB.description) from taxgroup tgB where tgB.code = 'B') TaxB_desc
, (select max(tgA.description) from taxgroup tgA where tgA.code = 'A') TaxA_desc
, case when billto.taxable = 'Y'
  then (select sum(ad1.amount) from artransaction ar1, artransactiondetail ad1, turnovergroup to1, taxgroup tx1
   where  ar1.invoiceheader_id = ih.invoiceheader_id  and ar1.artransaction_id = ad1.artransaction_id
          and ad1.turnovergroup_id = to1.turnovergroup_id and to1.taxgroup_id = tx1.taxgroup_id
          and tx1.code = '1' and tx1.turnovergroup_id <> to1.turnovergroup_id)
   else 0 end parentNet1
, case when billto.taxable = 'Y'
  then (select sum(ad2.amount) from artransaction ar2, artransactiondetail ad2, turnovergroup to2, taxgroup tx2
   where  ar2.invoiceheader_id = ih.invoiceheader_id  and ar2.artransaction_id = ad2.artransaction_id
          and ad2.turnovergroup_id = to2.turnovergroup_id and to2.taxgroup_id = tx2.taxgroup_id
          and tx2.code = '2' and tx2.turnovergroup_id <> to2.turnovergroup_id)
   else 0 end parentNet2
, case when billto.taxable <> 'Y'
  then (select sum(ad0.amount) from artransaction ar0, artransactiondetail ad0
   where  ar0.invoiceheader_id = ih.invoiceheader_id  and ar0.artransaction_id = ad0.artransaction_id)
   else 0 end parentNet0
, case when billto.taxable = 'Y'
  then (select sum(adA.amount) from artransaction arA, artransactiondetail adA, turnovergroup toA, taxgroup txA
   where  arA.invoiceheader_id = ih.invoiceheader_id  and arA.artransaction_id = adA.artransaction_id
          and adA.turnovergroup_id = toA.turnovergroup_id and toA.taxgroup_id = txA.taxgroup_id
          and txA.code = 'A' and txA.turnovergroup_id <> toA.turnovergroup_id)
   else 0 end parentNetA
, case when billto.taxable = 'Y'
  then (select sum(adB.amount) from artransaction arB, artransactiondetail adB, turnovergroup toB, taxgroup txB
   where  arB.invoiceheader_id = ih.invoiceheader_id  and arB.artransaction_id = adB.artransaction_id
          and adB.turnovergroup_id = toB.turnovergroup_id and toB.taxgroup_id = txB.taxgroup_id
          and txB.code = 'B' and txB.turnovergroup_id <> toB.turnovergroup_id)
   else 0 end parentNetB
from   artransaction ar
join   invoiceheader ih
on     ih.invoiceheader_id = ar.invoiceheader_id
join   invoiceheader pih
on     pih.invoiceheader_id = ih.parentinvoiceheader_id  ---ALWAYS PARENT
join   currency
on     currency.currency_id = ar.currency_id
left outer join customercluster clu
on     ih.cluster_id = clu.cluster_id, businessunit bu, businessunit pbu, invoicefrequency infq,
 address billaddress, customer billto
left outer join chain billchain
on     billto.chain_id = billchain.chain_id, artransactiondetail ard, artransactiontype,
 turnovergroup tgr, languages
where  ar.businessunit_id = bu.businessunit_id
and    ar.processbusinessunit_id = pbu.businessunit_id
and    ar.artransactiontype_id = artransactiontype.artransactiontype_id
and    artransactiontype.typenumber = 1
and    artransactiontype.debitcredit = 'D'
and    ih.invoicefrequency_id = infq.invoicefrequency_id
and    ar.billtocustomer_link_id = billto.customer_id
and    billto.visitaddress_id = billaddress.address_id
and    ar.artransaction_id = ard.artransaction_id
and    ard.turnovergroup_id = tgr.turnovergroup_id
union all --Turnover Group Childs
select 2 type, billto.taxable, bu.code businessunitcode, pbu.code prcbusinessunitcode, infq.invoicefrequencynumber,
       ih.invoiceheader_id, ih.parentinvoiceheader_id-- let parentinvoiceheader_id NULL ALLOWED !!!
      , ar.artransactiondate artransactiondate,
       (case ih.parentinvoiceheader_id
          when ih.invoiceheader_id then
           'Y'
          else
           'N'
        end) consolidatedyn, coalesce(clu.code, ' ') clustercode, billto.customernumber billtonumber, ih.billtocustomername,
       billaddress.city billtocity, billchain.code billtochaincode, billchain.name billtochainname, billto.legacycustomernumber,
       coalesce(ih.deltocustomernumber, ih.billtocustomernumber) deltonumber,
       coalesce(ih.deltocustomername, ih.billtocustomername) deltoname,
       coalesce(ih.deltocity, ih.city) deltocity,
       (select turnovergroup_desc.description
         from   turnovergroup_desc
         where  turnovergroup_desc.turnovergroup_id = tgr.turnovergroup_id
         and    turnovergroup_desc.language_id = languages.language_id) turnoverdesc,
       tgr.code turnovercode, -1 ledgeraccountsnumber,
       null ledgeraccountsdesc, ih.invoicenumber, ih.invoicedate invoicedate,
       ih.invoicedate parentinvoicedate,
       ih.invoicenumber parentinvoicenumber,
       ar.amount parenttotalamount,
       ih.totalamountexclvat parenttotalamountexclvat,
       ar.amount totalamount, ih.totalamountexclvat,
       (ar.amount - ih.totalamountexclvat) totaltaxamount, ard.amount turnoveramount,
       0 ledgeraccountsamount, ar.exportstatus, currency.code currencycode,
       currency.invoiceamountdecimals, languages.code languagecode,
       tgr.turnovergroup_id turnovergroup_id, null ledgeraccounts_id
, ar.artransaction_id, ar.businessunit_id
, coalesce(tgr.taxgroup_id, 0) taxgroup_id
, (select max(tg1.description) from taxgroup tg1 where tg1.code = '2') Tax23_desc
, (select max(tg2.description) from taxgroup tg2 where tg2.code = '1') Tax13_5_desc
, (select max(tg2.taxgroup_id) from taxgroup tg2 where tg2.code = '1') Tax13_5_ID
, (select max(tgB.description) from taxgroup tgB where tgB.code = 'B') TaxB_desc
, (select max(tgA.description) from taxgroup tgA where tgA.code = 'A') TaxA_desc
, case when billto.taxable = 'Y'
  then (select ard.amount from taxgroup tx1 where tx1.taxgroup_id = tgr.taxgroup_id and tx1.code = '1' and tx1.turnovergroup_id <> tgr.turnovergroup_id)
  else 0 end parentNet1
, case when billto.taxable = 'Y'
  then (select ard.amount from taxgroup tx2 where tx2.taxgroup_id = tgr.taxgroup_id and tx2.code = '2' and tx2.turnovergroup_id <> tgr.turnovergroup_id)
  else 0 end parentNet2
, case when billto.taxable <> 'Y'
  then ard.amount else 0 end parentNet0
, case when billto.taxable = 'Y'
  then (select ard.amount from taxgroup tx1 where tx1.taxgroup_id = tgr.taxgroup_id and tx1.code in ('1','2') and tx1.turnovergroup_id <> tgr.turnovergroup_id)
  else 0 end parentNetA
, case when billto.taxable = 'Y'
  then 0
  else 0 end parentNetB
from   artransaction ar
join   invoiceheader ih
on     ih.invoiceheader_id = ar.invoiceheader_id
join   currency
on     currency.currency_id = ar.currency_id
left   outer join customercluster clu
on     ih.cluster_id = clu.cluster_id, businessunit bu, businessunit pbu, invoicefrequency infq,
 address billaddress, customer billto
left   outer join chain billchain
on     billto.chain_id = billchain.chain_id, artransactiondetail ard, artransactiontype,
 turnovergroup tgr, languages
where  ar.businessunit_id = bu.businessunit_id
and ih.parentinvoiceheader_id is null ----> NO PARENT
and    ar.processbusinessunit_id = pbu.businessunit_id
and    ar.artransactiontype_id = artransactiontype.artransactiontype_id
and    artransactiontype.typenumber = 1
and    artransactiontype.debitcredit = 'D'
and    ih.invoicefrequency_id = infq.invoicefrequency_id
and    ar.billtocustomer_link_id = billto.customer_id
and    billto.visitaddress_id = billaddress.address_id
and    ar.artransaction_id = ard.artransaction_id
and    ard.turnovergroup_id = tgr.turnovergroup_id
union all --Ledger Account Parents
select 3 type, billto.taxable, 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, ih.billtocustomername,
       billaddress.city billtocity, billchain.code billtochaincode, billchain.name billtochainname, billto.legacycustomernumber,
       coalesce(ih.deltocustomernumber, ih.billtocustomernumber) deltonumber,
       coalesce(ih.deltocustomername, ih.billtocustomername) deltoname,
       coalesce(ih.deltocity, ih.city) deltocity,
       null turnoverdesc,
       null turnovercode, coalesce(lgr.accountnumber, -1) ledgeraccountsnumber,
       lgr.description ledgeraccountsdesc, ih.invoicenumber, ih.invoicedate invoicedate,
       pih.invoicedate parentinvoicedate,
       pih.invoicenumber parentinvoicenumber,
       (select sum(artransaction.amount)
                 from   artransaction
                 where  artransaction.invoiceheader_id = ih.parentinvoiceheader_id
                 group  by artransaction.invoiceheader_id) parenttotalamount,
       pih.totalamountexclvat parenttotalamountexclvat,
       ar.amount totalamount, ih.totalamountexclvat,
       (ar.amount - ih.totalamountexclvat) totaltaxamount, 0 turnoveramount,
       arl.amount ledgeraccountsamount, ar.exportstatus, currency.code currencycode,
       currency.invoiceamountdecimals, languages.code languagecode,
       null turnovergroup_id, lgr.ledgeraccounts_id ledgeraccounts_id
, arl.artransaction_id, arl.businessunit_id
, coalesce(lgr.taxgroup_id, 0) taxgroup_id
, (select max(tg1.description) from taxgroup tg1 where tg1.code = '2') Tax23_desc
, (select max(tg2.description) from taxgroup tg2 where tg2.code = '1') Tax13_5_desc
, (select max(tg2.taxgroup_id) from taxgroup tg2 where tg2.code = '1') Tax13_5_ID
, (select max(tgB.description) from taxgroup tgB where tgB.code = 'B') TaxB_desc
, (select max(tgA.description) from taxgroup tgA where tgA.code = 'A') TaxA_desc
, case when billto.taxable = 'Y'
  then (select sum(ad1.amount) from artransaction ar1, artransactiondetail ad1, turnovergroup to1, taxgroup tx1
   where  ar1.invoiceheader_id = ih.invoiceheader_id  and ar1.artransaction_id = ad1.artransaction_id
          and ad1.turnovergroup_id = to1.turnovergroup_id and to1.taxgroup_id = tx1.taxgroup_id
          and tx1.code = '1' and tx1.turnovergroup_id <> to1.turnovergroup_id)
   else 0 end parentNet1
, case when billto.taxable = 'Y'
  then (select sum(ad2.amount) from artransaction ar2, artransactiondetail ad2, turnovergroup to2, taxgroup tx2
   where  ar2.invoiceheader_id = ih.invoiceheader_id  and ar2.artransaction_id = ad2.artransaction_id
          and ad2.turnovergroup_id = to2.turnovergroup_id and to2.taxgroup_id = tx2.taxgroup_id
          and tx2.code = '2' and tx2.turnovergroup_id <> to2.turnovergroup_id)
   else 0 end parentNet2
, case when billto.taxable <> 'Y'
  then (select sum(ad0.amount) from artransaction ar0, artransactiondetail ad0
   where  ar0.invoiceheader_id = ih.invoiceheader_id  and ar0.artransaction_id = ad0.artransaction_id)
   else 0 end parentNet0
, case when billto.taxable = 'Y'
  then (select sum(adA.amount) from artransaction arA, artransactiondetail adA, turnovergroup toA, taxgroup txA
   where  arA.invoiceheader_id = ih.invoiceheader_id  and arA.artransaction_id = adA.artransaction_id
          and adA.turnovergroup_id = toA.turnovergroup_id and toA.taxgroup_id = txA.taxgroup_id
          and txA.code = 'A' and txA.turnovergroup_id <> toA.turnovergroup_id)
   else 0 end parentNetA
, case when billto.taxable = 'Y'
  then (select sum(adB.amount) from artransaction arB, artransactiondetail adB, turnovergroup toB, taxgroup txB
   where  arB.invoiceheader_id = ih.invoiceheader_id  and arB.artransaction_id = adB.artransaction_id
          and adB.turnovergroup_id = toB.turnovergroup_id and toB.taxgroup_id = txB.taxgroup_id
          and txB.code = 'B' and txB.turnovergroup_id <> toB.turnovergroup_id)
   else 0 end parentNetB
from   artransaction ar
inner join (artransledgeraccounts arl
join   ledgeraccounts lgr
on     lgr.ledgeraccounts_id = arl.ledgeraccounts_id) on arl.artransaction_id = ar.artransaction_id and arl.businessunit_id = ar.businessunit_id
join   invoiceheader ih
on     ih.invoiceheader_id = ar.invoiceheader_id
join   invoiceheader pih
on     pih.invoiceheader_id = ih.parentinvoiceheader_id  ---ALWAYS PARENT
join   currency
on     currency.currency_id = ar.currency_id
left outer join customercluster clu
on     ih.cluster_id = clu.cluster_id, businessunit bu, businessunit pbu, invoicefrequency infq,
 address billaddress, customer billto
left outer join chain billchain
on     billto.chain_id = billchain.chain_id, artransactiontype, languages
where  ar.businessunit_id = bu.businessunit_id
and    ar.processbusinessunit_id = pbu.businessunit_id
and    ar.artransactiontype_id = artransactiontype.artransactiontype_id
and    artransactiontype.typenumber = 1
and    artransactiontype.debitcredit = 'D'
and    ih.invoicefrequency_id = infq.invoicefrequency_id
and    ar.billtocustomer_link_id = billto.customer_id
and    billto.visitaddress_id = billaddress.address_id
union all --Ledger Account Childs
select 4 type, billto.taxable, bu.code businessunitcode, pbu.code prcbusinessunitcode, infq.invoicefrequencynumber,
       ih.invoiceheader_id, ih.parentinvoiceheader_id-- let parentinvoiceheader_id NULL ALLOWED !!!
      , ar.artransactiondate artransactiondate,
       (case ih.parentinvoiceheader_id
          when ih.invoiceheader_id then
           'Y'
          else
           'N'
        end) consolidatedyn, coalesce(clu.code, ' ') clustercode, billto.customernumber billtonumber, ih.billtocustomername,
       billaddress.city billtocity, billchain.code billtochaincode, billchain.name billtochainname, billto.legacycustomernumber,
       coalesce(ih.deltocustomernumber, ih.billtocustomernumber) deltonumber,
       coalesce(ih.deltocustomername, ih.billtocustomername) deltoname,
       coalesce(ih.deltocity, ih.city) deltocity,
       null turnoverdesc,
       null turnovercode, coalesce(lgr.accountnumber, -1) ledgeraccountsnumber,
       lgr.description ledgeraccountsdesc, ih.invoicenumber, ih.invoicedate invoicedate,
       ih.invoicedate parentinvoicedate,
       ih.invoicenumber parentinvoicenumber,
       ar.amount parenttotalamount,
       ih.totalamountexclvat parenttotalamountexclvat,
       ar.amount totalamount, ih.totalamountexclvat,
       (ar.amount - ih.totalamountexclvat) totaltaxamount, 0 turnoveramount,
       arl.amount ledgeraccountsamount, ar.exportstatus, currency.code currencycode,
       currency.invoiceamountdecimals, languages.code languagecode,
       null turnovergroup_id, lgr.ledgeraccounts_id ledgeraccounts_id
, arl.artransaction_id, arl.businessunit_id
, coalesce(lgr.taxgroup_id, 0) taxgroup_id
, (select max(tg1.description) from taxgroup tg1 where tg1.code = '2') Tax23_desc
, (select max(tg2.description) from taxgroup tg2 where tg2.code = '1') Tax13_5_desc
, (select max(tg2.taxgroup_id) from taxgroup tg2 where tg2.code = '1') Tax13_5_ID
, (select max(tgB.description) from taxgroup tgB where tgB.code = 'B') TaxB_desc
, (select max(tgA.description) from taxgroup tgA where tgA.code = 'A') TaxA_desc
, case when billto.taxable = 'Y' and tx.code = '1'
  then arl.amount--and tx1.turnovergroup_id <> lgr.turnovergroup_id)
  else 0 end parentNet1
, case when billto.taxable = 'Y' and tx.code = '2'
  then arl.amount--and tx2.turnovergroup_id <> lgr.turnovergroup_id)
  else 0 end parentNet2
, case when billto.taxable <> 'Y'
  then arl.amount else 0 end parentNet0
, case when billto.taxable = 'Y' and tx.code in ('1','2')
  then arl.amount--and tx1.turnovergroup_id <> lgr.turnovergroup_id)
  else 0 end parentNetA
, case when billto.taxable = 'Y'
  then 0
  else 0 end parentNetB
from   artransaction ar
inner join(artransledgeraccounts arl
join   ledgeraccounts lgr
       left outer join taxgroup tx on tx.taxgroup_id = lgr.taxgroup_id
on     lgr.ledgeraccounts_id = arl.ledgeraccounts_id) on arl.artransaction_id = ar.artransaction_id
join   invoiceheader ih
on     ih.invoiceheader_id = ar.invoiceheader_id
join   currency
on     currency.currency_id = ar.currency_id
left   outer join customercluster clu
on     ih.cluster_id = clu.cluster_id, businessunit bu, businessunit pbu, invoicefrequency infq,
 address billaddress, customer billto
left   outer join chain billchain
on     billto.chain_id = billchain.chain_id, artransactiontype, languages
where  ar.businessunit_id = bu.businessunit_id
and ih.parentinvoiceheader_id is null ----> NO PARENT
and    ar.processbusinessunit_id = pbu.businessunit_id
and    ar.artransactiontype_id = artransactiontype.artransactiontype_id
and    artransactiontype.typenumber = 1
and    artransactiontype.debitcredit = 'D'
and    ih.invoicefrequency_id = infq.invoicefrequency_id
and    ar.billtocustomer_link_id = billto.customer_id
and    billto.visitaddress_id = billaddress.address_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_ARTRIALBALANCEINVOICEDETAILS
 (BUSINESSUNIT_ID, BILLTOCUSTOMER_LINK_ID, INVOICENUMBER, ARTRANSACTIONDATE, REPORTPARAM_ID, AMOUNT_CURR, AMOUNT_30, AMOUNT_60, AMOUNT_90, AMOUNT_120, DUEDATE, CURRENTDATE)
as select  ar.businessunit_id, ar.billtocustomer_link_id,
       ar.invoicenumber, ar.artransactiondate, --ar.amount,
       rp.reportparam_id, --rp.date_value1, rp.date_value2, rp.date_value3, rp.date_value4,
F_GETARAGINGAMOUNT(ar.billtocustomer_link_id, rp.NUMBER_VALUE, 0, GETDATEASVARCHARFIXEDFORMAT(rp.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(rp.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(rp.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(rp.DATE_VALUE4), -1, -1, ar.invoiceheader_id, ar.artransaction_id) Amount_curr,
F_GETARAGINGAMOUNT(ar.billtocustomer_link_id, rp.NUMBER_VALUE, 1, GETDATEASVARCHARFIXEDFORMAT(rp.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(rp.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(rp.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(rp.DATE_VALUE4), -1, -1, ar.invoiceheader_id, ar.artransaction_id) Amount_30,
F_GETARAGINGAMOUNT(ar.billtocustomer_link_id, rp.NUMBER_VALUE, 2, GETDATEASVARCHARFIXEDFORMAT(rp.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(rp.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(rp.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(rp.DATE_VALUE4), -1, -1, ar.invoiceheader_id, ar.artransaction_id) Amount_60,
F_GETARAGINGAMOUNT(ar.billtocustomer_link_id, rp.NUMBER_VALUE, 3, GETDATEASVARCHARFIXEDFORMAT(rp.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(rp.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(rp.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(rp.DATE_VALUE4), -1, -1, ar.invoiceheader_id, ar.artransaction_id) Amount_90,
F_GETARAGINGAMOUNT(ar.billtocustomer_link_id, rp.NUMBER_VALUE, 4, GETDATEASVARCHARFIXEDFORMAT(rp.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(rp.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(rp.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(rp.DATE_VALUE4), -1, -1, ar.invoiceheader_id, ar.artransaction_id) Amount_120,
(select ihe.paymenttermsduedate from invoiceheaderextrainfo ihe where ar.invoiceheader_id = ihe.invoiceheader_id) duedate,
sysdate currentdate
from artransaction ar, reportparam rp, artransactiontype art
where ar.debitcredit = 'D' and ar.isopen_yn = 'Y' --and ar.closingtransaction_id is null
          and ar.artransactiontype_id = art.artransactiontype_id and art.typenumber <> 2
      and (ar.parentartransaction_id is null or ar.parentartransaction_id = ar.artransaction_id)

/
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((GETCURRENTDATE()-GETDATEONLY(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_BAGTAG_LLG
 (CORRECTEDNOTENUMBER, NOTENUMBER, SEQUENCENUMBER, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, STOPNUMBER, PACKINGNOTE_ID, ENDDATEFORUSE, ORIGIN, PRODUCTIONDATE, NUMBEROFGARMENTSINLOCKER, NUMBEROFLOCKERS, CUSTOMERNUMBER, SEARCHNAME, 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, DRIVINGDAY_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, DAYNUMBER, NOOFDELIVERYDAYS, TRANSPORTARTICLEDESCRIPTION)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER, PACKINGNOTE.NOTENUMBER,
PACKINGNOTE.SEQUENCENUMBER,
PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK,
PACKINGNOTE.STOPNUMBER,
PACKINGNOTE.PACKINGNOTE_ID,
PACKINGNOTE.ENDDATEFORUSE, PACKINGNOTE.ORIGIN,
PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
CUSTOMER.CUSTOMERNUMBER, CUSTOMER.SEARCHNAME,CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME, CUSTOMER.PHONENO,
ADDRESS.STREET CUSTOMERSTREET, ADDRESS.ZIPCODE CUSTOMERZIP, ADDRESS.CITY CUSTOMERCITY,
ADDRESS.STREET2 CUSTOMERSTREET2, ADDRESS.STATE CUSTOMERSTATE, ADDRESS.COUNTY CUSTOMERCOUNTY,
MAILADRESS.STREET MAIL_STREET, MAILADRESS.ZIPCODE MAIL_ZIPCODE, MAILADRESS.CITY MAIL_CITY,
MAILADRESS.STATE MAIL_STATE, MAILADRESS.COUNTY MAIL_COUNTY, MAILADRESS.STREET2 MAIL_STREET2,
DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
PROCESSBU.DESCRIPTION BUDESCRIPTION,
PLANT.NAME PLANTNAME,
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
(SELECT DD.DESCRIPTION FROM DAY_DESC DD WHERE DD.DAY_ID = ROUTE.DRIVINGDAY_ID AND DD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) DRIVINGDAY_DESC,
ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION ROUTEDESCRIPTION, ROUTE.LOADINGDOCK,
LANGUAGES.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,
DEPOT.DESCRIPTION DEPOTDESCRIPTION
, DISTRIBUTIONPOINT.Remarkonpackingnote, DISTRIBUTIONPOINT.Remarkondeliverynote
, (select lan.code from languages lan where CUSTOMER.language_id = lan.language_id) LanguageCodeCustomer
--,  CAST(PACKINGNOTE.WEEK AS VARCHAR2(2)) DeliveryWeek
, DISTRIBUTIONPOINT.Labelcolor cp_labelcolor, DISTRIBUTIONPOINT.Internalremarkfortransplabel
, DISTRIBUTIONPOINT.Transplabinternalremarkenddate, DISTRIBUTIONPOINT.Externalremarkfortransplabel
, DISTRIBUTIONPOINT.Transplabexternalremarkenddate, DISTRIBUTIONPOINT.Nooftransportlabels
, (select dud.usageday_id from departmentusageday dud where dud.department_id = department.department_id and dud.day_id = route.drivingday_id) usagedaynumber
, (select dd.description from departmentusageday dud, day_desc dd where dud.department_id = department.department_id and dud.usageday_id = dd.day_id and dud.day_id = route.drivingday_id and dd.language_id = languages.language_id) usagedaydesc
, CUSTOMER.labelcolor cu_labelcolor
, packingnote.daynumber
, (select count(1) from customerdeliveryday cdd where cdd.customer_id = customer.customer_id) NOOFDELIVERYDAYS
,(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION
FROM  CUSTOMER,
        ADDRESS, DEPARTMENT, DISTRIBUTIONPOINT, ADDRESS MAILADRESS,
        PLANT, ADDRESS PLANTADDRESS,
        BUSINESSUNIT PROCESSBU, DELIVERYPOINT,
        PACKINGNOTE
        LEFT OUTER JOIN ROUTE
        LEFT OUTER JOIN DEPOT ON ROUTE.DEPOT_ID=DEPOT.DEPOT_ID    --TODO7736
        ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID,
        LANGUAGES,
        ADDRESS DELPOINT_ADDRESS
  WHERE PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
  AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
  AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND CUSTOMER.VISITADDRESS_ID = ADDRESS.ADDRESS_ID
  AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND CUSTOMER.MAILADDRESS_ID = MAILADRESS.ADDRESS_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = DELPOINT_ADDRESS.ADDRESS_ID
/
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_BATCHPERIOD_STX
 (GARMENTBATCHNUMBER, LANGUAGECODE, DELIVERYDATE, INSCANDATE, OUTSCANDATE, PRIMARYID, PRODUCTCODE, PRODUCT_DESC, SIZECODE, WEARERNAME, CUSTOMERNUMBER, CUSTOMERNAME, INSCAN, OUTSCAN, REPAIRS, REWASH)
as select distinct gb.garmentbatchnumber,languages.Code languagecode, gb.deliverydate, (select trunc(max(scan.scantimestamp)) from scan where scan.uniqueitem_link_id=ui.uniqueitem_id and scan.customer_link_id=c.customer_id and  scan.transactiontype_id=1 and scan.scantimestamp<=gb.deliverydate ) inscandate,
(select trunc(max(scan.scantimestamp)) from scan where scan.uniqueitem_link_id=ui.uniqueitem_id and scan.customer_link_id=c.customer_id and  scan.transactiontype_id=2 and scan.scantimestamp<=gb.deliverydate) outscandate, ui.primaryid,
p.code productcode,(select pd.description from product_desc pd where p.product_id=pd.product_id and pd.language_id=languages.language_id) product_desc,
s.code sizecode, w.fullname wearername, c.customernumber, c.name customername,
(select count(scan.scan_id) from scan where scan.uniqueitem_link_id=ui.uniqueitem_id and  scan.transactiontype_id=1) inscan,
(select count(scan.scan_id) from scan where scan.uniqueitem_link_id=ui.uniqueitem_id and  scan.transactiontype_id=2) outscan,
(select count(scan.scan_id) from scan where scan.uniqueitem_link_id=ui.uniqueitem_id and  scan.transactiontype_id=3) repairs,
(select count(scan.scan_id) from scan where scan.uniqueitem_link_id=ui.uniqueitem_id and  scan.transactiontype_id=4) rewash
from garmentbatch gb join garmentbatchscan gbs on gb.garmentbatch_id=gbs.garmentbatch_id
join uniqueitem ui on ui.uniqueitem_id=gbs.uniqueitem_id
join product p on ui.product_id=p.product_id
join sizedefinition s on ui.sizedefinition_id=s.sizedefinition_id
join uniqueitemnonpool uinp on ui.uniqueitem_id=uinp.uniqueitem_id
join weareremployment we on uinp.weareremployment_id=we.weareremployment_id
join wearer w on we.wearer_id=w.wearer_id
join customer c on w.customer_id=c.customer_id
cross join languages

/
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,
       p.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 = p.address_id) plantstreet,
       (select a.zipcode from address a where a.address_id = p.address_id) plantzipcode,
       (select a.city from address a where a.address_id = p.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 p
    on p.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,
       p.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 = p.address_id) plantstreet,
       (select a.zipcode from address a where a.address_id = p.address_id) plantzipcode,
       (select a.city from address a where a.address_id = p.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 p
    on p.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,
       p.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 = p.address_id) plantstreet,
       (select a.zipcode from address a where a.address_id = p.address_id) plantzipcode,
       (select a.city from address a where a.address_id = p.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 p
    on p.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,
        p.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 = p.address_id) plantstreet,
        (select a.zipcode from address a where a.address_id = p.address_id) plantzipcode,
        (select a.city from address a where a.address_id = p.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 p
     on p.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_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
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 pnb.packingnote_id=pn.packingnote_id
join packingnoteboxquantity pnbq on pnbq.packingnotebox_id=pnb.packingnotebox_id
join packingnoteline pnl on pnl.packingnoteline_id=pnbq.packingnoteline_id
join deliverypoint del on del.deliverypoint_id=pn.deliverypoint_id
join address ad on ad.address_id=del.deliveryaddress_id
join plantdepartment pld on pld.plantdepartment_id=pn.plantdepartment_id
join distributionpoint db on db.distributionpoint_id=pn.distributionpoint_id
join department d on d.department_id=db.department_id
join customer c on c.customer_id=d.customer_id
join product p on p.product_id=pnl.product_id
join sizedefinition sz on sz.sizedefinition_id=pnl.sizedefinition_id
join finishingmethod fm on fm.finishingmethod_id=pnl.finishingmethod_id
join languages l on l.language_id=c.language_id

/
create or replace view V_BOXLABEL_ELJ
 (CUSTOMERNUMBER, NAME, STREET, STREET2, CITY, ZIPCODE, COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCR, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESC, PACKINGNOTE_ID, DELIVERYDATE, NOTENUMBER, BOXNUMBER, DELIVEREDQTY, CODE, PRODUCTDESC, SIZECODE, FMCODE, SORTADDRESS, PLANTCODE, LANGCODE)
as SELECT
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.parentproduct_id and psc.language_id = l.language_id) productDesc
,sz.code sizecode
,fm.code fmcode
, (select dp.sortaddress from deliverypoint dp where dp.deliverypoint_id=db.deliverypoint_id) sortaddress,
(select p.code from plant p join businessunit bu on p.plant_id=bu.plant_id where pn.processbusinessunit_id=bu.businessunit_id) plantcode
,l.code langcode
from packingnote pn
join packingnotebox pnb on pnb.packingnote_id=pn.packingnote_id
join packingnoteboxquantity pnbq on pnbq.packingnotebox_id=pnb.packingnotebox_id
join packingnoteline pnl on pnl.packingnoteline_id=pnbq.packingnoteline_id
join deliverypoint del on del.deliverypoint_id=pn.deliverypoint_id
join address ad on ad.address_id=del.deliveryaddress_id
join plantdepartment pld on pld.plantdepartment_id=pn.plantdepartment_id
join distributionpoint db on db.distributionpoint_id=pn.distributionpoint_id
join department d on d.department_id=db.department_id
join customer c on c.customer_id=d.customer_id
join product p on p.product_id=pnl.product_id
join sizedefinition sz on sz.sizedefinition_id=pnl.sizedefinition_id
join finishingmethod fm on fm.finishingmethod_id=pnl.finishingmethod_id
join languages l on l.language_id=c.language_id

/
create or replace view V_BOXLABEL_SNG
 (CUSTOMERNUMBER, NAME, STREET, STREET2, CITY, ZIPCODE, COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCR, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESC, PACKINGNOTE_ID, DELIVERYDATE, NOTENUMBER, BOXNUMBER, DELIVEREDQTY, CODE, PRODUCTDESC, SIZECODE, FMCODE, LANGCODE, PLANTLOGO, PLANTPHONE, PLANTCITY, PLANTZIP)
as SELECT 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
, pl.logo PlantLogo, pl.phoneno PlantPhone, plad.city Plantcity, plad.zipcode PlantZip
from packingnote pn
join packingnotebox pnb on pnb.packingnote_id=pn.packingnote_id
join packingnoteboxquantity pnbq on pnbq.packingnotebox_id=pnb.packingnotebox_id
join packingnoteline pnl on pnl.packingnoteline_id=pnbq.packingnoteline_id
join deliverypoint del on del.deliverypoint_id=pn.deliverypoint_id
join address ad on ad.address_id=del.deliveryaddress_id
join plantdepartment pld on pld.plantdepartment_id=pn.plantdepartment_id
join plant pl on pld.plant_id = pl.plant_id
join address plad on pl.address_id = plad.address_id
join distributionpoint db on db.distributionpoint_id=pn.distributionpoint_id
join department d on d.department_id=db.department_id
join customer c on c.customer_id=d.customer_id
join product p on p.product_id=pnl.product_id
join sizedefinition sz on sz.sizedefinition_id=pnl.sizedefinition_id
join finishingmethod fm on fm.finishingmethod_id=pnl.finishingmethod_id
join languages l on l.language_id=c.language_id

/
create or replace view V_BOXLABEL_STX
 (CUSTOMERNUMBER, NAME, STREET, STREET2, CITY, ZIPCODE, COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCR, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESC, PACKINGNOTE_ID, DELIVERYDATE, NOTENUMBER, BOXNUMBER, DELIVEREDQTY, CODE, PRODUCTDESC, SIZECODE, FMCODE, LANGCODE, BATCHNUMBER)
as SELECT
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
, (select max(ds.batchnumber) from deliveryscan ds where ds.packingnote_id = pn.Packingnote_Id) BatchNumber
from packingnote pn
join packingnotebox pnb on pnb.packingnote_id=pn.packingnote_id
join packingnoteboxquantity pnbq on pnbq.packingnotebox_id=pnb.packingnotebox_id
join packingnoteline pnl on pnl.packingnoteline_id=pnbq.packingnoteline_id
join deliverypoint del on del.deliverypoint_id=pn.deliverypoint_id
join address ad on ad.address_id=del.deliveryaddress_id
join plantdepartment pld on pld.plantdepartment_id=pn.plantdepartment_id
join distributionpoint db on db.distributionpoint_id=pn.distributionpoint_id
join department d on d.department_id=db.department_id
join customer c on c.customer_id=d.customer_id
join product p on p.product_id=pnl.product_id
join sizedefinition sz on sz.sizedefinition_id=pnl.sizedefinition_id
join finishingmethod fm on fm.finishingmethod_id=pnl.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
   and exists ( select 1
                from residentialitemscan rsi join workstation ws on ws.code = rsi.scanstation
                     join comportconfiguration ccf on ccf.workstation_id = ws.workstation_id
                where rsi.clientdeliverynoteline_id = cdl.clientdeliverynoteline_id
                and   ccf.sortdevicenumber <> 0 )
 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_BOXLOAD_CBD
 (CLIENTDELIVERYNOTEID, CLIENTDELIVERYNOTENUMBER, EMPTIED, CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESC, STREET, ZIPCODE, CITY, CLIENTNUMBER, CLIENTNAME, LEGACYCODE, 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,
       client.legacycode,
       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,
       client                   client,
       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 clientlink.client_id = client.client_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
   and exists ( select 1
                from residentialitemscan rsi join workstation ws on ws.code = rsi.scanstation
                     join comportconfiguration ccf on ccf.workstation_id = ws.workstation_id
                where rsi.clientdeliverynoteline_id = cdl.clientdeliverynoteline_id
                and   ccf.sortdevicenumber <> 0 )
 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,
          client.legacycode,
          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_BULKPUTUP
 (PACKINGNOTEID, STATUSTYPE, DRIVINGDATE, DEPOTCODE, DEPOTDESCRIPTION, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERLEGALNAME, STREET, STREET2, CITY, STATE, ZIPCODE, COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, PACKINGDEPARTMENTCODE, PACKINGDEPARTMENTDESCRIPTION, TRANSPORTARTICLECODE, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENUMBER, EMPLOYEENAME
, PRODUCTIONDATE, DELIVERYDATE, STATUSCODE, STATUSDESCRIPTION, REMARK, PROCESSBUCODE, PROCESSBUDESCRIPTION, INVOICEBUCODE, INVOICEBUDESCRIPTION, ROUTENUMBER, ROUTEDESCRIPTION, LOADINGDOCK, CLEANRETURN, DEADLINE, DEADLINEASNUMERIC, CONSIGNMENTNOTENUMBER, SYSTEMUSER_ID, TIMESTAMP, CREATIONTIMESTAMP, ENDDATEFORUSE, DAYDESCRIPTION, WEEK, LANGUAGECODE, DRIVERNAME, DRIVERNUMBER, BULKPUTUPONPACKINGNOTE, YEAR, PACKINGNOTECOLUMNS, DELIVERGARMENTS, STOPNUMBER, PUTUPREPORTPERCUSTOMER
, EXTRANAME1, LEGACYCUSTOMERNUMBER, DISTRICTDESC, DISTRICTCODE, ROUTECONTROL_ID)
as SELECT PACKINGNOTE.PACKINGNOTE_ID PACKINGNOTEID,STATUS.STATUSTYPE,  ROUTECONTROL.DRIVINGDATE, DEPOT.CODE DEPOTCODE, DEPOT.DESCRIPTION DEPOTDESCRIPTION,
 PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME CUSTOMERLEGALNAME,
 ADDRESS.STREET, ADDRESS.STREET2, ADDRESS.CITY, ADDRESS.STATE, ADDRESS.ZIPCODE, ADDRESS.COUNTY,
 DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
 DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
  DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
 PACKINGNOTE.SEQUENCENUMBER, PLANTDEPARTMENT.CODE PACKINGDEPARTMENTCODE, PLANTDEPARTMENT.DESCRIPTION PACKINGDEPARTMENTDESCRIPTION,
 TRANSPORTARTICLE.CODE TRANSPORTARTICLECODE,
 (SELECT A.DESCRIPTION FROM TRANSPORTARTICLE_DESC A WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
 PACKINGNOTE.OCCUPANCY, EMPLOYEE.EMPLOYEENUMBER, EMPLOYEE.NAME EMPLOYEENAME,
 PACKINGNOTE.PRODUCTIONDATE,
 PACKINGNOTE.DELIVERYDATE,
 STATUS.CODE STATUSCODE,
 (SELECT S.DESCRIPTION FROM STATUS_DESC S WHERE S.STATUS_ID = PACKINGNOTE.STATUS_ID AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) STATUSDESCRIPTION,
 PACKINGNOTE.PNREMARK REMARK, PROCESSBU.CODE PROCESSBUCODE, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
 INVOICEBU.CODE INVOICEBUCODE, INVOICEBU.DESCRIPTION INVOICEBUDESCRIPTION,
 ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION ROUTEDESCRIPTION, ROUTE.LOADINGDOCK,
 PACKINGNOTE.CLEANRETURN,
 PACKINGNOTE.DEADLINE,
 GETTIMEASNUMERIC(PACKINGNOTE.DEADLINE) DEADLINEASNUMERIC,
 CONSIGNMENTNOTE.CONSIGNMENTNOTENUMBER,
 PACKINGNOTE.SYSTEMUSER_ID, PACKINGNOTE.TIMESTAMP,PACKINGNOTE.CREATIONTIMESTAMP,
 PACKINGNOTE.ENDDATEFORUSE,
 (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,
  DRIVER.NAME DRIVERNAME,
  DRIVER.EMPLOYEENUMBER DRIVERNUMBER
  , CASE WHEN CUSTOMER.DELNOTEFORBULKPUTUPITEMS = 0 THEN  'N' ELSE 'Y' END BULKPUTUPONPACKINGNOTE,
  PACKINGNOTE.YEAR YEAR
  , (SELECT SS.VALUE FROM SYSTEMSETTING SS WHERE SS.PLANT_ID = PROCESSBU.PLANT_ID
            AND SS.NAME = 'PACKINGNOTECOLUMNS') PACKINGNOTECOLUMNS
  , (SELECT COUNT(*) FROM CUSTOMERDELIVERYDAY CDD WHERE CUSTOMER.CUSTOMER_ID = CDD.CUSTOMER_ID
        AND CDD.DAY_ID = PACKINGNOTE.DAYNUMBER AND CDD.TYPEOFMERCHADISE =2) DELIVERGARMENTS,
        PACKINGNOTE.STOPNUMBER, ROUTE.PUTUPREPORTPERCUSTOMER,
		CUSTOMER.EXTRANAME1, CUSTOMER.LEGACYCUSTOMERNUMBER, DI.CODE DISTRICTDESC, DI.DESCRIPTION DISTRICTCODE, ROUTECONTROL.ROUTECONTROL_ID
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, PLANTDEPARTMENT,
       TRANSPORTARTICLE,STATUS, DELIVERYPOINT, ADDRESS,
       BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU,
       PACKINGNOTE
       LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
       LEFT OUTER JOIN ROUTECONTROL ON (PACKINGNOTE.ROUTECONTROL_ID = ROUTECONTROL.ROUTECONTROL_ID )
       LEFT OUTER JOIN CONSIGNMENTNOTE ON (PACKINGNOTE.CONSIGNMENTNOTE_ID = CONSIGNMENTNOTE.CONSIGNMENTNOTE_ID)
       LEFT OUTER JOIN ROUTE
              LEFT OUTER JOIN DEPOT ON DEPOT.DEPOT_ID = ROUTE.DEPOT_ID
              LEFT OUTER JOIN EMPLOYEE DRIVER ON DRIVER.EMPLOYEE_ID = ROUTE.DRIVER_ID
              INNER JOIN DISTRICT DI ON DI.DISTRICT_ID = ROUTE.DISTRICT_ID
        ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID,
       LANGUAGES
 	WHERE
      PACKINGNOTE.TRANSPORTARTICLE_ID = TRANSPORTARTICLE.TRANSPORTARTICLE_ID
  AND PACKINGNOTE.STATUS_ID = STATUS.STATUS_ID
  AND STATUS.STATUSTYPE = 'PN'
  AND STATUS.CODE IN ('10','20','30')
  AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = ADDRESS.ADDRESS_ID
	AND PACKINGNOTE.PLANTDEPARTMENT_ID = PLANTDEPARTMENT.PLANTDEPARTMENT_ID
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
	AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  AND PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
	AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
	AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID

/
create or replace view V_BULKPUTUPLIST
 (ROUTECONTROL_ID, PLANTCODE, ROUTENUMBER, ROUTEDESCRIPTION, DEPOTECODE, DEPOTDESCRIPTION, DRIVERNAME, DRIVINGDATE, LOADINGDOCK, STARTTIME, TRUCKCODE, TRUCKDESCRIPTION, CUSTOMERNUMBER, SEARCHNAME, LEGALNAME, PRODUCTCODE, PRODUCTDESCRIPTION, PUTUPREPORTROUTESTOP, SIZECODE, FINISHINGMETHODCODE, TOBEDELIVEREDAMOUNT, DISTRIBUTIONPOINTNUMBER, REMARKONPACKINGNOTE, LANGUAGECODE, REPLACEMENTQTY, REPLACEMENTLOSSQTY)
as SELECT A.ROUTECONTROL_ID,
  D.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, X.CODE DEPOTECODE, X.DESCRIPTION DEPOTDESCRIPTION,
  Y.NAME DRIVERNAME, A.DRIVINGDATE, A.LOADINGDOCK, A.PACKINGDEADLINE STARTTIME, Z.CODE TRUCKCODE,
  Z.DESCRIPTION TRUCKDESCRIPTION, K.CUSTOMERNUMBER, K.SEARCHNAME, K.LEGALNAME, J.CODE PRODUCTCODE,
  (SELECT description FROM PRODUCT_DESC W WHERE J.PRODUCT_ID = W.PRODUCT_ID AND W.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
  B.PUTUPREPORTROUTESTOP,
  H.CODE SIZECODE, I.CODE FINISHINGMETHODCODE, G.TOBEDELIVEREDAMOUNT,
  L.DISTRIBUTIONPOINTNUMBER, L.REMARKONPACKINGNOTE,
  LANGUAGES.CODE LANGUAGECODE,
  G.REPLACEMENTQTY, G.REPLACEMENTLOSSQTY
FROM ROUTECONTROL A,
  ROUTE B
    left outer join DEPOT X ON (X.DEPOT_ID = B.DEPOT_ID)
    left outer join EMPLOYEE Y ON (Y.EMPLOYEE_ID = B.DRIVER_ID)
    left outer join TRUCK Z ON (Z.TRUCK_ID = B.TRUCK_ID),
  PLANT D,
  STOP E,
  PACKINGNOTE F, PACKINGNOTELINE G, SIZEDEFINITION H, FINISHINGMETHOD I, PRODUCT J,
  CUSTOMER K, LANGUAGES, DISTRIBUTIONPOINT L
WHERE A.ROUTE_ID = B.ROUTE_ID AND
  A.PLANT_ID = D.PLANT_ID AND
  A.ROUTECONTROL_ID = E.ROUTECONTROL_ID AND
  E.STOP_ID = F.STOP_ID AND
  F.PACKINGNOTE_ID = G.PACKINGNOTE_ID AND
  G.SIZEDEFINITION_ID = H.SIZEDEFINITION_ID AND
  G.FINISHINGMETHOD_ID = I.FINISHINGMETHOD_ID AND
  G.PRODUCT_ID = J.PRODUCT_ID AND
  E.CUSTOMER_LINK_ID = K.CUSTOMER_ID AND
  F.DISTRIBUTIONPOINT_ID = L.DISTRIBUTIONPOINT_ID and
  (e.status = 0 or e.status = 3) and
  (g.putuptype = 2 or g.putuptype = 4) AND
  B.ACTIVE = 'Y'

/
create or replace view V_BULKSHORTAGE
 (CUSTOMERNUMBER, CUSTOMERNAME, DELIVERYDATE, DELIVERYDATE_WEEK, DELIVERYDATE_DAYDESC, CONSIGNMENTNOTENUMBER, CONSIGNMENTNOTE_ID, PRODUCTCODE, SIZECODE, FINISHINGCODE, PRODUCTDESC, ORDEREDAMOUNT, DELIVEREDAMOUNT, SHORTAGEAMOUNT, LANGUAGECODE)
as select distinct
  cu.customernumber, cu.name customerName
, pn.deliverydate, pn.week deliverydate_Week
, ( select day_desc.description from day_desc where day_desc.day_id = pn.daynumber
  and day_desc.language_id = languages.language_id ) deliverydate_DayDesc
, cn.consignmentnotenumber, cn.consignmentnote_id
, 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
, pnl.tobedeliveredamount OrderedAmount
, pnl.deliveredAmount
, ( pnl.tobedeliveredamount - pnl.deliveredamount ) shortageAmount
, languages.code languageCode
from
  packingnote pn, packingnote bin, consignmentnote cn
, distributionpoint dip, department dep, customer cu
, packingnoteline pnl
, product prd, sizedefinition sz, finishingmethod fm
, languages
where
    pn.packingnote_id = bin.bulkpackingnote_id
and bin.consignmentnote_id = cn.consignmentnote_id
and pn.distributionpoint_id = dip.distributionpoint_id
    and dip.department_id = dep.department_id
        and dep.customer_id = cu.customer_id
            --and cu.printconsignmentnote = 'Y'
            and cu.consignmentnotelevel > 0
and pn.packingnote_id = pnl.packingnote_id
    and pnl.deliveredamount < pnl.tobedeliveredamount
        and pnl.product_id = prd.product_id
        and pnl.sizedefinition_id = sz.sizedefinition_id
        and pnl.finishingmethod_id = fm.finishingmethod_id

/
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_CAGESBAGS_ECL
 (ROUTE_ID, STOP_ID, CAGENUMBERCOLI, BAGNUMBERCOLI)
as select pn.route_id, pn.stop_id,
sum(case when pn.transportarticle_id IN (select td.transportarticle_id from transportarticle_desc td where td.description like '%Cage%')
  then pn.numberofcolli else 0 end) cagenumbercoli,
sum(case when pn.transportarticle_id IN (select td.transportarticle_id from transportarticle_desc td where td.description like '%Bag%')
  then pn.numberofcolli else 0 end) bagnumbercoli
from
  packingnote pn,
  stop sp, customer c--, routecontrol rc, route r
where pn.stop_id = sp.stop_id
  and sp.customer_link_id = c.customer_id  --and sp.routecontrol_id = rc.routecontrol_id  --and rc.route_id = r.route_id
  and pn.straightevenreturn = 'N'
  and c.bulkpacking = 'N'
  and pn.status_id <> (select s.status_id from status s where s.statustype = 'PN' and s.factorydescription = 'Cancelled')
  and (select COUNT(1) from packingnoteline pnl where pnl.putuptype <> 2 and pnl.packingnote_id = pn.packingnote_id) > 0
group by pn.route_id, pn.stop_id--, pn.transportarticle_id

/
create or replace view V_CAGES_PCO
 (NR)
as select rownum nr
from (select 1 just_a_column from dual connect by level <= 1000)

/
create or replace view V_CAGES_SNG
 (NR)
as select rownum nr
from (select 1 just_a_column from dual connect by level <= 100)

/
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_DELAYEDDELIVERY_CBD
 (LINETYPE, CLIENTDELIVERYNOTE_ID, PACKINGSEQUENCE, PRODUCTCODE, SIZECODE, FINISHINGMETHODCODE, PRODUCTDESC, PRIMARYID, LANGUAGECODE, PRODCUSTOM_CODE, PRODCUSTOM_DESC)
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
, 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' )
        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
, 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
, 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' )
        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
, 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_DELAYEDDELIVERY_CLO
 (LINETYPE, CLIENTDELIVERYNOTE_ID, PACKINGSEQUENCE, PRODUCTCODE, SIZECODE, FINISHINGMETHODCODE, PRODUCTDESC, PRIMARYID, 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
, 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' )
        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 cdn.closingdate is not null
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
, 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 cdn.closingdate is not null
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
, 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' )
        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 cdn.closingdate is not null
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
, 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 cdn.closingdate is not null
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_CBD
 (LINETYPE, CLIENTDELIVERYNOTE_ID, PACKINGSEQUENCE, PRODUCTCODE, SIZECODE, FINISHINGMETHODCODE, PRODUCTDESC, PRIMARYID, FROMNOTENR, FROMDELDATE, LANGUAGECODE, PRODCUSTOM_CODE, PRODCUSTOM_DESC)
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
, 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'
            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
, 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
, 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'
            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
, 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_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_RECEIVEFROMOWNER_CBD
 (LINETYPE, CLIENTDELIVERYNOTE_ID, PACKINGSEQUENCE, PRODUCTCODE, SIZECODE, FINISHINGMETHODCODE, PRODUCTDESC, PRIMARYID, OWNERNUMBER, OWNERNAME, ROOMNUMBER, NOTENUMBER, LANGUAGECODE, PRODCUSTOM_CODE, PRODCUSTOM_DESC)
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.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_note.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_CBD
 (LINETYPE, CLIENTDELIVERYNOTE_ID, PACKINGSEQUENCE, PRODUCTCODE, SIZECODE, FINISHINGMETHODCODE, PRODUCTDESC, PRIMARYID, OWNERNUMBER, OWNERNAME, ROOMNUMBER, NOTENUMBER, LANGUAGECODE, PRODCUSTOM_CODE, PRODCUSTOM_DESC)
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
, 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
, 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_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_CHECK_CONVERSION_DEPT_DAYID
 (CUSTOMERNUMBER, DEPARTMENTNUMBER, CUSTOMER_ID, DEPARTMENT_ID, DAY_ID)
as select x.customernumber, x.departmentnumber, x.customer_id, x.department_id, d.day_id
from   (select c.customernumber, c.customer_id, t.department_id, t.departmentnumber,
                case
                  when max(i.quantity_mo) is not null then
                   1
                  else
                   null
                end mo,
                case
                  when max(i.quantity_tu) is not null then
                   2
                  else
                   null
                end tu,
                case
                  when max(i.quantity_we) is not null then
                   3
                  else
                   null
                end we,
                case
                  when max(i.quantity_th) is not null then
                   4
                  else
                   null
                end th,
                case
                  when max(i.quantity_fr) is not null then
                   5
                  else
                   null
                end fr,
                case
                  when max(i.quantity_sa) is not null then
                   6
                  else
                   null
                end sa,
                case
                  when max(i.quantity_su) is not null then
                   7
                  else
                   null
                end su
         from   i_deliverystandards i
         join   customer c
         on     c.customernumber = i.customernumber
         join   department t
         on     t.departmentnumber = i.departmentnumber
         and    t.customer_id = c.customer_id
         group  by c.customernumber, t.departmentnumber, c.customer_id, t.department_id) x
join   day d
on     ((d.day_id = x.mo) or (d.day_id = x.tu) or (d.day_id = x.we) or (d.day_id = x.th) or
       (d.day_id = x.fr) or (d.day_id = x.sa) or (d.day_id = x.su))
group  by x.customernumber, x.departmentnumber, x.customer_id, x.department_id, d.day_id
union
select c.customernumber, t.departmentnumber, t.customer_id, t.department_id, dd.daynumber
from   i_deliverydays dd
join   i_consumptionpoint cp
on     (dd.customernumber = cp.customernumber and dd.deliverypointcode = cp.deliverypointnumber)
join   customer c
on     c.customernumber = cp.customernumber
join   department t
on     (t.customer_id = c.customer_id and t.departmentnumber = cp.departmentnumber)
group  by c.customernumber, t.departmentnumber, t.customer_id, t.department_id, dd.daynumber

/
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, 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 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_CIRCINVENTORYHISTORY_UDR
 (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_LLG
 (DEFAULTBUSINESSUNIT_ID, BUSINESSUNIT_ID, BU_CODE, 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, DATEACTIVE, DATEINACTIVE, ORIGIN, SAMPLEITEM, MINTURNAROUNDPERC, DELIVERYVARIATIONS_ID, DV_DELDATE)
as SELECT cus.defaultbusinessunit_id, bu.businessunit_id, bu.code bu_code,
       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
       , sdl.dateactive, sdl.dateinactive
       , rqa.origin, rqa.sampleitem
       , coalesce((select plpc.minimumturnaround from productlistpercustomer plpc
          where plpc.productlistpercustomer_id = sdl.productlistpercustomer_id),0)/100 minturnaroundperc
       , rqa.deliveryvariations_id
       , (select dv.deliverydate from deliveryvariations dv where dv.deliveryvariations_id = rqa.deliveryvariations_id) dv_deldate
FROM rentalqtyadjustment rqa,
     productlistperdistribpoint pld, standarddeliveryline sdl
     , 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 and
      pld.productlistperdistribpoint_id=sdl.productlistperdistribpoint_id
group by cus.defaultbusinessunit_id, bu.businessunit_id, bu.code,
      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
      , sdl.dateactive, sdl.dateinactive, sdl.productlistpercustomer_id
      , rqa.origin, rqa.sampleitem, rqa.deliveryvariations_id

/
create or replace view V_CIRCULATINGINVENTORYQTY_SGS
 (DEFAULTBUSINESSUNIT_ID, DISTRIBUTIONPOINT_ID, BUSINESSUNIT_ID, BU_CODE, BU_DESC, CUSTOMER_ID, PRODUCT_ID, SIZEDEFINITION_ID, FINISHINGMETHOD_ID, CUSTOMERNUMBER, PRODUCT_CODE, DEPARTMENTNUMBER, DISTRIBUTIONPOINTNUMBER, SIZEDEF_CODE, FINISHING_CODE, NAME, CITY, DEP_DESC, DISTRIB_DESC, QUANTITY, COUNTWEARERS, FINISHING_DESC, SIZEDEF_DESC, PRODUCT_DESC, MIN_ACTIVITY_ID, LANGUAGE_CODE, ADJUSTMENTDATE, SAMPLEITEM, DATEACTIVE, DATEINACTIVE, WIDTH_S, LENGTH_S, PRODUCTGROUP_CODE, TYPEOFMERCHANDISE
, PRODUCTGROUP_DESC, SALES_PRICE, RENT_PRICE, WEEKLYREVENUEQTY)
as SELECT  /*+ parallel */  cus.defaultbusinessunit_id,  dp.distributionpoint_id, bu.businessunit_id, bu.code bu_code, bu.description bu_desc, cus.customer_id,  p.product_id, s.sizedefinition_id, f.finishingmethod_id,
       cus.customernumber, p.code Product_code, dep.departmentnumber, dp.distributionpointnumber,
       s.code Sizedef_code, f.code Finishing_code, cus.name, 'city' city, dep.description Dep_desc, dp.description Distrib_desc,
       rqa.quantity quantity,
        0 CountWearers,
       (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, rqa.sampleitem
       , sdl.dateactive, sdl.dateinactive,
       s.WIDTH WIDTH_S, s.LENGTH LENGTH_S--CSW
       , pg.code ProductGroup_code, p.typeofmerchandise--2 = garment else non-garment
       , (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id and pgd.language_id = l.language_id) ProductGroup_desc
       , coalesce((select max(spp.purchaseprice)
                from supplierproduct s, productsizepersupproduct pss, supplierproductprice spp
                where s.supplierproduct_id = pss.supplierproduct_id and
                      s.supplierproduct_id = spp.supplierproduct_id and
                      pss.product_id = p.product_id and
                      spp.startdate <= sysDate and
                      (  pss.sizedefinition_id = s.sizedefinition_id
                         or
                         pss.sizedefinition_id = (select sz.sizedefinition_id from sizedefinition sz where sz.code = '*')
                         or
                         s.sizedefinition_id = (select sz.sizedefinition_id from sizedefinition sz where sz.code = '*')
                       ) ), rqa.salesprice,
                       PACK_PRICE.Sales_Price(cus.CUSTOMER_ID, P.PRODUCT_ID, s.SIZEDEFINITION_ID, rqa.adjustmentdate)) Sales_Price
       , PACK_PRICE.Rent_Price(cus.CUSTOMER_ID, P.PRODUCT_ID, s.SIZEDEFINITION_ID, f.finishingmethod_id, rqa.adjustmentdate) Rent_Price
        , case when
                    rqa.sampleitem = 'N' then rqa.quantity--SUM(rqa.quantity)
        else 0 end WeeklyRevenueQty
FROM  customer cus inner join businessunit bu on cus.defaultbusinessunit_id=bu.businessunit_id
                   inner join department dep on cus.customer_id=dep.customer_id
                              inner join distributionpoint dp on dep.department_id=dp.department_id
                                         inner join productlistperdistribpoint pld on dp.distributionpoint_id=pld.distributionpoint_id
                                                    inner join rentalqtyadjustment rqa on pld.productlistperdistribpoint_id=rqa.productlistperdistribpoint_id
                                                    inner join product p on pld.product_id=p.product_id
                                                          inner join productgroup pg on p.productgroup_id=pg.productgroup_id
                                                    inner join sizedefinition s on pld.sizedefinition_id=s.sizedefinition_id
                                                    inner join finishingmethod f on pld.finishingmethod_id=f.finishingmethod_id
                                                    inner join standarddeliveryline sdl on pld.productlistperdistribpoint_id=sdl.productlistperdistribpoint_id
      cross join languages l
WHERE p.typeofmerchandise <> 2
union all
SELECT /*+ parallel*/
 cus.defaultbusinessunit_id, dp.distributionpoint_id, bu.businessunit_id, bu.code bu_code, bu.description bu_desc, cus.customer_id, p.product_id, s.sizedefinition_id, f.finishingmethod_id,
       cus.customernumber, p.code Product_code, dep.departmentnumber, dp.distributionpointnumber,
       s.code Sizedef_code, f.code Finishing_code, cus.name, 'city' city, dep.description Dep_desc, dp.description Distrib_desc,
       get_circinventory(cus.customer_id, dp.distributionpoint_id, p.product_id, s.sizedefinition_id, f.finishingmethod_id, 'sum') quantity,
       get_circinventory(cus.customer_id, dp.distributionpoint_id, p.product_id, s.sizedefinition_id, f.finishingmethod_id, 'count')  CountWearers,
       (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, plpc.dateactive adjustmentdate, ' ' sampleitem
       , plpc.dateactive, plpc.dateinactive,
        s.WIDTH WIDTH_S, s.LENGTH LENGTH_S--CSW
       , pg.code ProductGroup_code, p.typeofmerchandise--2 = garment else non-garment
       , (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id and pgd.language_id = l.language_id) ProductGroup_desc,
        coalesce((select max(spp.purchaseprice)
                from supplierproduct sp, productsizepersupproduct pss, supplierproductprice spp
                where sp.supplierproduct_id = pss.supplierproduct_id and
                      sp.supplierproduct_id = spp.supplierproduct_id and
                      pss.product_id = p.product_id and
                      spp.startdate <= sysDate and
                      (  pss.sizedefinition_id = s.sizedefinition_id
                         or
                         pss.sizedefinition_id = (select sz.sizedefinition_id from sizedefinition sz where sz.code = '*')
                         or
                         s.sizedefinition_id = (select sz.sizedefinition_id from sizedefinition sz where sz.code = '*')
                       ) ),
                       PACK_PRICE.Sales_Price(cus.CUSTOMER_ID, P.PRODUCT_ID, s.SIZEDEFINITION_ID, sysdate)) Sales_Price,
        PACK_PRICE.Rent_Price(cus.CUSTOMER_ID, P.PRODUCT_ID, s.SIZEDEFINITION_ID, f.finishingmethod_id, sysdate) Rent_Price
   ,get_weeklyrevenueqty(plpc.billingmethod, cus.customer_id, p.product_id, s.sizedefinition_id, f.finishingmethod_id, dp.distributionpoint_id )  WeeklyRevenueQty
FROM productlistpercustomer plpc
     , distributionpoint dp, department dep, customer cus
     , product p, PRODUCTGROUP pg
     , sizedefinition s, finishingmethod f
     , businessunit bu, languages l
WHERE  cus.defaultbusinessunit_id = bu.businessunit_id and
        plpc.customer_id = cus.customer_id and
      dp.department_id = dep.department_id and
      dep.customer_id = cus.customer_id and
      plpc.product_id = p.product_id and
      plpc.sizedefinition_id = s.sizedefinition_id
       and plpc.finishingmethod_id = f.finishingmethod_id and
      p.productgroup_id = pg.productgroup_id and p.typeofmerchandise = 2

/
create or replace view V_CIRCULATINGINVENTORY_SMG
 (DEFAULTBUSINESSUNIT_ID, CUSTOMERNUMBER, PRODUCT_CODE, DEPARTMENTNUMBER, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT_ID, SIZEDEF_CODE, FINISHING_CODE, CUSTOMERNAME, CITY, DEP_DESC, DISTRIB_DESC, QUANTITY, FINISHING_DESC, SIZEDEF_DESC, PRODUCT_DESC, LANGUAGE_CODE, ADJUSTMENTDATE, TYPEOFMERCHANDISE, PRODGRCODE, CPL_DATEINACTIVE)
as SELECT cus.defaultbusinessunit_id, cus.customernumber, p.code Product_code, dep.departmentnumber, dp.distributionpointnumber, dp.distributionpoint_id,
       s.code Sizedef_code, f.code Finishing_code, cus.name customername, 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,
       l.code Language_code, rqa.adjustmentdate, p.typeofmerchandise, pg.code ProdGrCode,
       (select max(cpl.dateinactive) from standarddeliveryline cpl where cpl.productlistperdistribpoint_id = pld.productlistperdistribpoint_id) CPL_DateInactive
FROM rentalqtyadjustment rqa, productlistperdistribpoint pld
     , distributionpoint dp, department dep, customer cus, address a
     , productgroup pg, activity ac, product p, sizedefinition s, finishingmethod f
     , 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 and
      pg.productgroup_id = p.productgroup_id and ac.activity_id = pg.activity_id and
      ac.code in ('FR', 'FW', 'HS', 'MA', 'RT', 'BK', 'CR' ) and
      rqa.quantity <> 0 --and rqa.adjustmentdate <= sysdate
group by cus.defaultbusinessunit_id, cus.customer_id, cus.customernumber, cus.name, a.city,
      dep.departmentnumber, dep.description, dp.distributionpoint_id, 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, p.typeofmerchandise, pg.code, pld.productlistperdistribpoint_id

/
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)
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 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.sizedefinition_id=ui.sizedefinition_id or plpc.sizedefinition_id=(select sd.sizedefinition_id from sizedefinition sd where sd.code='*'))
and plpc.finishingmethod_id=ui.finishingmethod_id
) 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,
(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 or plpc2.sizedefinition_id=(select sd.sizedefinition_id from sizedefinition sd where sd.code='*'))
   and plpc2.finishingmethod_id=ui.finishingmethod_id
) remarkforpackinginstructions,
cbcust.deliverydate,cbcust.requiredsterilizationdate, COUNT(1) inscan
from  cleanroombatchcontent cbc
left outer join cleanroombatchcustomer cbcust on cbcust.cleanroombatchcustomer_id=cbc.cleanroombatchcustomer_id
inner join distributionpoint dp on cbcust.distributionpoint_link_id=dp.distributionpoint_id
inner join department dep on dep.department_id=dp.department_id
inner join customer c on c.customer_id=dep.customer_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 product parent_product on parent_product.product_id=p.parentproduct_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 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.sizedefinition_id=ri.sizedefinition_link_id or plpc.sizedefinition_id=(select sd.sizedefinition_id from sizedefinition sd where sd.code='*'))
  and plpc.finishingmethod_id=ri.finishingmethod_id) 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,
(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 or plpc2.sizedefinition_id=(select sd.sizedefinition_id from sizedefinition sd where sd.code='*'))
   and plpc2.finishingmethod_id=ri.finishingmethod_id
) remarkforpackinginstructions,
cbcust.deliverydate,cbcust.requiredsterilizationdate, COUNT(1) inscan
from  cleanroombatchcontent cbc
left outer join cleanroombatchcustomer cbcust on cbcust.cleanroombatchcustomer_id=cbc.cleanroombatchcustomer_id
inner join distributionpoint dp on cbcust.distributionpoint_link_id=dp.distributionpoint_id
inner join department dep on dep.department_id=dp.department_id
inner join customer c on c.customer_id=dep.customer_id
inner join raggeditem ri on cbc.raggeditem_id =ri.raggeditem_id
inner join product p on ri.product_link_id=p.product_id
inner join product parent_product on parent_product.product_id=p.parentproduct_id
left outer join finishingcode fc on fc.finishingcode_id= p.finishingcode_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.product_link_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 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.sizedefinition_id=cbcont.sizedefinition_link_id or plpc.sizedefinition_id=(select sd.sizedefinition_id from sizedefinition sd where sd.code='*'))
   and plpc.finishingmethod_id=cbcont.finishingmethod_id) 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,
(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=cbcont.product_link_id
   and (plpc2.sizedefinition_id=cbcont.sizedefinition_link_id or plpc2.sizedefinition_id=(select sd.sizedefinition_id from sizedefinition sd where sd.code='*'))
   and plpc2.finishingmethod_id=cbcont.finishingmethod_id
) remarkforpackinginstructions,
cbcust.deliverydate,cbcust.requiredsterilizationdate, SUM(cbcont.QUANTITY) inscan
from CLEANROOMBATCHCOUNTCONTENT  cbcont
inner join cleanroombatchcustomer cbcust on cbcust.cleanroombatchcustomer_id=cbcont.cleanroombatchcustomer_id
inner join distributionpoint dp on cbcust.distributionpoint_link_id=dp.distributionpoint_id
inner join department dep on dep.department_id=dp.department_id
inner join customer c on c.customer_id=dep.customer_id
inner join product p on cbcont.product_link_id=p.product_id
inner join product parent_product on parent_product.product_id=p.parentproduct_id
left outer join finishingcode fc on fc.finishingcode_id= p.finishingcode_id
cross join languages
group by cbcust.cleanroombatch_id,dp.deliverypoint_id, parent_product.code , dp.description, c.name,
dp.distributionpoint_id, cbcont.product_link_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, cbcont.sizedefinition_link_id, cbcont.finishingmethod_id, c.customer_id

/
create or replace view V_CLEANROOMBOXLABEL_ELJ
 (CUSTOMERNUMBER, NAME, STREET, STREET2, CITY, ZIPCODE, COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCR, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESC, CLEANROOMBATCHPKBOX_ID, DELIVERYDATE, CLEANROOMBATCHNUMBER, BOXNUMBER, DELIVEREDQTY, CODE, PRODUCTDESC, FMCODE, SORTADDRESS, PLANTCODE, LANGCODE)
as select
c.customernumber,c.name
,ad.street,ad.street2,ad.city,ad.zipcode,ad.county
,d.departmentnumber,d.description departmentdescr,
db.distributionpointnumber,db.description distributionpointdesc
,cbpb.cleanroombatchpkbox_id
,cbc.deliverydate,cb.cleanroombatchnumber
,cbpb.boxnumber,cbpbq.quantity deliveredqty
,p.code
,( select psc.description from product_desc psc where psc.product_id = p.parentproduct_id and psc.language_id = l.language_id) productDesc
,fm.code fmcode
, (select dp.sortaddress from deliverypoint dp where dp.deliverypoint_id=db.deliverypoint_id) sortaddress,
(select p.code from plant p join businessunit bu on p.plant_id=bu.plant_id where cb.businessunit_id=bu.businessunit_id) plantcode
,l.code langcode
from cleanroombatch cb
join cleanroombatchcustomer cbc on cb.cleanroombatch_id = cbc.cleanroombatch_id
join cleanroombatchpkbox cbpb on cbc.cleanroombatchcustomer_id = cbpb.cleanroombatchcustomer_id
join cleanroombatchpkboxqty cbpbq on cbpb.cleanroombatchpkbox_id = cbpbq.cleanroombatchpkbox_id
join distributionpoint db on db.distributionpoint_id=cbc.distributionpoint_link_id
join department d on d.department_id=db.department_id
join customer c on c.customer_id=d.customer_id
join deliverypoint del on del.deliverypoint_id=db.deliverypoint_id
join address ad on ad.address_id=del.deliveryaddress_id
join product p on p.product_id=cbpbq.product_link_id
join finishingmethod fm on fm.finishingmethod_id=cbpbq.finishingmethod_id
join languages l on l.language_id=c.language_id

/
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_CLIENTBUDGETCONDENSED_CBD
 (DELTOCUSTOMER_LINK_ID, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEHEADER_ID, INVOICENUMBER, INVOICEDATE, DELTOSTREET, DELTOSTREET2, DELTOZIPCODE, DELTOCITY, STARTYEAR, STARTMONTH, STARTWEEK, STARTDATE, ENDYEAR, ENDMONTH, ENDWEEK, ENDDATE, BILLEDQTY, AMOUNT, ORIGINALAMOUNT, 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, PARENTINVOICEHEADER_ID, CONSOLIDATEDINVOICE, BUDGETCLIENT, BUDGETUSAGE, SALESAREA)
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.originalamount, 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,ih.parentinvoiceheader_id,
       (select cbi.consolidatedinvoice from customerbillinginfo cbi where cbi.customer_id=ih.billtocustomer_link_id) consolidatedinvoice,
       cl.budgetclient, plpc.budgetusage, C.Salesarea_Id Salesarea
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,
      productlistpercustomer plpc,
      customer c
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
      and c.customer_id=coalesce(ih.deltocustomer_link_id,ih.billtocustomer_link_id)
      and plpc.product_id=cdl.product_link_id
      and (cdl.sizedefinition_link_id = plpc.sizedefinition_id or plpc.sizedefinition_id = (select sd1.sizedefinition_id from sizedefinition sd1 where sd1.code='*'))
      and plpc.finishingmethod_id=cdl.finishingmethod_id
      and plpc.customer_id=coalesce(ih.deltocustomer_link_id,ih.billtocustomer_link_id)
      and plpc.dateactive <= ih.invoicedate and plpc.dateinactive > ih.invoicedate
      and ((cl.budgetclient in (0,2) and plpc.budgetusage in (0,2))
	      or
          (cl.budgetclient = 0 and plpc.budgetusage = 1 and cl.clientnumber between 9000 and 9999)
		  )

/
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_CLIENTBUDGETDETAILED_CBD
 (DELTOCUSTOMER_LINK_ID, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEHEADER_ID, INVOICENUMBER, INVOICEDATE, DELTOSTREET, DELTOSTREET2, DELTOZIPCODE, DELTOCITY, STARTYEAR, STARTMONTH, STARTWEEK, STARTDATE, ENDYEAR, ENDMONTH, ENDWEEK, ENDDATE, BILLEDQTY, AMOUNT, ORIGINALAMOUNT, 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, PARENTINVOICEHEADER_ID, CONSOLIDATEDINVOICE, BUDGETCLIENT, BUDGETUSAGE, SALESAREA)
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.originalamount, 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,ih.parentinvoiceheader_id,
       (select cbi.consolidatedinvoice from customerbillinginfo cbi where cbi.customer_id=ih.billtocustomer_link_id) consolidatedinvoice,
       cl.budgetclient, plpc.budgetusage, C.Salesarea_Id Salesarea
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,
      productlistpercustomer plpc,
      customer c
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
      and plpc.product_id=cdl.product_link_id
      and (cdl.qtyscannedout +cdl.qtycountedout)<>0 --evb: needed because of wrong suppress in report
      and (cdl.sizedefinition_link_id = plpc.sizedefinition_id or plpc.sizedefinition_id = (select sd1.sizedefinition_id from sizedefinition sd1 where sd1.code='*'))
      and c.customer_id=coalesce(ih.deltocustomer_link_id,ih.billtocustomer_link_id)
      and plpc.finishingmethod_id=cdl.finishingmethod_id
      and plpc.customer_id=coalesce(ih.deltocustomer_link_id,ih.billtocustomer_link_id)
      and plpc.dateactive <= ih.invoicedate and plpc.dateinactive > ih.invoicedate
      and (cl.budgetclient=0 and plpc.budgetusage in(0,2)
      or cl.budgetclient = 0
      and plpc.budgetusage =1 and cl.clientnumber between 9000 and 9999
            or cl.budgetclient = 2 and plpc.budgetusage in (0, 2))

/
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_CLIENTCOST_SMG
 (LINETYPE, INVOICEHEADER_ID, CLIENTNUMBER, NAME, SELFPAYMENT, DEPARTMENTNUMBER, DEPDESC, DISTRIBUTIONPOINTNUMBER, DISTRIBDESC, ROOMNUMBER, PARENTINVOICEHEADER_ID, INVOICENUMBER, BILLTOCUSTOMERNUMBER, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEDATE, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, STREET, ZIPCODE, CITY, BILLTOSENDINVOICETO, PRICE, QTY, TAXPERC, PRODUCTCODE, SZCODE, FMCODE, WASHTYPE, PRODUCTDESC, FMWASHTYPECODE, CURRENCY_CODE, DECIMALS, INVOICEAMOUNTDECIMALS, CUSTTYPE
, LANGUAGECODE)
as select 1 linetype, ih.invoiceheader_id, cl.clientnumber, cl.name, cdl.selfpayment, dp.departmentnumber, dp.description depdesc,
distrib.distributionpointnumber, distrib.description distribdesc, droom.roomnumber,
ih.parentinvoiceheader_id, ih.invoicenumber, ih.billtocustomernumber, ih.deltocustomernumber,ih.deltocustomername, ih.invoicedate,
( case when ((select c.sendinvoiceto from customer c  where c.customer_id=ih.deltocustomer_link_id)=0) then  ih.deltocustomername
       else ih.billtocustomername end) billtocustomername, ih.extraname1, ih.extraname2, ih.street, ih.zipcode, ih.city,
(select c.sendinvoiceto from customer c where ih.deltocustomer_link_id = c.customer_id) billtosendinvoiceto,
il.price, (cdl.qtyscannedout + cdl.qtycountedout) qty,
(case when ih.parentinvoiceheader_id is null
 then (select max(ilv.percentage) from invoiceline a, invoicelinevarious ilv
     where a.invoiceheader_id = ih.invoiceheader_id and a.invoiceline_id = ilv.invoiceline_id
     and il.taxgroupcode = a.code)
 else (select max(ilv.percentage) from invoiceline a, invoiceline ilh, invoicelinevarious ilv, invoiceheader parh
       where ih.parentinvoiceheader_id = parh.invoiceheader_id and ilh.invoiceheader_id = parh.invoiceheader_id and
       ilh.invoiceline_id = ilv.invoiceline_id and a.taxgroupcode = ilh.code)
 end ) taxperc,
p.code productcode, sz.code szcode, fm.code fmcode, fm.washtype,
(select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = lan.language_id) productdesc,
(case when fm.washtype=1
  then 'WASCHEN'
  else 'CHEMISCH' end) fmwashtypecode,
curr.code currency_code, curr.decimals, curr.invoiceamountdecimals,
cast(F_GetCustType_smg(ih.invoiceheader_id) as varchar2(10)) custtype,
lan.code LanguageCode
from clientdeliverynote cdn, clientdeliverynoteline cdl, client cl, clientresident clred, department dp, departmentroom droom,
distributionpoint distrib, invoiceline il, invoiceheader ih, invoicelineproduct ilp, product p, sizedefinition sz, finishingmethod fm,
currency curr, languages lan
where cdn.client_link_id=cl.client_id
and cdn.clientdeliverynote_id=cdl.clientdeliverinote_id
and cdl.invoiceline_id=il.invoiceline_id
and il.invoiceheader_id=ih.invoiceheader_id
and ilp.invoiceline_id=il.invoiceline_id
and cdl.product_link_id=ilp.product_link_id
and ilp.product_link_id=p.product_id
and cdl.sizedefinition_link_id=ilp.sizedefinition_link_id
and ilp.sizedefinition_link_id=sz.sizedefinition_id
and cdl.finishingmethod_id=ilp.finishingmethod_id
and ilp.finishingmethod_id=fm.finishingmethod_id
and clred.client_id=cl.client_id
and clred.departmentroom_id=droom.departmentroom_id
and droom.department_id=dp.department_id
and droom.distributionpoint_id=distrib.distributionpoint_id
and curr.currency_id = ih.currency_id
union all
select 2 linetype, ih.invoiceheader_id, cl.clientnumber,cl.name, cdl.selfpayment, dp.departmentnumber, dp.description depdesc,
distrib.distributionpointnumber, distrib.description distribdesc, '' roomnumber,
ih.parentinvoiceheader_id, ih.invoicenumber, ih.billtocustomernumber, ih.deltocustomernumber,ih.deltocustomername, ih.invoicedate,
( case when ((select c.sendinvoiceto from customer c  where c.customer_id=ih.deltocustomer_link_id)=0) then  ih.deltocustomername
       else ih.billtocustomername end) billtocustomername, ih.extraname1, ih.extraname2, ih.street, ih.zipcode, ih.city,
(select c.sendinvoiceto from customer c where ih.deltocustomer_link_id = c.customer_id) billtosendinvoiceto,
il.price, (cdl.qtyscannedout+cdl.qtycountedout) qty,
(case when ih.parentinvoiceheader_id is null
 then (select max(ilv.percentage) from invoiceline a, invoicelinevarious ilv
     where a.invoiceheader_id = ih.invoiceheader_id and a.invoiceline_id = ilv.invoiceline_id
     and il.taxgroupcode = a.code)
 else (select max(ilv.percentage) from invoiceline a, invoiceline ilh, invoicelinevarious ilv, invoiceheader parh
       where ih.parentinvoiceheader_id = parh.invoiceheader_id and ilh.invoiceheader_id = parh.invoiceheader_id and
       ilh.invoiceline_id = ilv.invoiceline_id and a.taxgroupcode = ilh.code)
 end ) taxperc,
p.code productcode, sz.code szcode, fm.code fmcode, fm.washtype,
(select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = lan.language_id) productdesc,
(case when fm.washtype=1
  then 'WASCHEN'
  else 'CHEMISCH' end) fmwashtypecode,
curr.code currency_code, curr.decimals, curr.invoiceamountdecimals,
cast(F_GetCustType_smg(ih.invoiceheader_id) as varchar2(10)) custtype,
lan.code LanguageCode
from clientdeliverynote cdn, clientdeliverynoteline cdl, client cl, clientprivateperson cpred, department dp,
distributionpoint distrib, invoiceline il, invoiceheader ih, invoicelineproduct ilp, product p, sizedefinition sz, finishingmethod fm,
currency curr, languages lan
where cdn.client_link_id=cl.client_id
and cdn.clientdeliverynote_id=cdl.clientdeliverinote_id
and cdl.invoiceline_id=il.invoiceline_id
and il.invoiceheader_id=ih.invoiceheader_id
and ilp.invoiceline_id=il.invoiceline_id
and cdl.product_link_id=ilp.product_link_id
and cdl.sizedefinition_link_id=ilp.sizedefinition_link_id
and ilp.sizedefinition_link_id=sz.sizedefinition_id
and ilp.product_link_id=p.product_id
and cdl.finishingmethod_id=ilp.finishingmethod_id
and ilp.finishingmethod_id=fm.finishingmethod_id
and cpred.client_id=cl.client_id
and cpred.distributionpoint_id=distrib.distributionpoint_id
and distrib.department_id=dp.department_id
and curr.currency_id = ih.currency_id
union all
select 3 linetype, ih.invoiceheader_id, cl.clientnumber,cl.name, null, dp.departmentnumber, dp.description depdesc,
distrib.distributionpointnumber, distrib.description distribdesc, dr.roomnumber roomnumber,
ih.parentinvoiceheader_id, ih.invoicenumber, ih.billtocustomernumber, ih.deltocustomernumber,ih.deltocustomername, ih.invoicedate,
( case when ((select c.sendinvoiceto from customer c  where c.customer_id=ih.deltocustomer_link_id)=0) then  ih.deltocustomername
       else ih.billtocustomername end) billtocustomername, ih.extraname1, ih.extraname2, ih.street, ih.zipcode, ih.city,
(select c.sendinvoiceto from customer c where ih.deltocustomer_link_id = c.customer_id) billtosendinvoiceto,
pqr.patchprice price, count(pqr.printqueueresidentialitem_id) qty,
(case when ih.parentinvoiceheader_id is null
 then (select max(ilv.percentage) from invoiceline a, invoicelinevarious ilv
     where a.invoiceheader_id = ih.invoiceheader_id and a.invoiceline_id = ilv.invoiceline_id
     and il.taxgroupcode = a.code)
 else (select max(ilv.percentage) from invoiceline a, invoiceline ilh, invoicelinevarious ilv, invoiceheader parh
       where ih.parentinvoiceheader_id = parh.invoiceheader_id and ilh.invoiceheader_id = parh.invoiceheader_id and
       ilh.invoiceline_id = ilv.invoiceline_id and a.taxgroupcode = ilh.code)
 end ) taxperc,
il.code, null szcode, null fmcode, null washtype,
il.description productdesc,
null fmwashtypecode,
curr.code currency_code, curr.decimals, curr.invoiceamountdecimals,
cast(F_GetCustType_smg(ih.invoiceheader_id) as varchar2(10)) custtype,
lan.code LanguageCode
from
printqueueresidentialitem pqr join invoiceline il on il.invoiceline_id=pqr.invoiceline_id
join invoiceheader ih on il.invoiceheader_id=ih.invoiceheader_id
join clientdeliverynote cdn on pqr.clientdeliverynote_id=cdn.clientdeliverynote_id
join client_link c_l on pqr.client_link_id= c_l.client_link_id
join client cl on cl.client_id=c_l.client_id
join departmentroom dr on c_l.departmentroom_id=dr.departmentroom_id
join department dp on dp.department_id=dr.department_id
join distributionpoint distrib on distrib.department_id=dp.department_id
join currency curr on curr.currency_id=ih.currency_id
, languages lan
where pqr.patching=1
and pqr.patchprice<>0
group by ih.invoiceheader_id, cl.clientnumber,cl.name, dp.departmentnumber, dr.roomnumber, dp.description,
distrib.distributionpointnumber, distrib.description,
ih.parentinvoiceheader_id, ih.invoicenumber, ih.billtocustomernumber, ih.deltocustomernumber,ih.deltocustomername, ih.invoicedate, pqr.patchprice, il.description,
curr.code, curr.decimals, curr.invoiceamountdecimals,lan.code, ih.billtocustomername, ih.extraname1, ih.extraname2, ih.street, ih.zipcode, ih.city,
il.code,ih.deltocustomer_link_id, il.taxgroupcode
union all
select 4 linetype, ih.invoiceheader_id, cl.clientnumber,cl.name, null, dp.departmentnumber, dp.description depdesc,
distrib.distributionpointnumber, distrib.description distribdesc, dr.roomnumber roomnumber,
ih.parentinvoiceheader_id, ih.invoicenumber, ih.billtocustomernumber, ih.deltocustomernumber,ih.deltocustomername, ih.invoicedate,
( case when ((select c.sendinvoiceto from customer c  where c.customer_id=ih.deltocustomer_link_id)=0) then  ih.deltocustomername
       else ih.billtocustomername end) billtocustomername, ih.extraname1, ih.extraname2, ih.street, ih.zipcode, ih.city,
(select c.sendinvoiceto from customer c where ih.deltocustomer_link_id = c.customer_id) billtosendinvoiceto,
pqr.patchprice price, count(pqr.printqueueresidentialitem_id) qty,
(case when ih.parentinvoiceheader_id is null
 then (select max(ilv.percentage) from invoiceline a, invoicelinevarious ilv
     where a.invoiceheader_id = ih.invoiceheader_id and a.invoiceline_id = ilv.invoiceline_id
     and il.taxgroupcode = a.code)
 else (select max(ilv.percentage) from invoiceline a, invoiceline ilh, invoicelinevarious ilv, invoiceheader parh
       where ih.parentinvoiceheader_id = parh.invoiceheader_id and ilh.invoiceheader_id = parh.invoiceheader_id and
       ilh.invoiceline_id = ilv.invoiceline_id and a.taxgroupcode = ilh.code)
 end ) taxperc,
il.code, null szcode, null fmcode, null washtype,
il.description productdesc,
null fmwashtypecode,
curr.code currency_code, curr.decimals, curr.invoiceamountdecimals,
cast(F_GetCustType_smg(ih.invoiceheader_id) as varchar2(10)) custtype,
lan.code LanguageCode
from
printqueueresidentialitem pqr join invoiceline il on il.invoiceline_id=pqr.invoiceline_id
join invoiceheader ih on il.invoiceheader_id=ih.invoiceheader_id
join clientdeliverynote cdn on pqr.clientdeliverynote_id=cdn.clientdeliverynote_id
join client_link c_l on pqr.client_link_id= c_l.client_link_id
join client cl on cl.client_id=c_l.client_id
join departmentroom dr on c_l.departmentroom_id=dr.departmentroom_id
join department dp on dp.department_id=dr.department_id
join distributionpoint distrib on distrib.department_id=dp.department_id
join currency curr on curr.currency_id=ih.currency_id
, languages lan
where pqr.patching<>1
and il.price<>0
group by ih.invoiceheader_id, cl.clientnumber,cl.name, dp.departmentnumber, dr.roomnumber, dp.description,
distrib.distributionpointnumber, distrib.description,
ih.parentinvoiceheader_id, ih.invoicenumber, ih.billtocustomernumber, ih.deltocustomernumber,ih.deltocustomername, ih.invoicedate, pqr.patchprice, il.description,
curr.code, curr.decimals, curr.invoiceamountdecimals,lan.code, ih.billtocustomername, ih.extraname1, ih.extraname2, ih.street, ih.zipcode, ih.city,
il.code,ih.deltocustomer_link_id, il.taxgroupcode

/
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, 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
, (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.route_id
, customer cu, batch
, client
, client_link
   left outer join (departmentroom dr
                     inner join (department de inner join customerresidentialsettings crs1 on de.customer_id = crs1.customer_id)
                     on dr.department_id = de.department_id) on client_link.departmentroom_id = dr.departmentroom_id
										 and de.customer_id = crs1.customer_id
										 and crs1.customerclients = 0
   left outer join (deliverypoint dpl inner join customerresidentialsettings crs2 on dpl.customer_id = crs2.customer_id)
	 on client_link.deliverypoint_link_id = dpl.deliverypoint_id
						and crs2.customerclients = 1
, 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 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 cdn.weighingcategory_link_id,
  cdn.processbusinessunit_id, cu.customer_id, cu.customernumber, cu.name customerName
, coalesce(de.departmentnumber, -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
, '' productCode, '' sizeCode, '' finishingmethodCode
, '' productDesc
, '' finishingmethodDesc
, 0 qtyIn
, 0 qtyOut
, 0 qty
, batch.origin batchOrigin, batch.status batchStatus
, languages.code languageCode
,  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) InvoicedTo
from
   customer cu, batch
, client
, client_link
   left outer join (departmentroom dr
                     inner join (department de inner join customerresidentialsettings crs1 on de.customer_id = crs1.customer_id)
                     on dr.department_id = de.department_id) on client_link.departmentroom_id = dr.departmentroom_id
                     and de.customer_id = crs1.customer_id
                     and crs1.customerclients = 0
   left outer join (deliverypoint dpl inner join customerresidentialsettings crs2 on dpl.customer_id = crs2.customer_id)
   on client_link.deliverypoint_link_id = dpl.deliverypoint_id
            and crs2.customerclients = 1
, clientdeliverynote cdn
    left outer join route on cdn.route_id = route.route_id
    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 cdn.invoiceline_id = il.invoiceline_id
, 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 cdn.batch_id = batch.batch_id
and cdn.processbusinessunit_id = bu.businessunit_id
    and bu.plant_id = ss.plant_id
        AND ss.name = 'BATCHCODEUSAGE'
AND NOT EXISTS (SELECT 1 FROM CLIENTDELIVERYNOTELINE CDNL WHERE CDN.CLIENTDELIVERYNOTE_ID = CDNL.CLIENTDELIVERINOTE_ID)

/
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)
as select p.clientdeliverynote_id, p.price, p.quantity
from printqueueresidentialitem p
where p.chargeable = 'Y'

/
create or replace view V_CLIENTDELIVERYNOTELINES_LTS
 (CLIENTDELIVERYNOTE_ID, PRODUCT_LINK_ID, PRICE, WEIGHINGCATEGORY_LINK_ID)
as select cdn.clientdeliverynote_id, cdl.product_link_id, cdl.price, cdn.weighingcategory_link_id
from clientdeliverynote cdn
     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 on cdl.clientdeliverynoteline_id = cds.outscanclientdelnoteline_id
      ) on cdn.clientdeliverynote_id = cdl.clientdeliverinote_id,
      languages lan

/
create or replace view V_CLIENTDELIVERYNOTESCHARGE
 (CLIENTDELIVERINOTE_ID, LANGUAGECODE, CODE, DESCRIPTION, QUANTITY, PRICE, PRICEONDELNOTE)
as select 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
from clientdeliverynotespeccharge cdsc, specialcharge sc, languages l
where cdsc.specialcharge_id = sc.specialcharge_id
-- ClientDeliveryNote.rpt

/
create or replace view V_CLIENTDELIVERYNOTEVAT
 (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_CLIENTDELIVERYNOTE_FLAG_SMG
 (UNIQUERESIDENTIALITEM_LINK_ID, LANGUAGE_CODE, FLAGCODE, FLAGDESC, CLIENTDELIVERINOTE_ID, PRIMARYID, PRODCODE, SIZECODE, FMCODE)
as select  ris.uniqueresidentialitem_link_id,  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,
cdl.clientdeliverinote_id, uir.primaryid,
(select p.code from product p where p.product_id=uirp.product_id)prodcode,
(select sd.code from sizedefinition sd where sd.sizedefinition_id=uirp.sizedefinition_id)sizecode,
(select fm.code from finishingmethod fm where fm.finishingmethod_id=uirp.finishingmethod_id)fmcode
from flag, residentialitemscan ris, residentialitemscanflag risf,uniqueresidentialitem uir,uniqueresidentialitemproduct uirp, languages, clientdeliverynoteline cdl
where risf.flag_id = flag.flag_id and ris.residentialitemscan_id = risf.residentialitemscan_id
and ris.transactiontype_id = 2 AND flag.showonwashlist = 'Y'
and ris.clientdeliverynoteline_id=cdl.clientdeliverynoteline_id
and uir.uniqueresidentialitem_id=ris.uniqueresidentialitem_link_id
and uir.uniqueresidentialitem_id=uirp.uniqueresidentialitem_id

/
create or replace view V_CLIENTDELIVERYNOTE_SMG
 (LINETYPE, PRINTPRICEONDELNOTE, PRICEDECIMALS, AMOUNTDECIMALS, PRICE, PRICEONDELNOTE, WEIGHTPRICE, CLIENTDELIVERYNOTE_ID, PROCESSBUSINESSUNIT_ID, CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESC, CLIENTNUMBER, CLIENTNAME, ROOM, CLIENTDELIVERYNOTENUMBER, CLOSINGDATE, DELIVERYDATE, BOXNUMBER, GROSSWEIGHT, WEIGHTDECIMALS, RDNNUMBER, PACKINGSEQUENCE, PRODUCTCODE, SIZECODE, FINISHINGMETHODCODE, PRODUCTDESC, QTYRECEIVED, CDLQTYDELIVERED, PRIMARYID
, CUSTOMERCLIENTS, PRINTIDCODE, PRINTQTYRECEIVED, LANGUAGECODE, UNIQUERESIDENTIALITEM_LINK_ID, OUTSCANTIMESTAMP, SEQUENCENUMBER, WORKSTATION_ID, WORKSTATION_CODE, WASHTYPE, DELIVERYPOINT_CODE, DELIVERYPOINT_DESC, PRESORTNUMBER, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT_DESC, CORRECTIONCLIENTDELNOTE_ID, OLD_QTY, QTYDELIVERED, CORRECTIONCLIENTDELNOTE_NRDATE, REPORTPARAM_ID)
as SELECT
  1 linetype, crs.printpriceondelnote, crr.decimals pricedecimals, crr.invoiceamountdecimals amountdecimals
, cdl.price, cdl.priceondelnote, cdn.weightprice
, 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
, cdn.clientdeliverynotenumber, cdn.closingdate, cdn.deliverydate, cdn.boxnumber
, cdn.grossweight, cdn.weightdecimals
, ( select pn.notenumber from packingnote pn where cdn.packingnote_id=pn.packingnote_id ) RDNNumber
, 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 ) CDLqtyDelivered
, (   select uri.primaryid
  from uniqueresidentialitem uri where cds.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id  ) primaryid
, crs.customerclients, crs.printidcode,  crs.printqtyreceived
, languages.code languageCode
/*, (SELECT plpc.customdescription FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cu.customer_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc*/
, cds.uniqueresidentialitem_link_id, GETDATEONLY(cds.outscantimestamp) outscantimestamp/* Added 10-06-09 ROP */
, cdn.sequencenumber
, ws.workstation_id, ws.code workstation_code
, fm.washtype, coalesce(delpres.code,delvp.code)deliverypoint_code, coalesce(delpres.description,delvp.description) deliverypoint_desc
, cdn.presortnumber, coalesce(dpres.distributionpointnumber ,dip.distributionpointnumber)distributionpointnumber
, coalesce(dpres.description, dip.description) distributionpoint_desc
, cdn.correctionclientdelnote_id
, (SELECT SUM(ccdl.qtyscannedout + ccdl.qtycountedout)
            FROM   clientdeliverynoteline ccdl
            WHERE  ccdl.clientdeliverinote_id = cdn.correctionclientdelnote_id AND
                   ccdl.product_link_id = cdl.product_link_id AND
                   ccdl.sizedefinition_link_id = cdl.sizedefinition_link_id AND
                   ccdl.finishingmethod_id = cdl.finishingmethod_id) OLD_QTY
, coalesce(get_qtyforresidential(cdn.clientdeliverynotenumber, cdl.clientdeliverynoteline_id, ws.code),cdl.qtyscannedout,0) qtyDelivered
, (select (castnumberasvarchar(cpn.notenumber) || ' ' || TO_CHAR(cpn.deliverydate, 'dd.mm.yyyy')) from clientdeliverynote ccdn, packingnote cpn
  where ccdn.clientdeliverynote_id = cdn.correctionclientdelnote_id and cpn.packingnote_id = ccdn.packingnote_id) correctionclientdelnote_nrdate
, rp.reportparam_id
from
  clientdeliverynote cdn
     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 on cdl.clientdeliverynoteline_id = cds.outscanclientdelnoteline_id
      ) on cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
, customer cu, currency crr
, batch, client
    left outer join
      ( clientresident cr join ( departmentroom dr join department de on dr.department_id = de.department_id
      left outer join distributionpoint dpres on dr.distributionpoint_id=dpres.distributionpoint_id
      left outer join deliverypoint delpres on dpres.deliverypoint_id=delpres.deliverypoint_id )
                            on cr.departmentroom_id = dr.departmentroom_id
      ) on client.client_id = cr.client_id
    left outer join
      ( clientprivateperson cpp
      left outer join ( deliverypoint delvp join address on delvp.deliveryaddress_id = address.address_id )
                                  on cpp.deliverypoint_id = delvp.deliverypoint_id
      join distributionpoint dip on cpp.distributionpoint_id = dip.distributionpoint_id
      ) on client.client_id = cpp.client_id
, customerresidentialsettings crs, languages
, workstation ws, reportparam rp
where cdn.clientdeliverynote_id = rp.number_value and
        coalesce(get_qtyforresidential(cdn.clientdeliverynotenumber, cdl.clientdeliverynoteline_id, ws.code),cdl.qtyscannedout,0)>0
    and 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 cu.currency_id = crr.currency_id
and ws.code = rp.string_value
union all --non unique items
SELECT
  2 linetype, crs.printpriceondelnote, crr.decimals pricedecimals, crr.invoiceamountdecimals amountdecimals
, cdl.price, cdl.priceondelnote, cdn.weightprice
, 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
, cdn.clientdeliverynotenumber, cdn.closingdate, cdn.deliverydate, cdn.boxnumber
, cdn.grossweight, cdn.weightdecimals
, ( select pn.notenumber from packingnote pn where cdn.packingnote_id=pn.packingnote_id ) RDNNumber
, 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 ) CDLqtyDelivered
, ( select uri.primaryid
  from uniqueresidentialitem uri where cds.uniqueresidentialitem_link_id = uri.uniqueresidentialitem_id  ) primaryid
, crs.customerclients, crs.printidcode,  crs.printqtyreceived
, languages.code languageCode
/*, (SELECT plpc.customdescription FROM productlistpercustomer plpc
  WHERE plpc.productlistpercustomer_id = F_GetIDColumnFromActivePLPC (cu.customer_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, sz.sizedefinition_id, cdn.deliverydate, 0)) ProdCustom_Desc*/
, cds.uniqueresidentialitem_link_id, GETDATEONLY(cds.outscantimestamp) outscantimestamp/* Added 10-06-09 ROP */
, cdn.sequencenumber
, 0 workstation_id, (select min(rp2.string_value) from reportparam rp2 where rp2.reportparam_id = rp.reportparam_id) workstation_code
, fm.washtype, coalesce(delpres.code,delvp.code)deliverypoint_code, coalesce(delpres.description,delvp.description) deliverypoint_desc
, cdn.presortnumber, coalesce(dpres.distributionpointnumber ,dip.distributionpointnumber)distributionpointnumber
, coalesce(dpres.description, dip.description) distributionpoint_desc
, cdn.correctionclientdelnote_id
, (SELECT SUM(ccdl.qtyscannedout + ccdl.qtycountedout)
            FROM   clientdeliverynoteline ccdl
            WHERE  ccdl.clientdeliverinote_id = cdn.correctionclientdelnote_id AND
                   ccdl.product_link_id = cdl.product_link_id AND
                   ccdl.sizedefinition_link_id = cdl.sizedefinition_link_id AND
                   ccdl.finishingmethod_id = cdl.finishingmethod_id) OLD_QTY
, cdl.qtycountedout qtyDelivered
, (select (castnumberasvarchar(cpn.notenumber) || ' ' || TO_CHAR(cpn.deliverydate, 'dd.mm.yyyy')) from clientdeliverynote ccdn, packingnote cpn
  where ccdn.clientdeliverynote_id = cdn.correctionclientdelnote_id and cpn.packingnote_id = ccdn.packingnote_id) correctionclientdelnote_nrdate
, rp.reportparam_id
from
  clientdeliverynote cdn
     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 on cdl.clientdeliverynoteline_id = cds.outscanclientdelnoteline_id
      ) on cdn.clientdeliverynote_id = cdl.clientdeliverinote_id
, customer cu, currency crr
, batch, client
    left outer join
      ( clientresident cr join ( departmentroom dr join department de on dr.department_id = de.department_id
      left outer join distributionpoint dpres on dr.distributionpoint_id=dpres.distributionpoint_id
      left outer join deliverypoint delpres on dpres.deliverypoint_id=delpres.deliverypoint_id )
                            on cr.departmentroom_id = dr.departmentroom_id
      ) on client.client_id = cr.client_id
    left outer join
      ( clientprivateperson cpp
      left outer join ( deliverypoint delvp join address on delvp.deliveryaddress_id = address.address_id )
                                  on cpp.deliverypoint_id = delvp.deliverypoint_id
      join distributionpoint dip on cpp.distributionpoint_id = dip.distributionpoint_id
      ) on client.client_id = cpp.client_id
, customerresidentialsettings crs, languages--, workstation ws
, reportparam rp
where cdn.clientdeliverynote_id = rp.number_value /*and
      (--coalesce(rp.string_value1, 'N') = 'N' or (rp.string_value1 = 'Y' and
       exists (select 1 from residentialitemscan ris where ris.clientdeliverynoteline_id = cdl.clientdeliverynoteline_id
       and ris.scanstation = rp.string_value and ris.uniqueresidentialitem_link_id = cds.uniqueresidentialitem_link_id
       and ris.transactiontype_id = 2))--)--only OUT scans*/
    and 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 cu.currency_id = crr.currency_id --and ws.code = rp.string_value
and cdl.qtycountedout <> 0

/
create or replace view V_CLIENTDELIVERY_SGS
 (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, 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
, (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
   left outer join (departmentroom dr
                     inner join (department de inner join customerresidentialsettings crs1 on de.customer_id = crs1.customer_id)
                     on dr.department_id = de.department_id) on client_link.departmentroom_id = dr.departmentroom_id
										 and de.customer_id = crs1.customer_id
										 and crs1.customerclients = 0
   left outer join (deliverypoint dpl inner join customerresidentialsettings crs2 on dpl.customer_id = crs2.customer_id)
	 on client_link.deliverypoint_link_id = dpl.deliverypoint_id
						and crs2.customerclients = 1
, 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 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_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_COLLECTACTIVITYBARCODE_POS
 (CUSTOMERID, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERPHONENUMBER, CUSTOMERCITY, CUSTOMEREMAIL, DEPARTMENTNUMBER, WEARERNUMBER, WEARERNAME, PRODUCTCODE, PRODUCTDESCRIPTION, SIZECODE, IDCODE, ISSUEDATE, LASTINSCANDATE, LASTOUTSCANDATE, REPAIROUT, RAGGEDDATE, RETURNEDTOSTOCKDATE, DELIVERYNOTENUMBER, LANGUAGECODE, LANGUAGE_ID, REPORTPARAM_ID)
as select coalesce( customer_uinp.customer_id, cust.customer_id) customerid,
       coalesce( customer_uinp.customernumber, cust.customernumber) customernumber,
       coalesce( customer_uinp.name, cust.name) customername,
       coalesce( customer_uinp.phoneno, cust.phoneno) customerphonenumber,
       coalesce((select a1.city from address a1 where a1.address_id = customer_uinp.visitaddress_id),(select a2.city from address a2 where a2.address_id = cust.visitaddress_id)) customercity,
       coalesce( customer_uinp.email, cust.email) customeremail,
       coalesce(dep_uinp.departmentnumber,d.departmentnumber) departmentnumber,
       coalesce( wearer_uinp.wearernumber,
                 w.wearernumber
                ) wearernumber,
       coalesce( wearer_uinp.fullname,
                 w.searchname) wearername,
       p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = p.product_id
           and pd.language_id = l.language_id) productdescription,
       sd.code sizecode,
       ui.primaryid idcode,
       (select uifi.lastissuedate
          from uniqueitemfixedinfo uifi
         where uifi.uniqueitem_id = ui.uniqueitem_id) issuedate,
       GETDATEONLY(ui.lastinscandate) lastinscandate,
       GETDATEONLY(ui.lastoutscandate) lastoutscandate,
       (select max(rh.repairdate)
          from repairhistory rh
         where rh.uniqueitem_link_id = ui.uniqueitem_id) repairout,
       null raggeddate,
       (select uifi.lastonstockdate
          from uniqueitemfixedinfo uifi
         where uifi.uniqueitem_id = ui.uniqueitem_id
          and ui.status_id <> (select st.status_id from status st where st.statustype = 'UI' and st.code = 20)) returnedtostockdate,
       (select max(pn.notenumber)
          from packingnote pn, deliveryscan ds
         where pn.packingnote_id = ds.packingnote_id
           and ds.uniqueitem_link_id = ui.uniqueitem_id
           and (ui.status_id = (select st.status_id from status st where st.statustype = 'UI' and st.code = 20) --in circulation
                and ui.stay_id = (select stay.stay_id from stay where stay.staytype = 4 and stay.staynr = 20) --at customer
               )
        ) deliverynotenumber,
       l.code languagecode,
       l.language_id,
       rp.reportparam_id
  from uniqueitem ui
         left outer join (uniqueitemnonpool uinp
                              join (weareremployment wemp_uinp
                                        join (distributionpoint dp_uinp
                                                 join(department dep_uinp
                                                          join customer customer_uinp on customer_uinp.customer_id = dep_uinp.customer_id)
                                                 on dep_uinp.department_id = dp_uinp.department_id)
                                        on dp_uinp.distributionpoint_id = wemp_uinp.distributionpoint_id)
                                        join wearer wearer_uinp
                                        on wemp_uinp.wearer_id = wearer_uinp.wearer_id
                              on uinp.weareremployment_id = wemp_uinp.weareremployment_id)
                     on ui.uniqueitem_id = uinp.uniqueitem_id
         left outer join (weareremployment wemp
                             join (distributionpoint dp
                                      join (department d
                                              join customer cust
                                              on cust.customer_id = d.customer_id)
                                      on d.department_id = dp.department_id)
                              on dp.distributionpoint_id = wemp.distributionpoint_id)
                            join wearer w
                            on w.wearer_id = wemp.wearer_id
                    on ui.lastweareremployment_link_id = wemp.weareremployment_id,
       product           p,
       sizedefinition    sd,
       languages         l,
        reportparam      rp
 where ui.product_id = p.product_id
   and ui.sizedefinition_id = sd.sizedefinition_id
   and (
                     (getdateonly(ui.lastinscandate) between rp.date_value1 and rp.date_value2
                                                       and (getdateonly(ui.lastinscandate) > getdateonly(ui.lastoutscandate) or getdateonly(ui.lastoutscandate) > rp.date_value2))
                      or
                      (getdateonly(ui.lastoutscandate) between rp.date_value1 and rp.date_value2
                                                       and (getdateonly(ui.lastinscandate)) < rp.date_value1)
   )
   and p.code between rp.string_value3 and rp.string_value4
union
select c.customer_id customerid,
       c.customernumber,
       c.name customername,
       c.phoneno customerphonenumber,
       (select a.city from address a where a.address_id = c.visitaddress_id) customercity,
       c.email customeremail,
       dep.departmentnumber departmentnumber,
       we.wearernumber wearernumber,
       we.fullname wearername,
       prd.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = prd.product_id
           and pd.language_id = l.language_id) productdescription,
       sd.code sizecode,
       ragi.primaryid idcode,
       ragi.lastissuedate issuedate,
       null lastinscandate,
       null lastoutscandate,
       (select max(rh.repairdate)
          from repairhistory rh
         where rh.uniqueitem_link_id = ragi.raggeditem_id) repairout,
       getdateonly(ragi.ragtimestamp) raggeddate,
       ragi.lastonstockdate returnedtostockdate,
       null deliverynotenumber,
       l.code languagecode,
       l.language_id,
       rp.reportparam_id
  from raggeditem  ragi left outer join (weareremployment wemp
                                                 join (distributionpoint dp
                                                        join (department dep
                                                                join customer c on c.customer_id = dep.customer_id
                                                             )
                                                        on dep.department_id = dp.department_id)
                                                 on wemp.distributionpoint_id = dp.distributionpoint_id)
                                          join wearer we
                                          on we.wearer_id = wemp.wearer_id
                                   on wemp.weareremployment_id = ragi.weareremployment_link_id,
       product          prd,
       sizedefinition   sd,
       languages        l,
        reportparam     rp
 where ragi.poolitem = 2
   and ragi.product_link_id = prd.product_id
   and ragi.sizedefinition_link_id = sd.sizedefinition_id
   and getdateonly(ragi.ragtimestamp) between rp.date_value1 and rp.date_value2
   and prd.code between rp.string_value3 and rp.string_value4

/
create or replace view V_COLLECTACTIVITYDELNOTE_POS
 (PRODUCT_CODE, FROMSTOCK, PACKINGNOTE_ID, PACKINGNOTENUMBER, PACKINGNOTEDELIVERYDATE, PRIMARYID, CUSTOMERID, DEPARTMENTNUMBER, WEARERNUMBER, WEARERNAME, LANGUAGECODE, REPORTPARAM_ID)
as SELECT --+index(ds XIF11DELIVERYSCAN) index(ri_link XSPEEDUNIQUEITEM_LINK) index(w_link XPKWEAREREMPLOYMENT_LINK) index(s XPKSIZEDEFINITION_LINK)
       p.code product_code,
       ds.fromstock, ds.packingnote_id,
       pn.notenumber packingnotenumber,
       pn.deliverydate packingnotedeliverydate,
       ri.primaryid,
       cl.customer_id customerid,
       d.departmentnumber,
       w_link.wearernumber, w_link.wearername,
       l.code languagecode, rp.reportparam_id
  FROM deliveryscan ds
       LEFT OUTER JOIN weareremployment_link w_link on w_link.weareremployment_link_id = ds.weareremployment_link_id,
       product p,
       packingnote pn, customer_link cl, department d, distributionpoint dp, uniqueitem_link ri_link, raggeditem ri, languages l, reportparam rp
 WHERE p.product_id = ds.product_link_id and
       ri_link.uniqueitem_link_id = ds.uniqueitem_link_id AND
       ri.raggeditem_id = ri_link.raggeditem_id and
       cl.customer_id = d.customer_id and
       d.department_id = dp.department_id and
       dp.distributionpoint_id = pn.distributionpoint_id and
       pn.packingnote_id = ds.packingnote_id and
       pn.status_id = (select status.status_id from status where status.code = 30 and status.statustype = 'PN')
       and pn.deliverydate between rp.date_value1 and rp.date_value2
UNION ALL-- UNIQUE ITEMS
SELECT --+index(ds XIF11DELIVERYSCAN)  index(w_link XPKWEAREREMPLOYMENT_LINK)  index(s XPKSIZEDEFINITION_LINK)
       p.code product_code,
       ds.fromstock, ds.packingnote_id,
       pn.notenumber packingnotenumber,
       pn.deliverydate packingnotedeliverydate,
       ui.primaryid,
       cl.customer_id customerid,
       d.departmentnumber,
       w_link.wearernumber, w_link.wearername,
       l.code languagecode, rp.reportparam_id
  FROM deliveryscan ds
       LEFT OUTER JOIN weareremployment_link w_link on w_link.weareremployment_link_id = ds.weareremployment_link_id,
       product p,
       packingnote pn, customer_link cl, department d, distributionpoint dp, uniqueitem_link ui_link, uniqueitem ui, languages l, reportparam rp
 WHERE p.product_id = ds.product_link_id and
       ui_link.uniqueitem_link_id = ds.uniqueitem_link_id and
       ui.uniqueitem_id = ui_link.uniqueitem_id and
       cl.customer_id = d.customer_id and
       d.department_id = dp.department_id and
       dp.distributionpoint_id = pn.distributionpoint_id and
       pn.packingnote_id = ds.packingnote_id and
       pn.status_id = (select status.status_id from status where status.code = 30 and status.statustype = 'PN')
       and pn.deliverydate between rp.date_value1 and rp.date_value2
       and d.departmentnumber between rp.number_value3 and rp.number_value4
       and w_link.wearernumber between rp.number_value5 and rp.number_value6
       and p.code between rp.string_value3 and rp.string_value4
union all -- return to stock from raggeditem
SELECT --+index(o XIE3OUTOFCIRCULATIONHISTORY)  index(ri_link XSPEEDUNIQUEITEM_LINK)  index(p XIF311PRODUCT_LINK)  index(w_link XPKWEAREREMPLOYMENT_LINK)
       distinct p.code product_code,
       'Z' fromstock, o.packingnote_id,
       pn.notenumber packingnotenumber,
       pn.deliverydate packingnotedeliverydate,
       ri.primaryid,
       cl.customer_id customerid,
       d.departmentnumber,
       w_link.wearernumber, w_link.wearername,
       l.code languagecode, rp.reportparam_id
  FROM outofcirculationhistory o
       LEFT OUTER JOIN weareremployment_link w_link on w_link.weareremployment_link_id = o.weareremployment_link_id,
       product p, packingnote pn, customer_link cl, department d, distributionpoint dp,
       uniqueitem_link ri_link, raggeditem ri, languages l, reportparam rp
 WHERE p.product_id = o.product_link_id and
       ri_link.uniqueitem_link_id = o.uniqueitem_link_id AND
       ri.raggeditem_id = ri_link.raggeditem_id and
       cl.customer_id = d.customer_id and
       d.department_id = dp.department_id and
       dp.distributionpoint_id = pn.distributionpoint_id and
       pn.packingnote_id = o.packingnote_id and
       pn.status_id = (select status.status_id from status where status.code = 30 and status.statustype = 'PN')
       and pn.deliverydate between rp.date_value1 and rp.date_value2
       and d.departmentnumber between rp.number_value3 and rp.number_value4
       and w_link.wearernumber between rp.number_value5 and rp.number_value6
       and p.code between rp.string_value3 and rp.string_value4
union all -- return to stock from uniqueitem
SELECT --+index(o XIE3OUTOFCIRCULATIONHISTORY)  index(w_link XPKWEAREREMPLOYMENT_LINK) index_rs(we XPKWEAREREMPLOYMENT)
       distinct p.code product_code,
       'Z' fromstock, o.packingnote_id,
       pn.notenumber packingnotenumber,
       pn.deliverydate packingnotedeliverydate,
       ui.primaryid,
       cl.customer_id customerid,
       d.departmentnumber,
       w_link.wearernumber, w_link.wearername,
       l.code languagecode, rp.reportparam_id
  FROM outofcirculationhistory o
       LEFT OUTER JOIN weareremployment_link w_link on w_link.weareremployment_link_id = o.weareremployment_link_id,
       product p, packingnote pn, customer_link cl, department d, distributionpoint dp,
       uniqueitem_link ui_link, uniqueitem ui, languages l, reportparam rp
 WHERE p.product_id = o.product_link_id and
       ui_link.uniqueitem_link_id = o.uniqueitem_link_id and
       ui.uniqueitem_id = ui_link.uniqueitem_id and
       cl.customer_id = d.customer_id and
       d.department_id = dp.department_id and
       dp.distributionpoint_id = pn.distributionpoint_id and
       pn.packingnote_id = o.packingnote_id and
       o.ragreason_id is null and
       pn.status_id = (select status.status_id from status where status.code = 30 and status.statustype = 'PN')
       and pn.deliverydate between rp.date_value1 and rp.date_value2
       and d.departmentnumber between rp.number_value3 and rp.number_value4
       and w_link.wearernumber between rp.number_value5 and rp.number_value6
       and p.code between rp.string_value3 and rp.string_value4

/
create or replace view V_COLLECTACTIVITYSCANS_POS
 (CUSTOMER_ID, CUSTOMERNUMBER, DATEACTIVE, DATEINACTIVE, DEBTORNUMBER, MASTERACCOUNT, MASTERACCOUNTNUMBER, CUSTOMERNAME, EMAIL, DEPARTMENTNUMBER, DEPARTMENTDESC, CITY, PHONENO, FAXNO, PRODUCTCODE, PRODUCTDESCRIPTION, TRANSACTIONTYPE, SCANDATE, SCANDATETRUNC, LANGUAGECODE, BUSINESSUNIT_ID, PRIMARYID, WEARERNUMBER, WEARERNAME, EXISTSREPAIRHISTORY, REPORTPARAM_ID)
as select cu.customer_id, cu.customernumber, cu.dateactive, cu.dateinactive,
       (select deb.customernumber from customer deb where deb.customer_id = cu.debtor_id) debtornumber,
       cu.masteraccount,
       (select macc.customernumber from customer macc where macc.customer_id = cu.masteraccount_id) masteraccountnumber,
       cu.name customername, cu.email,
       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,
       scan.scantimestamp scandatetrunc, languages.code languagecode,
       scan.businessunit_id, scan.primaryid, we.wearernumber, we.wearername,
       (select max(rh.repairhistory_id) from repairhistory rh where rh.uniqueitem_link_id = scan.uniqueitem_link_id and getdateonly(rh.repairdate) = getdateonly(scan.scantimestamp) and rh.repairtype_id <> 63) existsrepairhistory,
       rp.reportparam_id
from   customer cu, 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 (getdateonly(scan.scantimestamp) between rp.date_value1 and rp.date_value2)
      and (we.wearernumber between rp.number_value5 and rp.number_value6)
      and (prd.code between rp.string_value3 and rp.string_value4)

/
create or replace view V_COLLECTIONACTIVITYSTATUS_POS
 (COLLECTDATE, INSCANDATE, CUSTOMER_ID, PRODUCT_ID, SIZEDEFINITION_ID, CODE, CUSTOMERNUMBER, CUSTOMERNAME, STREET, ZIPCODE, CITY, PRODUCTCODE, SIZECODE, WEARERNR, PROD_DESCR, INSCANNED, REPAIRSOUT, REPAIRSIN, ISSUES, CANCELS, RAGS, DEPARTMENTNUMBER, REPORTPARAM_ID)
as select rc.drivingdate collectdate, sysdate inscandate,
cu.customer_id, p.product_id, sd.sizedefinition_id,
bu.code, cu.customernumber, cu.name customername, a.street, a.zipcode, a.city,
p.code productcode, sd.code sizecode, w.wearernumber wearernr,
(select pd.description from product_desc pd where p.product_id=pd.product_id and pd.language_id = cu.language_id) prod_descr,
/*(select count(ds.uniqueitem_link_id) from deliveryscan ds
        where ds.businessunit_id = bu.businessunit_id and ds.customer_link_id = cu.customer_id
        and ds.product_link_id = p.product_id and ds.sizedefinition_link_id = sd.sizedefinition_id
        and ds.weareremployment_link_id = we.weareremployment_id
        and trunc(ds.scantimestamp) between rp.date_value1 and rp.date_value2+1)*/--As made by WBO
(select count(s3.primaryid) from scan s3 where s3.transactiontype_id in (2, 540, 640)
        and s3.businessunit_id = bu.businessunit_id and s3.customer_link_id = cu.customer_id
        and s3.product_link_id = p.product_id and s3.sizedefinition_link_id = sd.sizedefinition_id
        and s3.weareremployment_link_id = we.weareremployment_id
        and trunc(s3.scantimestamp) between rp.date_value1 and rp.date_value2+1) --based on Johanna
        inscanned,--in ABS is saved as OutScan
(select count(rh.uniqueitem_link_id) from repairhistory rh, uniqueitem u
        where u.uniqueitem_id = rh.uniqueitem_link_id and rh.repairtype_id = 63
        and rh.businessunit_id = bu.businessunit_id and rh.customer_link_id = cu.customer_id
        and rh.product_link_id = p.product_id and u.sizedefinition_id = sd.sizedefinition_id
        and rh.weareremployment_link_id = we.weareremployment_id
        and rh.repairdate between rp.date_value1 and rp.date_value2+1) repairsOUT,
(select count(rh.uniqueitem_link_id) from repairhistory rh, uniqueitem u
        where u.uniqueitem_id = rh.uniqueitem_link_id and rh.repairtype_id <> 63
        and rh.businessunit_id = bu.businessunit_id and rh.customer_link_id = cu.customer_id
        and rh.product_link_id = p.product_id and u.sizedefinition_id = sd.sizedefinition_id
        and rh.weareremployment_link_id = we.weareremployment_id
        and rh.repairdate between rp.date_value1 and rp.date_value2+1) repairsIN,
(select count (ih.uniqueitem_link_id) from issuehistory ih
        where ih.processbusinessunit_id = bu.businessunit_id and ih.customer_link_id = cu.customer_id
        and ih.product_link_id = p.product_id and ih.sizedefinition_link_id = sd.sizedefinition_id
        and ih.weareremployment_link_id = we.weareremployment_id
        and trunc(ih.assigndate) between rp.date_value1 and rp.date_value2+1) issues,
(select count(s1.primaryid) from scan s1 where s1.transactiontype_id = 15
        and s1.businessunit_id = bu.businessunit_id and s1.customer_link_id = cu.customer_id
        and s1.product_link_id = p.product_id and s1.sizedefinition_link_id = sd.sizedefinition_id
        and s1.weareremployment_link_id = we.weareremployment_id
        and trunc(s1.scantimestamp) between rp.date_value1 and rp.date_value2+1) cancels,
(select count(s2.primaryid) from scan s2 where s2.transactiontype_id in (42, 43)
        and s2.businessunit_id = bu.businessunit_id and s2.customer_link_id = cu.customer_id
        and s2.product_link_id = p.product_id and s2.sizedefinition_link_id = sd.sizedefinition_id
        and s2.weareremployment_link_id = we.weareremployment_id
        and trunc(s2.scantimestamp) between rp.date_value1 and rp.date_value2+1) rags,
( select dep.departmentnumber
         from   department dep
         where  dep.department_id = (select dp.department_id
                                     from   distributionpoint dp
                                     where  dp.distributionpoint_id = we.distributionpoint_id)) departmentnumber
, rp.reportparam_id
from businessunit bu, customer cu, product p, sizedefinition sd
, wearerinventory wi, weareremployment we, wearer w, address a
, routecontrol rc, stop st
, reportparam rp
where cu.defaultbusinessunit_id = bu.businessunit_id
and cu.customer_id = w.customer_id
and w.wearer_id = we.wearer_id
and we.weareremployment_id = wi.weareremployment_id
and wi.product_id = p.product_id
and wi.sizedefinition_id = sd.sizedefinition_id
and cu.mailaddress_id = a.address_id
and cu.customer_id = st.customer_link_id and st.routecontrol_id = rc.routecontrol_id
and rc.drivingdate between rp.date_value1 and rp.date_value2+1
and rp.number_value = cu.customernumber

/
create or replace view V_COLLECTIONACTIVITY_POS
 (CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMER_DATEACTIVE, CUSTOMER_DATEINACTIVE, CUSTOMER_CITY, CUSTOMER_PHONENO, CUSTOMER_EMAIL, CHAINCODE, SYSTEMUSER_ID, USERGROUP_ID, LANGUAGECODE, BUSINESSUNIT_ID, REPORTPARAM_ID)
as select cu.customer_id,
       cu.customernumber,
       cu.name customername,
       cu.dateactive customer_dateactive,
       cu.dateinactive customer_dateinactive,
       (select a.city from address a where a.address_id = cu.visitaddress_id) customer_city,
       cu.phoneno customer_phoneno,
       cu.email customer_email,
       c.code chaincode,
       su.systemuser_id,
       ug.usergroup_id,
       languages.code languagecode,
       bu.businessunit_id,
       rp.reportparam_id
  from customer cu left outer join chain c on cu.chain_id = c.chain_id,
       languages,
       businessunitsperusergroup buperug,
       businessunit bu,
       usergroup    ug,
       systemuser su,
       reportparam rp
 where cu.defaultbusinessunit_id = bu.businessunit_id
   and buperug.businessunit_id = bu.businessunit_id
   and buperug.usergroup_id = ug.usergroup_id
   and ug.usergroup_id = su.usergroup_id
   and cu.customernumber between rp.number_value1 and rp.number_value2
   and (cu.dateactive <= rp.date_value2 and cu.dateinactive > rp.date_value1)
   and (c.code between rp.string_value1 and rp.string_value2)

/
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_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_BDE
 (PACKINGNOTE_ID, NOTENUMBER, DELIVERYDATE, PRODUCTIONDATE, REMARK, ORIGIN, STOPNUMBER, ROUTE_ID, CORRECTEDNOTENUMBER, CONSIGNMENTNOTE_ID, YEAR, WEEK, DAYNUMBER, TOTALAMOUNT, TOTALAMOUNTEXCLUDINGVAT, PROCESSBU_CODE, PROCESSBU_DESC, PROCESSBU_PHONE, PROCESSBU_FAX, CONTACTPERSON_NAME, 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
, PROCESSBU.Code PROCESSBU_code, PROCESSBU.Description PROCESSBU_desc
, PLANT.Phoneno PROCESSBU_phone, PLANT.Faxno PROCESSBU_fax
, (select max(emp.name) from employee emp where exists (select * from customer cust where cust.defaultbusinessunit_id = PROCESSBU.businessunit_id and cust.serviceemployee_id = emp.employee_id)) ContactPerson_name
, 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)/100 vat
from PACKINGNOTE H, STATUS, businessunit PROCESSBU, PLant, packingnoteline l
where H.STATUS_ID = STATUS.STATUS_ID
      AND H.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
      AND PLant.Plant_Id = PROCESSBU.Plant_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
, PROCESSBU.Code PROCESSBU_code, PROCESSBU.Description PROCESSBU_desc
, PLANT.Phoneno PROCESSBU_phone, PLANT.Faxno PROCESSBU_fax
, (select max(emp.name) from employee emp where exists (select * from customer cust where cust.defaultbusinessunit_id = PROCESSBU.businessunit_id and cust.serviceemployee_id = emp.employee_id)) ContactPerson_name
, 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)/100 vat
from PACKINGNOTE H, STATUS, businessunit PROCESSBU, PLant, packingnotecontainer c
where H.STATUS_ID = STATUS.STATUS_ID
      AND H.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
      AND PLant.Plant_Id = PROCESSBU.Plant_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_COMPRESSEDDELIVERYNOTE_NLI
 (PACKINGNOTE_ID, NOTENUMBER, DELIVERYDATE, PRODUCTIONDATE, REMARK, ORIGIN, STOPNUMBER, ROUTE_ID, CORRECTEDNOTENUMBER, CONSIGNMENTNOTE_ID, YEAR, WEEK, DAYNUMBER, TOTALAMOUNT, TOTALAMOUNTEXCLUDINGVAT, INVOICEHEADER_ID, AMOUNT, DISCOUNTPERCENTAGE, VAT)
as select h.packingnote_id, cast (h.notenumber as varchar2(60)) notenumber, h.deliverydate, h.productiondate,CAST(H.remark AS VARCHAR2(60))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.deliveredamount*coalesce((select max(il.price)
             from invoicelineproduct ilp, invoiceline il
            where il.invoiceheader_id = ih.invoiceheader_id
              and il.invoiceline_id = ilp.invoiceline_id
              and ilp.product_link_id = l.product_id
              and ilp.finishingmethod_id = l.finishingmethod_id
              and il.invoicelinetype_id = 2
              and (ilp.sizedefinition_link_id = l.sizedefinition_id or
                  ilp.sizedefinition_link_id =
                  (select sizedefinition.sizedefinition_id
                      from sizedefinition
                     where sizedefinition.code = '*')))
             , l.price
             , pack_price.Wash_Price(ih.deltocustomer_link_id, l.product_id, l.sizedefinition_id, l.finishingmethod_id, ih.invoicedate)) amount,
                           (select min(il.discountpercentage)
          from invoicelineproduct ilp, invoiceline il
         where il.invoiceheader_id = ih.invoiceheader_id
           and il.invoiceline_id = ilp.invoiceline_id
           and ilp.product_link_id = l.product_id
           and ilp.finishingmethod_id = l.finishingmethod_id
           and il.invoicelinetype_id = 2
           and (ilp.sizedefinition_link_id = l.sizedefinition_id or
               ilp.sizedefinition_link_id =
               (select sizedefinition.sizedefinition_id
                   from sizedefinition
                  where sizedefinition.code = '*'))) discountpercentage
, 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 join invoiceheader ih on ih.invoiceheader_id=l.invoiceheader_id
where H.STATUS_ID = STATUS.STATUS_ID
      AND (STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20))
      and l.packingnote_id=h.packingnote_id
union all
select h.packingnote_id, cast (h.notenumber as varchar2(60)) notenumber, h.deliverydate, h.productiondate,CAST(H.remark AS VARCHAR2(60))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,
       l.deliveredamount*coalesce((select max(il.price)
             from invoicelineproduct ilp, invoiceline il
            where il.invoiceheader_id = ih.invoiceheader_id
              and il.invoiceline_id = ilp.invoiceline_id
              and ilp.product_link_id = l.product_id
              and ilp.finishingmethod_id = l.finishingmethod_id
              and il.invoicelinetype_id = 2
              and (ilp.sizedefinition_link_id = l.sizedefinition_id or
                  ilp.sizedefinition_link_id =
                  (select sizedefinition.sizedefinition_id
                      from sizedefinition
                     where sizedefinition.code = '*')))
             , l.price
             , pack_price.Wash_Price(ih.deltocustomer_link_id, l.product_id, l.sizedefinition_id, l.finishingmethod_id, ih.invoicedate)) amount,
                           (select min(il.discountpercentage)
          from invoicelineproduct ilp, invoiceline il
         where il.invoiceheader_id = ih.invoiceheader_id
           and il.invoiceline_id = ilp.invoiceline_id
           and ilp.product_link_id = l.product_id
           and ilp.finishingmethod_id = l.finishingmethod_id
           and il.invoicelinetype_id = 2
           and (ilp.sizedefinition_link_id = l.sizedefinition_id or
               ilp.sizedefinition_link_id =
               (select sizedefinition.sizedefinition_id
                   from sizedefinition
                  where sizedefinition.code = '*'))) discountpercentage
, coalesce((select pnt.taxpercentage from packingnotetax pnt where c.packingnote_id = pnt.packingnote_id and c.taxgroupcode = pnt.taxgroupcode), 0) vat
from PACKINGNOTE H join packingnoteline l on h.packingnote_id=l.packingnote_id, STATUS, packingnotecontainer c join invoiceheader ih on ih.invoiceheader_id=c.invoiceheader_id
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_COMPRESSEDDELNOTE_INV_BDE
 (INVOICEHEADER_ID, INVOICEDATE, INVOICENUMBER, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOSTATE, DELTOCITY, DELTOZIPCODE, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, STREET, STREET2, HOUSENUMBER, HOUSENUMBEREXT, 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, NEXTPERIODSTARTDATE, INVOICEFREQUENCYNUMBER, PARENTINVOICEHEADER_ID, INVOICELAYOUTCODE
, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, INV_BU_CODE, INV_BU_DESC)
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.HOUSENUMBER, H.HOUSENUMBEREXT, 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
, h.nextperiodstartdate, h.invoicefrequency_id invoicefrequencynumber, h.parentinvoiceheader_id
, ihe.formlayoutcode INVOICELAYOUTCODE, ihe.billtocountrydescription, ihe.deltocountrydescription
, ibu.code Inv_bu_code, ibu.description Inv_bu_desc
FROM INVOICEHEADER H, currency c, businessunit ibu, invoiceheaderextrainfo ihe
where h.currency_id = c.currency_id and h.invoicebusinessunit_id = ibu.businessunit_id
      and ihe.invoiceheader_id = h.invoiceheader_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)
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
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

/
create or replace view V_CONDENSEDCOSTREPORT_BDE
 (INVOICEHEADER_ID, INVOICENUMBER, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, CITY, ZIPCODE, STREET, CONTACTPERSONNAME, INVOICECOMMENTS, NEXTPERIODSTARTDATE, INVOICEFREQUENCYNUMBER, PARENTINVOICEHEADER_ID, INVOICELAYOUTCODE, COSTCENTER_CODE, COSTCENTER_DESCRIPTION, COSTCENTERINVOICELINE_AMOUNT, TAXGROUPCODE, PERCENTAGE, AMOUNT_VAT, AMOUNT_GROSS, CURRENCYCODE, INVOICEAMOUNTDECIMALS, LANGUAGECODE
, INV_BU_CODE)
as select
  ih.invoiceheader_id, ih.invoicenumber, 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 invoicefrequencynumber, ih.parentinvoiceheader_id
, (select ihe.formlayoutcode from invoiceheaderextrainfo ihe where ihe.invoiceheader_id=ih.invoiceheader_id) INVOICELAYOUTCODE
, cclk.code costcenter_code, cclk.description costcenter_description
, sum(ccil.amount) costcenterinvoiceline_amount
, coalesce(il.taxgroupcode, ' ') taxgroupcode
, coalesce(ilv.percentage  , 0) percentage
, ( sum(ccil.amount) * coalesce(ilv.percentage  , 0))/100 Amount_VAT
, ( sum(ccil.amount) + ( sum(ccil.amount)*coalesce(ilv.percentage  , 0))/100 ) Amount_Gross
, currency.code currencycode, currency.invoiceamountdecimals
, languages.code languageCode
, (select ibu.code from businessunit ibu where ih.invoicebusinessunit_id = ibu.businessunit_id) Inv_bu_code
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.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, ih.parentinvoiceheader_id, ih.invoicebusinessunit_id
, cclk.code , cclk.description
, il.taxgroupcode, ilv.percentage
, currency.code , currency.invoiceamountdecimals
, languages.code

/
create or replace view V_CONDENSEDCOSTREPORT_SMG
 (INVOICEHEADER_ID, INVOICENUMBER, ACTIVITYREFERENCE, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, DELTOCUSTVATNR, CITY, ZIPCODE, STREET, CONTACTPERSONNAME, COSTCENTER_CODE, COSTCENTER_DESCRIPTION, COSTCENTERINVOICELINE_AMOUNT, TAXGROUPCODE, PERCENTAGE, AMOUNT_VAT, AMOUNT_GROSS, CURRENCYCODE, INVOICEAMOUNTDECIMALS, PRINTTAXONAPPENDIX, LANGUAGECODE, EXTRANAME1, EXTRANAME2, BILLTOCOUNTRYDESCRIPTION
, PLANTCOUNTRYDESCRIPTION, BILLTOSENDINVOICETO, CUSTTYPE, PARENTINVOICEHEADER_ID, BILLTOCUSTOMER_LINK_ID, BILTOCUSTVATNR, LEGALENTITY_LEGALNAME, LEGALENTITY_ID, PLANT_STREET, PLANT_STREET2, PLANT_ZIPCODE, PLANT_CITY, PLANT_STATE, PLANT_PHONENO, PLANT_FAXNO, PLANT_WEBSITE, PLANT_EMAIL)
as select ih.invoiceheader_id
, coalesce((select ihp.invoicenumber from invoiceheader ihp where ihp.invoiceheader_id = ih.parentinvoiceheader_id), ih.invoicenumber) invoicenumber
, ih.activityreference, ih.startweek, ih.endweek, ih.startmonth, ih.endmonth
, ih.billtocustomernumber, ih.billtocustomername, ih.deltocustomernumber, ih.deltocustomername,
( select c.vatnumber from customer c where c.customernumber=ih.deltocustomernumber) deltocustvatnr
, ih.city, ih.zipcode, ih.street, ih.contactpersonname
, cclk.code costcenter_code, cclk.description costcenter_description
, sum(ccil.amount) costcenterinvoiceline_amount
, coalesce(il.taxgroupcode, ' ') taxgroupcode
, coalesce(ilv.percentage, 0) percentage
, ( sum(ccil.amount) * coalesce(ilv.percentage, 0))/100 Amount_VAT
, ( sum(ccil.amount) + ( sum(ccil.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
, ih.extraname1, ih.extraname2
, (select ihextr.billtocountrydescription from invoiceheaderextrainfo ihextr where ihextr.invoiceheader_id = ih.invoiceheader_id) billtocountrydescription
, (select co.description from businessunit bu, plant pl, country co
  where ih.invoicebusinessunit_id = bu.businessunit_id and bu.plant_id = pl.plant_id and pl.country_id = co.country_id) PLANTCOUNTRYDESCRIPTION
, (select c.sendinvoiceto from customer c where ih.deltocustomer_link_id = c.customer_id) billtosendinvoiceto
, F_GetCustType_smg(ih.invoiceheader_id) custtype
, ih.parentinvoiceheader_id, ih.billtocustomer_link_id
, (select deb.vatnumber from customer deb where deb.customer_id=ih.billtocustomer_link_id) biltocustvatnr
, (select le.legalname from legalentity le where le.legalentity_id = e.legalentity_id) LegalEntity_LegalName
, (select le.legalentity_id from legalentity le where le.legalentity_id = e.legalentity_id) LegalEntity_ID
, pad.street plant_street, pad.street2 plant_street2, pad.zipcode plant_zipcode, pad.city plant_city
, pad.state plant_state, p.phoneno plant_phoneno, p.faxno plant_faxno, p.website plant_website, p.email plant_email
from
  invoiceheader ih, businessunit e, plant p, address pad
, 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
and ih.invoicebusinessunit_id = e.businessunit_id
and e.plant_id = p.plant_id
and pad.address_id = p.address_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.extraname1, ih.extraname2, ih.invoicebusinessunit_id
, ih.parentinvoiceheader_id, e.legalentity_id
, pad.street, pad.street2, pad.zipcode, pad.city, pad.state, p.phoneno, p.faxno, p.website, p.email

/
create or replace view V_CONDENSEDCOSTREPORT_SNG
 (BILLTOCOUNTRYDESCRIPTION, PAYMENTTERMS_DESC, DELTOCUSTVATNUMBER, CONTACTPERSONNAME, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, ENDWEEK, ENDDATE, STARTWEEK, STARTDATE, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, CITY, ZIPCODE, STREET, DELTOSTREET, DELTOZIPCODE, DELTOCUSTOMERNAME, DELTOCUSTOMERNUMBER, DELTOCITY, HOUSENUMBER, HOUSENUMBEREXT, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL
, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, INVOICECOMMENTS, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, PREBILLAMOUNT, PURCHASEORDER, CURRENCYCODE, INVOICEAMOUNTDECIMALS, DECIMALS, COLLECTIONRESPEMPLOYEE, BILLTOLEGALNAME, INVOICEDATE, INVOICENUMBER, LINENUMBER, PARENTINVOICEHEADER_ID, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT
, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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)
as select ihtr.billtocountrydescription,
			 ihtr.paymenttermsdescription paymentterms_desc,
			 ihtr.deltocustvatnumber,
			 f.contactpersonname,
			 (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 = f.DELTOCUSTOMER_LINK_ID)) GENERALINV_REMARK_CUSTOMER,
       f.endweek, f.enddate, f.startweek, f.startdate,
       f.billtocustomernumber, f.billtocustomername, f.city, f.zipcode, f.street,
			 f.deltostreet, f.deltozipcode, f.deltocustomername, f.deltocustomernumber, f.deltocity,
			 f.housenumber, f.housenumberext,
			 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,
			 f.nextperiodstartdate, f.nextperiodenddate, f.nextperiodstartweek, f.nextperiodendweek,
			 f.invoicecomments, p.invoiceremarkstartdate, p.invoiceremarkenddate,
			 f.prebillamount, f.purchaseorder,
			 crr.code currencycode, crr.invoiceamountdecimals, crr.decimals,
			 (select empl.name from customerbillinginfo cbi, employee empl
          where cbi.customer_id = f.billtocustomer_link_id
                and empl.employee_id = cbi.collectionresponsible_id) collectionRespEmployee
       , (select bc.legalname from customer bc where f.billtocustomer_link_id = bc.customer_id) BillToLegalName,
       f.invoicedate, f.invoicenumber, a.linenumber, ih.parentinvoiceheader_id,
       (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.adjustmentpermited, 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
from   invoiceheader ih,
       invoiceheader f,
			 invoiceline a, costcenterinvoiceline ccil --left outer join costcenterinvoiceline ccil on ccil.invoiceline_id = a.invoiceline_id
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, businessunit bu, plant p, address x, currency crr, invoiceheaderextrainfo ihtr
where  a.invoiceheader_id = f.invoiceheader_id
       and f.invoicebusinessunit_id = bu.businessunit_id
			 and f.currency_id = crr.currency_id
			 and bu.plant_id = p.plant_id
			 and p.address_id = x.address_id
			 and ihtr.invoiceheader_id = f.invoiceheader_id
and    f.parentinvoiceheader_id = ih.invoiceheader_id
and    f.documenttype = 1
and languages.language_id = (select cu.language_id from customer cu where cu.customer_id = ih.billtocustomer_link_id)
and    ccil.invoiceline_id = a.invoiceline_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_CONDENSEDINVOICESREPORT_LTS
 (BILLNUMBER, BILLNAME, BILLCUSTOMER_ID, BILLEXTRANAME1, BILLTOCOUNTRYDESC, CONTACTPERSONNAME, STREET, HOUSENUMBER, ZIPCODE, CITY, STATE, DELLNUMBER, DELLNAME, INVOICENUMBER, INVOICEDATE, INVOICESTARTPERIOD, INVOICEENDPERIOD, TOTALAMOUNTEXCLVAT, PREBILLAMOUNT, CURRENCYCODE, INVOICEAMOUNTDECIMALS, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, IHC_BILLTO_PAYMENTTERM_DESC, IHC_BILLTO_PAYMENTTYPE
)
as select
  bill.customernumber BillNumber, bill.legalname BillName, bill.customer_id BillCustomer_id
, bill.extraname1 BillExtraname1
, (select c.description from country c where c.country_id = bill.country_id) BillToCountryDesc
, ( 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
, billaddr.street, billaddr.housenumber, billaddr.zipcode, billaddr.city, billaddr.state
, coalesce(del.customernumber, bill.customernumber ) DellNumber
, coalesce(del.legalname, bill.legalname) DellName
, ih.invoicenumber , ih.invoicedate
, coalesce((select invoiceheader.startdate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0 ), -- 0 means Direct invoice in invoicefrequency table
            (select invoiceheader.invoicedate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id = 0 ) ) InvoiceStartPeriod
, coalesce((select invoiceheader.enddate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0  ),
            (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber < ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 ),
             (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber = ih.invoicenumber -- this is for the first record when invoiceheader.invoicenumber = ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceEndPeriod
, ih.totalamountexclvat, ih.prebillamount, currency.code currencyCode, currency.invoiceamountdecimals
--, ih.purchaseorder PurchaseOrderNumber
--, (select cc.code from customercluster cc where cc.cluster_id = ih.cluster_id) cust_cluster_code
, p.name plantname, p.website plantwebsite, p.email plantemail
, x.street plantstreet,x.street2 plantstreet2, x.zipcode plantzipcode
, x.city plantcity, x.state plantstate, x.county plantcounty, p.phoneno plantphone
, p.faxno plantfax
, (select ptd.description
           from paymentterms_desc ptd
           where cbi.paymentterms_id = ptd.paymentterms_id
                 and ptd.language_id = bill.language_id
  ) ihc_billto_paymentterm_desc
, (select pt.paymenttermtype
           from paymentterms pt
           where cbi.paymentterms_id = pt.paymentterms_id
  ) ihc_billto_paymenttype
from
  invoiceheader ih left outer join customer del on del.customer_id = ih.deltocustomer_link_id
, customer bill, status, customerbillinginfo cbi, address billaddr, currency, address x
, plant p--, businessunit bu
where
    ih.billtocustomer_link_id = bill.customer_id
and cbi.customer_id = bill.customer_id
and ih.status_id = status.status_id
and status.statustype = 'IN'
and status.code = '2'
and (ih.parentinvoiceheader_id is null or ih.invoiceheader_id = ih.parentinvoiceheader_id)
and billaddr.address_id = bill.mailaddress_id
and ih.currency_id = currency.currency_id
--and ih.invoicebusinessunit_id = bu.businessunit_id
--and bu.plant_id = p.plant_id
and p.code = '07'
and p.address_id = x.address_id

/
create or replace view V_CONDENSEDINVOICESREPORT_SMG
 (BILLNUMBER, BILLNAME, VATNUMBER, CONTACTPERSONNAME, STREET, ZIPCODE, CITY, STATE, DELLNUMBER, DELLNAME, INVOICENUMBER, INVOICEDATE, INVOICESTARTPERIOD, INVOICEENDPERIOD, TOTALAMOUNTEXCLVAT, PREBILLAMOUNT, CURRENCYCODE, INVOICEAMOUNTDECIMALS, PURCHASEORDERNUMBER, CUST_CLUSTER_CODE, EXTRANAME1, EXTRANAME2, SPLITUPDESCRIPTION, BILLTOCOUNTRYDESCRIPTION, PLANTCOUNTRYDESCRIPTION)
as select
  bill.customernumber BillNumber, bill.legalname BillName,  bill.vatnumber
, ( 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
, address.street, address.zipcode, address.city, address.state
, coalesce(del.customernumber, bill.customernumber ) DellNumber
, coalesce(del.legalname, bill.legalname) DellName
, ih.invoicenumber , ih.invoicedate
, coalesce((select invoiceheader.startdate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0 ), -- 0 means Direct invoice in invoicefrequency table
            (select invoiceheader.invoicedate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id = 0 ) ) InvoiceStartPeriod
, coalesce((select invoiceheader.enddate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0  ),
            (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber < ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 ),
             (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber = ih.invoicenumber -- this is for the first record when invoiceheader.invoicenumber = ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceEndPeriod
, coalesce(ihc.totalamountexclvat, ih.totalamountexclvat) totalamountexclvat, coalesce(ihc.prebillamount, ih.prebillamount) prebillamount
, coalesce(icu.code, currency.code) currencyCode, coalesce(icu.invoiceamountdecimals, currency.invoiceamountdecimals) invoiceamountdecimals
, ih.purchaseorder PurchaseOrderNumber
, (select cc.code from customercluster cc where cc.cluster_id = ih.cluster_id) cust_cluster_code
, ih.extraname1, ih.extraname2, ih.splitupdescription
, (select ihextr.billtocountrydescription from invoiceheaderextrainfo ihextr where ihextr.invoiceheader_id = ih.invoiceheader_id) billtocountrydescription
, (select co.description from businessunit bu, plant pl, country co
  where ih.invoicebusinessunit_id = bu.businessunit_id and bu.plant_id = pl.plant_id and pl.country_id = co.country_id) PLANTCOUNTRYDESCRIPTION
from
  invoiceheader ih left outer join customer del on del.customer_id = ih.deltocustomer_link_id
  left outer join invoiceheadercurrency ihc
       inner join currency icu on icu.currency_id = ihc.currency_id
  on ihc.invoiceheader_id = ih.invoiceheader_id and ihc.invoicecurrencytype = 1 --Invoice Currency
, customer bill, status, customerbillinginfo, address, currency
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
and ih.currency_id = currency.currency_id

/
create or replace view V_CONSDELIVEREDPRODUCTS_BUB
 (CONSIGNMENTNOTENUMBER, PRODUCTGROUPCODE, PRODUCTGROUPDESC, TYPEOFMERCHANDISE, PRODUCTCODE, SIZEDEFINITIONCODE, FINISHINGMETHODCODE, PRODUCTDESCRIPTION, FINMETHDESC, DELIVEREDAMOUNT, LANGUAGECODE, BU_CODE, VARIATIONAMOUNT, STANDARDAMOUNT, TOBEDELIVEREDAMOUNT, COLOUR)
as SELECT
  CN.CONSIGNMENTNOTENUMBER, PRDG.CODE PRODUCTGROUPCODE
, ( SELECT DESCRIPTION FROM PRODUCTGROUP_DESC WHERE PRODUCTGROUP_DESC.PRODUCTGROUP_ID = PRDG.PRODUCTGROUP_ID
  AND PRODUCTGROUP_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) PRODUCTGROUPDESC
, PRD.TYPEOFMERCHANDISE
, PRD.CODE PRODUCTCODE, SIZDEF.CODE SIZEDEFINITIONCODE, FINMETH.CODE FINISHINGMETHODCODE
, ( SELECT DESCRIPTION FROM PRODUCT_DESC WHERE PRODUCT_DESC.PRODUCT_ID = PRD.PRODUCT_ID
  AND PRODUCT_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) PRODUCTDESCRIPTION
, ( SELECT FINISHINGMETHOD_DESC.DESCRIPTION FROM FINISHINGMETHOD_DESC WHERE FINISHINGMETHOD_DESC.FINISHINGMETHOD_ID = FINMETH.FINISHINGMETHOD_ID
  AND FINISHINGMETHOD_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) FINMETHDESC
, SUM(PNL.DELIVEREDAMOUNT) DELIVEREDAMOUNT
, LANGUAGES.CODE LANGUAGECODE
, (SELECT BU.CODE FROM BUSINESSUNIT BU WHERE PN.PROCESSBUSINESSUNIT_ID = BU.BUSINESSUNIT_ID) BU_CODE
, sum(PNL.VARIATIONAMOUNT) VARIATIONAMOUNT
, sum(PNL.STANDARDAMOUNT) STANDARDAMOUNT
, sum(PNL.TOBEDELIVEREDAMOUNT) TOBEDELIVEREDAMOUNT
, (select cod.description from color_desc cod where cod.color_id = PRD.color_id and cod.language_id = languages.language_id) Colour
FROM
  CONSIGNMENTNOTE CN, PACKINGNOTE PN, PACKINGNOTELINE PNL
, PRODUCT PRD LEFT OUTER JOIN PRODUCTGROUP PRDG ON PRD.PRODUCTGROUP_ID = PRDG.PRODUCTGROUP_ID
, SIZEDEFINITION SIZDEF, FINISHINGMETHOD FINMETH, LANGUAGES
WHERE
    CN.CONSIGNMENTNOTE_ID = PN.CONSIGNMENTNOTE_ID
AND PN.PACKINGNOTE_ID = PNL.PACKINGNOTE_ID
AND PNL.PRODUCT_ID = PRD.PRODUCT_ID
AND PNL.SIZEDEFINITION_ID = SIZDEF.SIZEDEFINITION_ID
AND PNL.FINISHINGMETHOD_ID = FINMETH.FINISHINGMETHOD_ID-- AND PNL.DELIVEREDAMOUNT <> 0
GROUP BY
  LANGUAGES.LANGUAGE_ID, LANGUAGES.CODE, CN.CONSIGNMENTNOTENUMBER, PRDG.CODE, PRDG.PRODUCTGROUP_ID
, PRD.CODE, PRD.PRODUCT_ID, SIZDEF.CODE, FINMETH.FINISHINGMETHOD_ID, FINMETH.CODE, PRD.color_id
, PNL.PRODUCT_ID, PNL.SIZEDEFINITION_ID, PNL.FINISHINGMETHOD_ID, PN.PROCESSBUSINESSUNIT_ID, PRD.TYPEOFMERCHANDISE

/
create or replace view V_CONSDELIVEREDPRODUCTS_LTS
 (CONSIGNMENTNOTENUMBER, PRODUCTGROUPCODE, PRODUCTGROUPDESC, PRODUCTCODE, SIZEDEFINITIONCODE, PRODUCTDESCRIPTION, FINMETHDESC, DELIVEREDAMOUNT, LANGUAGECODE, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, BU_CODE, ACTIVITY, ACTIVITYCODE, REGUNIT)
as SELECT
  CN.CONSIGNMENTNOTENUMBER, PRDG.CODE PRODUCTGROUPCODE
, ( SELECT DESCRIPTION FROM PRODUCTGROUP_DESC WHERE PRODUCTGROUP_DESC.PRODUCTGROUP_ID = PRDG.PRODUCTGROUP_ID
  AND PRODUCTGROUP_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) PRODUCTGROUPDESC
, PRD.CODE PRODUCTCODE, SIZDEF.CODE SIZEDEFINITIONCODE
, ( SELECT DESCRIPTION FROM PRODUCT_DESC WHERE PRODUCT_DESC.PRODUCT_ID = PRD.PRODUCT_ID
  AND PRODUCT_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) PRODUCTDESCRIPTION
, ( SELECT FINISHINGMETHOD_DESC.DESCRIPTION FROM FINISHINGMETHOD_DESC WHERE FINISHINGMETHOD_DESC.FINISHINGMETHOD_ID = FINMETH.FINISHINGMETHOD_ID
  AND FINISHINGMETHOD_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) FINMETHDESC
, SUM(PNL.DELIVEREDAMOUNT) DELIVEREDAMOUNT
, LANGUAGES.CODE LANGUAGECODE
, CASE WHEN SUM(PNL.NOCHARGEPREVSHORTAGE) = 0 THEN 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)
ELSE SUM(PNL.NOCHARGEPREVSHORTAGE) END  NOCHARGEPREVSHORTAGE
, CASE WHEN SUM(PNL.NOCHARGEPREVREJECTED) = 0 THEN 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)
ELSE SUM(PNL.NOCHARGEPREVREJECTED) END NOCHARGEPREVREJECTED
, (SELECT BU.CODE FROM BUSINESSUNIT BU WHERE PN.PROCESSBUSINESSUNIT_ID = BU.BUSINESSUNIT_ID) BU_CODE
, (SELECT AD.DESCRIPTION FROM ACTIVITY_DESC AD WHERE PRDG.ACTIVITY_ID = AD.ACTIVITY_ID AND AD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) ACTIVITY
, (SELECT AR.CODE FROM ACTIVITY AR WHERE PRDG.ACTIVITY_ID = AR.ACTIVITY_ID ) ACTIVITYCODE
, (SELECT RUD.DESCRIPTION FROM REGISTRATIONUNIT_DESC RUD WHERE RUD.REGISTRATIONUNIT_ID = PRD.REGISTRATIONUNIT_ID AND RUD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) REGUNIT
FROM
  CONSIGNMENTNOTE CN, PACKINGNOTE PN, PACKINGNOTELINE PNL
, PRODUCT PRD LEFT OUTER JOIN PRODUCTGROUP PRDG ON PRD.PRODUCTGROUP_ID = PRDG.PRODUCTGROUP_ID
, SIZEDEFINITION SIZDEF, FINISHINGMETHOD FINMETH, LANGUAGES
WHERE
    CN.CONSIGNMENTNOTE_ID = PN.CONSIGNMENTNOTE_ID
AND PN.PACKINGNOTE_ID = PNL.PACKINGNOTE_ID
AND PNL.PRODUCT_ID = PRD.PRODUCT_ID
AND PNL.SIZEDEFINITION_ID = SIZDEF.SIZEDEFINITION_ID
AND PNL.FINISHINGMETHOD_ID = FINMETH.FINISHINGMETHOD_ID
GROUP BY
  LANGUAGES.LANGUAGE_ID, LANGUAGES.CODE, CN.CONSIGNMENTNOTENUMBER, PRDG.CODE, PRDG.PRODUCTGROUP_ID
, PRD.CODE, PRD.PRODUCT_ID, SIZDEF.CODE, FINMETH.FINISHINGMETHOD_ID, PNL.PACKINGNOTE_ID, PNL.PRODUCT_ID
, PNL.SIZEDEFINITION_ID, PNL.FINISHINGMETHOD_ID, PN.PROCESSBUSINESSUNIT_ID, PRDG.ACTIVITY_ID, PRD.REGISTRATIONUNIT_ID

/
create or replace view V_CONSDELIVEREDPRODUCTS_PLS
 (CONSIGNMENTNOTENUMBER, PRODUCTGROUPCODE, PRODUCTGROUPDESC, TYPEOFMERCHANDISE, PRODUCTCODE, SIZEDEFINITIONCODE, PRODUCTDESCRIPTION, FINMETHDESC, DELIVEREDAMOUNT, STANDARDAMOUNT, VARIATIONAMOUNT, LANGUAGECODE, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, BU_CODE, LINE_ORIGIN, ADJUSTMENT)
as SELECT
  CN.CONSIGNMENTNOTENUMBER, PRDG.CODE PRODUCTGROUPCODE
, ( SELECT DESCRIPTION FROM PRODUCTGROUP_DESC WHERE PRODUCTGROUP_DESC.PRODUCTGROUP_ID = PRDG.PRODUCTGROUP_ID
  AND PRODUCTGROUP_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) PRODUCTGROUPDESC
, PRD.TYPEOFMERCHANDISE
, PRD.CODE PRODUCTCODE, SIZDEF.CODE SIZEDEFINITIONCODE--, FINMETH.CODE FINISHINGMETHODCODE
, ( SELECT DESCRIPTION FROM PRODUCT_DESC WHERE PRODUCT_DESC.PRODUCT_ID = PRD.PRODUCT_ID
  AND PRODUCT_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) PRODUCTDESCRIPTION
, ( SELECT FINISHINGMETHOD_DESC.DESCRIPTION FROM FINISHINGMETHOD_DESC WHERE FINISHINGMETHOD_DESC.FINISHINGMETHOD_ID = FINMETH.FINISHINGMETHOD_ID
  AND FINISHINGMETHOD_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) FINMETHDESC
, SUM(PNL.DELIVEREDAMOUNT) DELIVEREDAMOUNT
, sum(pnl.standardamount) standardamount
, sum(pnl.variationamount) variationamount
, LANGUAGES.CODE LANGUAGECODE
, COALESCE(SUM(PNL.NOCHARGEPREVSHORTAGE),0)  NOCHARGEPREVSHORTAGE
, COALESCE(SUM(PNL.NOCHARGEPREVREJECTED),0)  NOCHARGEPREVREJECTED
, (SELECT BU.CODE FROM BUSINESSUNIT BU WHERE PN.PROCESSBUSINESSUNIT_ID = BU.BUSINESSUNIT_ID) BU_CODE
, pnl.origin line_origin,
nvl((select sum(q.quantity)
         from   rentalqtyadjustment q, productlistperdistribpoint plpd, distributionpoint dp,
                department t, deliveryvariations dev
         where  q.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
         and    plpd.distributionpoint_id = dp.distributionpoint_id
         and    dp.department_id = t.department_id
         and    t.customer_id = CN.Customer_Link_Id
         and    PRD.Product_Id = plpd.product_id
         and    SIZDEF.sizedefinition_id = plpd.sizedefinition_id
         and    FINMETH.finishingmethod_id = plpd.finishingmethod_id
				 AND    q.deliveryvariations_id = dev.deliveryvariations_id
         AND DEV.DELIVERYDATE=PN.DELIVERYDATE
				 ), 0) ADJUSTMENT
FROM
  CONSIGNMENTNOTE CN, PACKINGNOTE PN, PACKINGNOTELINE PNL
, PRODUCT PRD LEFT OUTER JOIN PRODUCTGROUP PRDG ON PRD.PRODUCTGROUP_ID = PRDG.PRODUCTGROUP_ID
, SIZEDEFINITION SIZDEF, FINISHINGMETHOD FINMETH, LANGUAGES
WHERE
    CN.CONSIGNMENTNOTE_ID = PN.CONSIGNMENTNOTE_ID
AND PN.PACKINGNOTE_ID = PNL.PACKINGNOTE_ID
AND PNL.PRODUCT_ID = PRD.PRODUCT_ID
AND PNL.SIZEDEFINITION_ID = SIZDEF.SIZEDEFINITION_ID
AND PNL.FINISHINGMETHOD_ID = FINMETH.FINISHINGMETHOD_ID-- AND PNL.DELIVEREDAMOUNT <> 0
GROUP BY
  LANGUAGES.LANGUAGE_ID, LANGUAGES.CODE, CN.CONSIGNMENTNOTENUMBER, PRDG.CODE, PRDG.PRODUCTGROUP_ID
, PRD.CODE, PRD.PRODUCT_ID, SIZDEF.CODE, FINMETH.FINISHINGMETHOD_ID --PNL.PACKINGNOTE_ID,
, PNL.PRODUCT_ID, PNL.SIZEDEFINITION_ID, PNL.FINISHINGMETHOD_ID, pnl.origin, PN.PROCESSBUSINESSUNIT_ID, PRD.TYPEOFMERCHANDISE, CN.Customer_Link_Id, SIZDEF.sizedefinition_id, PN.DELIVERYDATE--, pn.packingnote_id--, PNL.NOCHARGEPREVSHORTAGE, PNL.NOCHARGEPREVREJECTED

/
create or replace view V_CONSIGNDELNOTES_FIS
 (CONSIGNMENTNOTENUMBER, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, CONSPOINT, NOTENUMBER, TRANSPORTARTICLE, PACKINGNOTE_ID, WEIGHTUNIT, CONTAINERRECORDINGACTIVE, LANGUAGECODE, ORIGIN, READYDATE, REMARK)
as select /*+index (department XPKDEPARTMENT)*/
       cn.consignmentnotenumber
,      department.departmentnumber
,      department.description departmentdescription
,      distributionpoint.distributionpointnumber conspoint
,      pn.notenumber
,      transportarticle.code transportarticle
,      pn.packingnote_id
,      ss.value weightunit
,      ss2.value containerrecordingactive
,      languages.code languagecode
,      pn.origin
,      pn.deliverydate readydate
,      pn.remark
from   consignmentnote cn
,      packingnote pn
,      distributionpoint
,      department
,      transportarticle
,      businessunit bu
,      systemsetting ss
,      systemsetting ss2
,      languages
where  cn.consignmentnote_id = pn.consignmentnote_id
   and pn.distributionpoint_id = distributionpoint.distributionpoint_id
   and distributionpoint.department_id = department.department_id
   and pn.transportarticle_id = transportarticle.transportarticle_id
   and pn.processbusinessunit_id = bu.businessunit_id
   and bu.plant_id = ss.plant_id
   and ss.name = 'WEIGHTUNIT'
   and ss2.plant_id = bu.plant_id
   and ss2.name = 'CONTAINERRECORDINGACTIVE'

/
create or replace view V_CONSIGNMENTBAGDETAILS_LLG
 (LINETYPE, PRIMARYID, EXTRABAG, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDEFINITIONCODE, FMCODE, CONSIGNMENTNOTE_ID, CN_BUSINESSUNITCODE, CONSIGNMENTNOTENUMBER, TOBEDELIVEREDAMOUNT, DELIVEREDQTY, VARIATIONAMOUNT, STANDARDAMOUNT, SHORTAGEQTY, PLPD_ADJUSTCIRCINVENTORY, LANGUAGECODE, BUCODE, NOTENUMBER, ORIGIN, DEPARTMENTNUMBER, DISTRIBUTIONPOINTNUMBER, PACKINGNOTE_ID, PRODUCT_ID, SIZEDEFINITION_ID, FINISHINGMETHOD_ID)
as select 1 linetype
, bt.primaryid
, bt.extrabag
, p.code productcode
, (select description from product_desc where product_desc.product_id = p.product_id and product_desc.language_id = languages.language_id ) productdescription
, sd.code sizedefinitioncode
, fm.code fmcode
, cn.consignmentnote_id
, (select bu.code from businessunit bu where bu.businessunit_id = cn.businessunit_id) cn_businessunitcode
, cn.consignmentnotenumber
, sum(pnl.tobedeliveredamount) tobedeliveredamount
, sum(pnl.deliveredamount) deliveredqty
, sum(pnl.variationamount) variationamount
, sum(pnl.standardamount) standardamount
, sum(pnl.standardamount + pnl.variationamount - pnl.deliveredamount) shortageqty
, (select plpd.adjustcircinventory
   from productlistperdistribpoint plpd
   where plpd.distributionpoint_id = dp.distributionpoint_id
   and plpd.product_id = pnl.product_id
   and plpd.sizedefinition_id = pnl.sizedefinition_id
   and plpd.finishingmethod_id = pnl.finishingmethod_id
   ) plpd_adjustcircinventory
, languages.code languagecode
, bu.code bucode
, pn.notenumber
, pn.origin
, d.departmentnumber
, dp.distributionpointnumber
, pn.packingnote_id
, pnl.product_id
, pnl.sizedefinition_id
, pnl.finishingmethod_id
from bagtag bt,
     packingnote pn,
     consignmentnote cn,
     packingnoteline pnl,
     product p,
     sizedefinition sd,
     finishingmethod fm,
     languages,
     businessunit bu,
     distributionpoint dp,
     department d
where bt.packingnote_id = pn.packingnote_id
and 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 pn.consignmentnote_id = cn.consignmentnote_id
and pn.processbusinessunit_id = bu.businessunit_id
and pn.distributionpoint_id = dp.distributionpoint_id
and dp.department_id = d.department_id
and bt.extrabag <> 'Y'
group by cn.consignmentnote_id, cn.consignmentnotenumber, cn.businessunit_id
, d.departmentnumber, dp.distributionpoint_id, dp.distributionpointnumber
, pn.packingnote_id, pn.notenumber, pn.origin
, p.product_id, p.code, pnl.product_id
, pnl.sizedefinition_id, sd.code
, pnl.finishingmethod_id, fm.code
, bt.primaryid, bt.extrabag
, bu.code
, languages.language_id,languages.code

/
create or replace view V_CONSIGNMENTCORRECTIONNOTES
 (CONSIGNMENTNOTENUMBER, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, CONSPOINT, CONSPOINTDESC, NOTENUMBER, TRANSPORTARTICLE, PACKINGNOTE_ID, ORIGIN, WEIGHTUNIT, CONTAINERRECORDINGACTIVE, LANGUAGECODE, BU_CODE, BU_DESC)
as select /*+index (department XPKDEPARTMENT)*/
       cn.consignmentnotenumber, department.departmentnumber,
       department.description departmentdescription,
       distributionpoint.distributionpointnumber conspoint, distributionpoint.description conspointdesc, pn.notenumber,
       transportarticle.code transportarticle, pn.packingnote_id, pn.origin, ss.value weightunit,
       ss2.value containerrecordingactive, languages.code languagecode,
			 bu.code BU_code, bu.description BU_desc
from   consignmentnote cn, packingnote pn, distributionpoint, department, transportarticle,
       businessunit bu, systemsetting ss, systemsetting ss2, languages
where  cn.consignmentnote_id = pn.consignmentnote_id and
       pn.distributionpoint_id = distributionpoint.distributionpoint_id and
       distributionpoint.department_id = department.department_id and
       pn.transportarticle_id = transportarticle.transportarticle_id and
       pn.processbusinessunit_id = bu.businessunit_id and bu.plant_id = ss.plant_id and
       ss.name = 'WEIGHTUNIT' and ss2.plant_id = bu.plant_id and
       ss2.name = 'CONTAINERRECORDINGACTIVE'

/
create or replace view V_CONSIGNMENTCORRECTIONS_WMA
 (CONSIGNMENTNOTENUMBER, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, CONSPOINT, NOTENUMBER, TRANSPORTARTICLE, PACKINGNOTE_ID, ORIGIN, REFERENCENUMBER, DELIVERYDATE, REMARK, TOTALAMOUNT, TOTALAMOUNTEXCLUDINGVAT, TOTALVAT)
as select
  cn.consignmentnotenumber, department.departmentnumber, department.description departmentDescription
, distributionpoint.distributionpointnumber ConsPoint, pn.notenumber, transportarticle.code TransportArticle
, pn.packingnote_id, pn.origin
, pn.referencenumber, pn.deliverydate, pn.remark
, pn.totalamount, pn.totalamountexcludingvat, (pn.totalamount - pn.totalamountexcludingvat) totalVAT
--, ss.value WEIGHTUNIT, SS2.VALUE CONTAINERRECORDINGACTIVE
--, languages.code languageCode
from
  ConsignmentNote cn, packingnote pn, distributionpoint, department, transportarticle
--  , businessunit bu, systemsetting ss, SYSTEMSETTING SS2
--, languages
where
    cn.consignmentnote_id = pn.consignmentnote_id
and pn.distributionpoint_id = distributionpoint.distributionpoint_id
and distributionpoint.department_id = department.department_id
and pn.transportarticle_id = transportarticle.transportarticle_id
--and pn.processbusinessunit_id = bu.businessunit_id
--and bu.plant_id = ss.plant_id
--and ss.name = 'WEIGHTUNIT'
--AND SS2.PLANT_ID = bu.PLANT_ID
--AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'

/
create or replace view V_CONSIGNMENTDELIVEREDPRODUCTS
 (CONSIGNMENTNOTENUMBER, PRODUCTGROUPCODE, PRODUCTGROUPDESC, TYPEOFMERCHANDISE, PRODUCTCODE, SIZEDEFINITIONCODE, PRODUCTDESCRIPTION, FINMETHDESC, DELIVEREDAMOUNT, LANGUAGECODE, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, BU_CODE)
as SELECT
  CN.CONSIGNMENTNOTENUMBER, PRDG.CODE PRODUCTGROUPCODE
, ( SELECT DESCRIPTION FROM PRODUCTGROUP_DESC WHERE PRODUCTGROUP_DESC.PRODUCTGROUP_ID = PRDG.PRODUCTGROUP_ID
  AND PRODUCTGROUP_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) PRODUCTGROUPDESC
, PRD.TYPEOFMERCHANDISE
, PRD.CODE PRODUCTCODE, SIZDEF.CODE SIZEDEFINITIONCODE--, FINMETH.CODE FINISHINGMETHODCODE
, ( SELECT DESCRIPTION FROM PRODUCT_DESC WHERE PRODUCT_DESC.PRODUCT_ID = PRD.PRODUCT_ID
  AND PRODUCT_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) PRODUCTDESCRIPTION
, ( SELECT FINISHINGMETHOD_DESC.DESCRIPTION FROM FINISHINGMETHOD_DESC WHERE FINISHINGMETHOD_DESC.FINISHINGMETHOD_ID = FINMETH.FINISHINGMETHOD_ID
  AND FINISHINGMETHOD_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) FINMETHDESC
, SUM(PNL.DELIVEREDAMOUNT) DELIVEREDAMOUNT
, LANGUAGES.CODE LANGUAGECODE
, CASE WHEN SUM(PNL.NOCHARGEPREVSHORTAGE) = 0 THEN COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV, PACKINGNOTELINE PNL1, PACKINGNOTE PN1, CONSIGNMENTNOTE CN1
WHERE DV.CAUSENOTE_ID = PNL1.PACKINGNOTE_ID AND DV.PRODUCT_ID = PNL1.PRODUCT_ID
AND DV.SIZEDEFINITION_ID = PNL1.SIZEDEFINITION_ID AND DV.FINISHINGMETHOD_ID = PNL1.FINISHINGMETHOD_ID
AND DV.ORIGIN = 1 AND DV.SOILCOUNTSUBTYPE = 2
AND PNL1.PACKINGNOTE_ID = PN1.PACKINGNOTE_ID AND PN1.CONSIGNMENTNOTE_ID = CN1.CONSIGNMENTNOTE_ID 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 DELIVERYVARIATIONS DV, PACKINGNOTELINE PNL1, PACKINGNOTE PN1, CONSIGNMENTNOTE CN1
WHERE DV.CAUSENOTE_ID = PNL1.PACKINGNOTE_ID AND DV.PRODUCT_ID = PNL1.PRODUCT_ID
AND DV.SIZEDEFINITION_ID = PNL1.SIZEDEFINITION_ID AND DV.FINISHINGMETHOD_ID = PNL1.FINISHINGMETHOD_ID
AND DV.ORIGIN = 1 AND DV.SOILCOUNTSUBTYPE = 3
AND PNL1.PACKINGNOTE_ID = PN1.PACKINGNOTE_ID AND PN1.CONSIGNMENTNOTE_ID = CN1.CONSIGNMENTNOTE_ID 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
  CONSIGNMENTNOTE CN, PACKINGNOTE PN, PACKINGNOTELINE PNL
, PRODUCT PRD LEFT OUTER JOIN PRODUCTGROUP PRDG ON PRD.PRODUCTGROUP_ID = PRDG.PRODUCTGROUP_ID
, SIZEDEFINITION SIZDEF, FINISHINGMETHOD FINMETH, LANGUAGES
WHERE
    CN.CONSIGNMENTNOTE_ID = PN.CONSIGNMENTNOTE_ID
AND PN.PACKINGNOTE_ID = PNL.PACKINGNOTE_ID
AND PNL.PRODUCT_ID = PRD.PRODUCT_ID
AND PNL.SIZEDEFINITION_ID = SIZDEF.SIZEDEFINITION_ID
AND PNL.FINISHINGMETHOD_ID = FINMETH.FINISHINGMETHOD_ID-- AND PNL.DELIVEREDAMOUNT <> 0
GROUP BY
  LANGUAGES.LANGUAGE_ID, LANGUAGES.CODE, CN.CONSIGNMENTNOTENUMBER, PRDG.CODE, PRDG.PRODUCTGROUP_ID
, PRD.CODE, PRD.PRODUCT_ID, SIZDEF.CODE, FINMETH.FINISHINGMETHOD_ID --PNL.PACKINGNOTE_ID,
, PNL.PRODUCT_ID, PNL.SIZEDEFINITION_ID, PNL.FINISHINGMETHOD_ID, PN.PROCESSBUSINESSUNIT_ID, PRD.TYPEOFMERCHANDISE--, PNL.NOCHARGEPREVSHORTAGE, PNL.NOCHARGEPREVREJECTED

/
create or replace view V_CONSIGNMENTDELIVERYNOTES
 (CONSIGNMENTNOTENUMBER, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, CONSPOINT, NOTENUMBER, TRANSPORTARTICLE, PACKINGNOTE_ID, WEIGHTUNIT, CONTAINERRECORDINGACTIVE, LANGUAGECODE, ORIGIN, BU_CODE, BU_DESC)
as select /*+index (department XPKDEPARTMENT)*/
       cn.consignmentnotenumber, department.departmentnumber,
       department.description departmentdescription,
       distributionpoint.distributionpointnumber conspoint, pn.notenumber,
       transportarticle.code transportarticle, pn.packingnote_id, ss.value weightunit,
       ss2.value containerrecordingactive, languages.code languagecode, pn.origin,
			 bu.code BU_code, bu.description BU_desc
from   consignmentnote cn, packingnote pn, distributionpoint, department, transportarticle,
       businessunit bu, systemsetting ss, systemsetting ss2, languages
where  cn.consignmentnote_id = pn.consignmentnote_id and
       pn.distributionpoint_id = distributionpoint.distributionpoint_id and
       distributionpoint.department_id = department.department_id and
       pn.transportarticle_id = transportarticle.transportarticle_id and
       pn.processbusinessunit_id = bu.businessunit_id and bu.plant_id = ss.plant_id and
       ss.name = 'WEIGHTUNIT' and ss2.plant_id = bu.plant_id and
       ss2.name = 'CONTAINERRECORDINGACTIVE'

/
create or replace view V_CONSIGNMENTDELIVERYNOTES_ANG
 (CONSIGNMENTNOTENUMBER, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, CONSPOINT, NOTENUMBER, TRANSPORTARTICLE, PACKINGNOTE_ID, WEIGHTUNIT, CONTAINERRECORDINGACTIVE, LANGUAGECODE, ORIGIN, LANGUAGE_ID)
as select /*+index (department XPKDEPARTMENT)*/
       cn.consignmentnotenumber, department.departmentnumber,
       department.description departmentdescription,
       distributionpoint.distributionpointnumber conspoint, pn.notenumber,
       transportarticle.code transportarticle, pn.packingnote_id, ss.value weightunit,
       ss2.value containerrecordingactive, languages.code languagecode, pn.origin
/*, (select v2.weighcat_code from v_deliverynote_knt v2
where  languages.code = v2.languagecode and pn.packingnote_id = v2.packingnote_id) weighcat_code
, (select v2.weighingcategorydesc from v_deliverynote_knt v2
where  languages.code = v2.languagecode and pn.packingnote_id = v2.packingnote_id) weighingcategorydesc
, (select (v2.grossweight - v2.tareweight) from v_deliverynote_knt v2
where  languages.code = v2.languagecode and pn.packingnote_id = v2.packingnote_id) weight
, (select v2.weightdecimals from v_deliverynote_knt v2
where  languages.code = v2.languagecode and pn.packingnote_id = v2.packingnote_id) weightdecimals
, (select v2.CONTAINER_PRIMARYID from v_deliverynote_knt v2
where  languages.code = v2.languagecode and pn.packingnote_id = v2.packingnote_id) CONTAINER_PRIMARYID
, (select v2.CONTAINERTYPE_CODE from v_deliverynote_knt v2
where  languages.code = v2.languagecode and pn.packingnote_id = v2.packingnote_id) CONTAINERTYPE_CODE
, (select v2.CONTAINERTYPE_DESC from v_deliverynote_knt v2
where  languages.code = v2.languagecode and pn.packingnote_id = v2.packingnote_id) CONTAINERTYPE_DESC*/
, languages.language_id
from   consignmentnote cn, packingnote pn, distributionpoint, department, transportarticle,
       businessunit bu, systemsetting ss, systemsetting ss2, languages
where  cn.consignmentnote_id = pn.consignmentnote_id and
       pn.distributionpoint_id = distributionpoint.distributionpoint_id and
       distributionpoint.department_id = department.department_id and
       pn.transportarticle_id = transportarticle.transportarticle_id and
       pn.processbusinessunit_id = bu.businessunit_id and bu.plant_id = ss.plant_id and
       ss.name = 'WEIGHTUNIT' and ss2.plant_id = bu.plant_id and
       ss2.name = 'CONTAINERRECORDINGACTIVE'

/
create or replace view V_CONSIGNMENTDELIVERYNOTES_BUB
 (CONSIGNMENTNOTENUMBER, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, CONSPOINT, NOTENUMBER, TRANSPORTARTICLE, PACKINGNOTE_ID, WEIGHTUNIT, CONTAINERRECORDINGACTIVE, LANGUAGECODE, ORIGIN, BU_CODE, BU_DESC, REMARK, CONSIGNMENTNOTE_ID)
as select /*+index (department XPKDEPARTMENT)*/
       cn.consignmentnotenumber, department.departmentnumber,
       department.description departmentdescription,
       distributionpoint.distributionpointnumber conspoint, pn.notenumber,
       transportarticle.code transportarticle, pn.packingnote_id, ss.value weightunit,
       ss2.value containerrecordingactive, languages.code languagecode, pn.origin,
       bu.code BU_code, bu.description BU_desc,
	     pn.remark, cn.consignmentnote_id
from   consignmentnote cn, packingnote pn, distributionpoint, department, transportarticle,
       businessunit bu, systemsetting ss, systemsetting ss2, languages
where  cn.consignmentnote_id = pn.consignmentnote_id and
       pn.distributionpoint_id = distributionpoint.distributionpoint_id and
       distributionpoint.department_id = department.department_id and
       pn.transportarticle_id = transportarticle.transportarticle_id and
       pn.processbusinessunit_id = bu.businessunit_id and bu.plant_id = ss.plant_id and
       ss.name = 'WEIGHTUNIT' and ss2.plant_id = bu.plant_id and
       ss2.name = 'CONTAINERRECORDINGACTIVE'

/
create or replace view V_CONSIGNMENTDELIVERYNOTES_CIW
 (CONSIGNMENTNOTENUMBER, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, CONSPOINT, CONSPOINTDESCRIPTION, NOTENUMBER, TRANSPORTARTICLE, PACKINGNOTE_ID, WEIGHTUNIT, CONTAINERRECORDINGACTIVE, LANGUAGECODE, ORIGIN, BU_CODE, BU_DESC)
as select /*+index (department XPKDEPARTMENT)*/
       cn.consignmentnotenumber, department.departmentnumber,
       department.description departmentdescription,
       distributionpoint.distributionpointnumber conspoint, distributionpoint.description conspointdescription,
       pn.notenumber,
       transportarticle.code transportarticle, pn.packingnote_id, ss.value weightunit,
       ss2.value containerrecordingactive, languages.code languagecode, pn.origin,
       bu.code BU_code, bu.description BU_desc
from   consignmentnote cn, packingnote pn, distributionpoint, department, transportarticle,
       businessunit bu, systemsetting ss, systemsetting ss2, languages
where  cn.consignmentnote_id = pn.consignmentnote_id and
       pn.distributionpoint_id = distributionpoint.distributionpoint_id and
       distributionpoint.department_id = department.department_id and
       pn.transportarticle_id = transportarticle.transportarticle_id and
       pn.processbusinessunit_id = bu.businessunit_id and bu.plant_id = ss.plant_id and
       ss.name = 'WEIGHTUNIT' and ss2.plant_id = bu.plant_id and
       ss2.name = 'CONTAINERRECORDINGACTIVE'

/
create or replace view V_CONSIGNMENTDELIVERYNOTES_EDE
 (CONSIGNMENTNOTENUMBER, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, CONSPOINT, NOTENUMBER, TRANSPORTARTICLE, PACKINGNOTE_ID, WEIGHTUNIT, CONTAINERRECORDINGACTIVE, LANGUAGECODE, ORIGIN, WEEK, DAYNUMBER)
as select cn.consignmentnotenumber, department.departmentnumber,
       department.description departmentdescription,
       distributionpoint.distributionpointnumber conspoint, pn.notenumber,
       transportarticle.code transportarticle, pn.packingnote_id, ss.value weightunit,
       ss2.value containerrecordingactive, languages.code languagecode, pn.origin
       , pn.week, pn.daynumber
from   consignmentnote cn, packingnote pn, distributionpoint, department, transportarticle,
       businessunit bu, systemsetting ss, systemsetting ss2, languages
where  cn.consignmentnote_id = pn.consignmentnote_id and
       pn.distributionpoint_id = distributionpoint.distributionpoint_id and
       distributionpoint.department_id = department.department_id and
       pn.transportarticle_id = transportarticle.transportarticle_id and
       pn.processbusinessunit_id = bu.businessunit_id and bu.plant_id = ss.plant_id and
       ss.name = 'WEIGHTUNIT' and ss2.plant_id = bu.plant_id and
       ss2.name = 'CONTAINERRECORDINGACTIVE'

/
create or replace view V_CONSIGNMENTDELIVERYNOTES_LTS
 (CONSIGNMENTNOTENUMBER, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, CONSPOINT, NOTENUMBER, TRANSPORTARTICLE, PACKINGNOTE_ID, WEIGHTUNIT, ORIGIN, BU_CODE, BU_DESC, PRD500AMNT)
as select /*+index (department XPKDEPARTMENT)*/
       cn.consignmentnotenumber, department.departmentnumber,
       department.description departmentdescription,
       distributionpoint.distributionpointnumber conspoint, pn.notenumber,
       transportarticle.code transportarticle, pn.packingnote_id, ss.value weightunit,
       pn.origin,
			 bu.code BU_code, bu.description BU_desc,
       coalesce((select sum(pnl.deliveredamount) from packingnoteline pnl where pnl.packingnote_id = pn.packingnote_id and pnl.product_id = (select p.product_id from product p where p.code = '000500')), 0) prd500amnt
from   consignmentnote cn, packingnote pn, distributionpoint, department, transportarticle,
       businessunit bu, systemsetting ss
where  cn.consignmentnote_id = pn.consignmentnote_id and
       pn.distributionpoint_id = distributionpoint.distributionpoint_id and
       distributionpoint.department_id = department.department_id and
       pn.transportarticle_id = transportarticle.transportarticle_id and
       pn.processbusinessunit_id = bu.businessunit_id and bu.plant_id = ss.plant_id and
       ss.name = 'WEIGHTUNIT'

/
create or replace view V_CONSIGNMENTDELIVERYNOTES_RAS
 (CONSIGNMENTNOTENUMBER, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, CONSPOINT, NOTENUMBER, TRANSPORTARTICLE, PACKINGNOTE_ID, WEIGHTUNIT, CONTAINERRECORDINGACTIVE, LANGUAGECODE, ORIGIN, WEEK, DAYNUMBER)
as select cn.consignmentnotenumber, department.departmentnumber,
       department.description departmentdescription,
       distributionpoint.distributionpointnumber conspoint, pn.notenumber,
       transportarticle.code transportarticle, pn.packingnote_id, ss.value weightunit,
       ss2.value containerrecordingactive, languages.code languagecode, pn.origin
       , pn.week, pn.daynumber
from   consignmentnote cn, packingnote pn, distributionpoint, department, transportarticle,
       businessunit bu, systemsetting ss, systemsetting ss2, languages, status st
where  cn.consignmentnote_id = pn.consignmentnote_id  and
       (pn.status_id = st.status_id and st.code not in ('40','60') and st.statustype = 'PN') and
       pn.distributionpoint_id = distributionpoint.distributionpoint_id and
       distributionpoint.department_id = department.department_id and
       pn.transportarticle_id = transportarticle.transportarticle_id and
       pn.processbusinessunit_id = bu.businessunit_id and bu.plant_id = ss.plant_id and
       ss.name = 'WEIGHTUNIT' and ss2.plant_id = bu.plant_id and
       ss2.name = 'CONTAINERRECORDINGACTIVE'

/
create or replace view V_CONSIGNMENTDELIVERYNOTES_WMA
 (CONSIGNMENTNOTENUMBER, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, CONSPOINT, NOTENUMBER, TRANSPORTARTICLE, PACKINGNOTE_ID, ORIGIN, REFERENCENUMBER, DELIVERYDATE, REMARK, TOTALAMOUNT, TOTALAMOUNTEXCLUDINGVAT, TOTALVAT)
as select
  cn.consignmentnotenumber, department.departmentnumber, department.description departmentDescription
, distributionpoint.distributionpointnumber ConsPoint, pn.notenumber, transportarticle.code TransportArticle
, pn.packingnote_id
--, ss.value WEIGHTUNIT, SS2.VALUE CONTAINERRECORDINGACTIVE
--, languages.code languageCode
, pn.origin
, pn.referencenumber, pn.deliverydate, pn.remark
, pn.totalamount, pn.totalamountexcludingvat, (pn.totalamount - pn.totalamountexcludingvat) totalVAT
from
  ConsignmentNote cn, packingnote pn, distributionpoint, department, transportarticle
  --, businessunit bu, systemsetting ss, SYSTEMSETTING SS2
  --, languages
where
    cn.consignmentnote_id = pn.consignmentnote_id
and pn.distributionpoint_id = distributionpoint.distributionpoint_id
and distributionpoint.department_id = department.department_id
and pn.transportarticle_id = transportarticle.transportarticle_id
--and pn.processbusinessunit_id = bu.businessunit_id
--and bu.plant_id = ss.plant_id
--and ss.name = 'WEIGHTUNIT'
--AND SS2.PLANT_ID = bu.PLANT_ID
--AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'

/
create or replace view V_CONSIGNMENTDELIVPRODUCTS_ANG
 (CONSIGNMENTNOTENUMBER, PRODUCTGROUPCODE, PRODUCTGROUPDESC, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDEFINITIONCODE, SIZEDEFINITIONDESCRIPTION, FINISHINGMETHODCODE, FINMETHDESC, DELIVEREDAMOUNT, LANGUAGECODE)
as select cn.consignmentnotenumber, prdg.code productgroupcode,
       max((select description
            from   productgroup_desc
            where  productgroup_desc.productgroup_id = prdg.productgroup_id
            and    productgroup_desc.language_id = l.language_id)) productgroupdesc,
       prd.code productcode,
       max(nvl(pnl.customdescription,
                (select description
                  from   product_desc
                  where  product_desc.product_id = prd.product_id
                  and    product_desc.language_id = l.language_id))) productdescription,
       sizdef.code sizedefinitioncode,
       max((select description
            from   sizedefinition_desc sdd
            where  sdd.sizedefinition_id = sizdef.sizedefinition_id
            and    sdd.language_id = l.language_id)) sizedefinitiondescription,
            finmeth.code finishingmethodcode,
       max((select finishingmethod_desc.description
            from   finishingmethod_desc
            where  finishingmethod_desc.finishingmethod_id = finmeth.finishingmethod_id
            and    finishingmethod_desc.language_id = l.language_id)) finmethdesc,
       sum(pnl.deliveredamount) deliveredamount, l.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
left   outer join productgroup prdg
on     prd.productgroup_id = prdg.productgroup_id
join   sizedefinition sizdef
on     pnl.sizedefinition_id = sizdef.sizedefinition_id
join   finishingmethod finmeth
on     pnl.finishingmethod_id = finmeth.finishingmethod_id, languages l
group  by l.code, cn.consignmentnotenumber, prdg.code, prd.code, sizdef.code, finmeth.code

/
create or replace view V_CONSIGNMENTDELPRODUCTS_LLG
 (CONSIGNMENTNOTE_ID, CONSIGNMENTNOTENUMBER, PRODUCTCODE, SIZEDEFINITIONCODE, PRODUCTDESCRIPTION, DELIVEREDAMOUNT, LANGUAGECODE, SHORTAGEQTY, SOILCOUNTQTY, INCREASEDQTY, DECREASEDQTY, BU_CODE, CONSPOINTNUMBER, CONSPOINTDESCR)
as SELECT cn.consignmentnote_id
,  cn.consignmentnotenumber
, 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
, sum(pnl.deliveredamount) deliveredamount
, languages.code languagecode
, sum(pnl.standardamount + pnl.variationamount - pnl.deliveredamount) shortageqty
, nvl((select sum (dv.amount)
             from deliveryvariations dv
             where dv.packingnote_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 in (1, 4, 5)), 0) soilcountqty
, nvl((select sum (dv.amount) from deliveryvariations dv
              where dv.packingnote_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 = 3 and dv.amount > 0), 0) increasedqty
, nvl((select sum (dv.amount) from deliveryvariations dv
              where dv.packingnote_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 in (3,4,5) and dv.amount < 0)), 0) decreasedqty
, (select bu.code from businessunit bu where pn.processbusinessunit_id = bu.businessunit_id) bu_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
  consignmentnote cn, packingnote pn, packingnoteline pnl
, product p
, sizedefinition sizdef, finishingmethod finmeth, languages
where
    cn.consignmentnote_id = pn.consignmentnote_id
and pn.packingnote_id = pnl.packingnote_id
and pnl.product_id = p.product_id
and pnl.sizedefinition_id = sizdef.sizedefinition_id
and pnl.finishingmethod_id = finmeth.finishingmethod_id
group by cn.consignmentnote_id, cn.consignmentnotenumber
, pn.distributionpoint_id, pn.processbusinessunit_id
, pnl.packingnote_id
, pnl.product_id, p.product_id, p.code, pnl.sizedefinition_id, sizdef.code, pnl.finishingmethod_id
, languages.language_id, languages.code

/
create or replace view V_CONSIGNMENTNOTE
 (PLANTNAME, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTPHONENO, PLANTFAXNO, PLANTSTATE, CONSIGNMENTNOTE_ID, CONSIGNMENTNOTENUMBER, CONSIGNMENTNOTEYEAR, PHONELEN, CONSIGNMENTNOTEWEEK, ROUTENUMBER, ROUTEDESCRIPTION, STOPNUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERSTREET, CUSTOMERSTREET2, CUSTOMERZIPCODE, CUSTOMERCITY, CUSTOMERSTATE, DELIVERYDATE, CONSIGNMENTNOTELEVEL, DEPARTMENT_LINK_ID, DELIVERYPOINT_LINK_ID, EXTERNALORDERNUMBER, DEL_POINT_CODE, DEL_POINT_DESC, DEL_POINT_STREET
, DEL_POINT_ZIP, DEL_POINT_CITY, DEL_POINT_STATE, DEL_POINT_STREET2, DEL_POINT_COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESC, BU_CODE, BU_DESC, SCANSONDELIVERYNOTE, LAYOUTCODE)
as select
  plant.name PlantName, address.street plantstreet, address.zipcode plantzipcode, address.city plantcity
, plant.phoneno plantphoneno, plant.faxno plantfaxno, address.state plantstate, CN.CONSIGNMENTNOTE_ID
, cn.consignmentnotenumber, cn.year ConsignmentNoteYear, /*cast(*/ (select ss.value from systemsetting ss
where ss.name like 'PHONEFAXLENGTH'
and ss.plant_id=plant.plant_id
) /*as varchar2(16))*/phonelen
, cn.week ConsignmentNoteWeek, route.routenumber, route.description routeDescription
, /*(select max(routestop.stopnumber) from routestop where cu.customer_id = routestop.customer_id and
routestop.route_id = route.route_id)*/ cn.stopnumber stopnumber
, cu.customernumber
, cu.legalname customerName, ads.street customerstreet, ads.street2 customerstreet2, ads.zipcode customerzipcode, ads.city customercity, ads.state customerstate
, CN.DELIVERYDATE, cu.consignmentnotelevel -- check must be on department_link_id and deliverypoint_link_id
, 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, 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.county del_point_county
, d.departmentnumber, d.description departmentdesc
, bu.code BU_code, bu.description BU_desc, cu.scansondeliverynote
, (select fl.code from formlayout fl where fl.formlayout_id = cu.consignmentnotelayout_id) layoutcode
from
  ConsignmentNote cn
     left outer join route on cn.route_id = route.route_id
     left outer join department d on d.department_id = cn.department_link_id
     left outer join (deliverypoint dp left outer join address dp_addr on dp_addr.address_id = dp.deliveryaddress_id)
          on dp.deliverypoint_id = cn.deliverypoint_link_id
, businessunit bu, plant, address, address ads, customer cu-- , routestop
where cn.businessunit_id = bu.businessunit_id
and bu.plant_id = plant.plant_id
and plant.address_id = address.address_id-- and cu.customer_id = routestop.customer_id
and cn.customer_link_id = cu.customer_id
and cu.visitaddress_id = ads.address_id
and 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_CONSIGNMENTNOTE_ANG
 (PLANTNAME, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTPHONENO, PLANTFAXNO, PLANTSTATE, CONSIGNMENTNOTE_ID, CONSIGNMENTNOTENUMBER, CONSIGNMENTNOTEYEAR, CONSIGNMENTNOTEWEEK, ROUTENUMBER, ROUTEDESCRIPTION, STOPNUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERSTREET, CUSTOMERSTREET2, CUSTOMERZIPCODE, CUSTOMERCITY, CUSTOMERSTATE, DELIVERYDATE, CONSIGNMENTNOTELEVEL, DEPARTMENT_LINK_ID, DELIVERYPOINT_LINK_ID, EXTERNALORDERNUMBER, DEL_POINT_CODE, DEL_POINT_DESC, DEL_POINT_STREET
, DEL_POINT_ZIP, DEL_POINT_CITY, DEL_POINT_STATE, DEL_POINT_STREET2, DEL_POINT_COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESC, BU_CODE, BU_DESC, SCANSONDELIVERYNOTE)
as select
  plant.name PlantName, address.street plantstreet, address.zipcode plantzipcode, address.city plantcity
, plant.phoneno plantphoneno, plant.faxno plantfaxno, address.state plantstate, CN.CONSIGNMENTNOTE_ID
, cn.consignmentnotenumber, cn.year ConsignmentNoteYear
, cn.week ConsignmentNoteWeek, route.routenumber, route.description routeDescription
, /*(select max(routestop.stopnumber) from routestop where cu.customer_id = routestop.customer_id and
routestop.route_id = route.route_id)*/ cn.stopnumber stopnumber
, cu.customernumber
, --cast(
cu.name --as varchar2(60))
customerName, ads.street customerstreet, ads.street2 customerstreet2, ads.zipcode customerzipcode, ads.city customercity, ads.state customerstate
, CN.DELIVERYDATE, cu.consignmentnotelevel -- check must be on department_link_id and deliverypoint_link_id
, 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, 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.county del_point_county
, d.departmentnumber, d.description departmentdesc
, bu.code BU_code, bu.description BU_desc, cu.scansondeliverynote
from
  ConsignmentNote cn
     left outer join route on cn.route_id = route.route_id
     left outer join department d on d.department_id = cn.department_link_id
     left outer join (deliverypoint dp left outer join address dp_addr on dp_addr.address_id = dp.deliveryaddress_id)
          on dp.deliverypoint_id = cn.deliverypoint_link_id
, businessunit bu, plant, address, address ads, customer cu-- , routestop
where cn.businessunit_id = bu.businessunit_id
and bu.plant_id = plant.plant_id
and plant.address_id = address.address_id-- and cu.customer_id = routestop.customer_id
and cn.customer_link_id = cu.customer_id
and cu.visitaddress_id = ads.address_id
and cu.consignmentnotelevel > 0

/
create or replace view V_CONSIGNMENTNOTE_CIW
 (PLANTNAME, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTCOUNTY, PLANTCOUNTRY_DESC, PLANTEMAIL, PLANTWEBSITE, PLANTCOMPANYPHONE, PLANTPHONENO, PLANTFAXNO, PLANTSTATE, CONSIGNMENTNOTE_ID, CONSIGNMENTNOTENUMBER, CONSIGNMENTNOTEYEAR, CONSIGNMENTNOTEWEEK, ROUTENUMBER, ROUTEDESCRIPTION, STOPNUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERSTREET, CUSTOMERSTREET2, CUSTOMERZIPCODE, CUSTOMERCITY, CUSTOMERCOUNTY, CUSTOMERSTATE, DELIVERYDATE, CONSIGNMENTNOTELEVEL, DEPARTMENT_LINK_ID
, DELIVERYPOINT_LINK_ID, EXTERNALORDERNUMBER, DEL_POINT_CODE, DEL_POINT_DESC, DEL_POINT_STREET, DEL_POINT_ZIP, DEL_POINT_CITY, DEL_POINT_STATE, DEL_POINT_STREET2, DEL_POINT_COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESC, BU_CODE, BU_DESC, SCANSONDELIVERYNOTE)
as select
  plant.name PlantName, address.street plantstreet, address.zipcode plantzipcode, address.city plantcity, address.county plantcounty
, c2.description plantcountry_desc
, plant.email plantemail
, plant.website plantwebsite
,(select pc.phone from plantcompany pc where pc.code = (select min(pc.code) from plantcompany pc where pc.plant_id = plant.plant_id) and pc.plant_id = plant.plant_id) plantcompanyphone
, plant.phoneno plantphoneno, plant.faxno plantfaxno, address.state plantstate, CN.CONSIGNMENTNOTE_ID
, cn.consignmentnotenumber, cn.year ConsignmentNoteYear
, cn.week ConsignmentNoteWeek, route.routenumber, route.description routeDescription
, /*(select max(routestop.stopnumber) from routestop where cu.customer_id = routestop.customer_id and
routestop.route_id = route.route_id)*/ cn.stopnumber stopnumber
, cu.customernumber
, cu.name customerName, ads.street customerstreet, ads.street2 customerstreet2, ads.zipcode customerzipcode, ads.city customercity, ads.county customercounty, ads.state customerstate
, CN.DELIVERYDATE, cu.consignmentnotelevel -- check must be on department_link_id and deliverypoint_link_id
, 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, 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.county del_point_county
, d.departmentnumber, d.description departmentdesc
, bu.code BU_code, bu.description BU_desc, cu.scansondeliverynote
from
  ConsignmentNote cn
     left outer join route on cn.route_id = route.route_id
     left outer join department d on d.department_id = cn.department_link_id
     left outer join (deliverypoint dp left outer join address dp_addr on dp_addr.address_id = dp.deliveryaddress_id)
          on dp.deliverypoint_id = cn.deliverypoint_link_id
, businessunit bu, plant, address, address ads, customer cu-- , routestop
, country c2
where cn.businessunit_id = bu.businessunit_id
and bu.plant_id = plant.plant_id
and plant.address_id = address.address_id-- and cu.customer_id = routestop.customer_id
and plant.country_id = c2.country_id
and cn.customer_link_id = cu.customer_id
and cu.visitaddress_id = ads.address_id
and cu.consignmentnotelevel > 0

/
create or replace view V_CONSIGNMENTNOTE_EDE
 (PLANTNAME, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, CONSIGNMENTNOTE_ID, NOTENUMBER, WEEK, CONSIGNMENTNOTENUMBER, CONSIGNMENTNOTEYEAR, DAY_DESC, DEPNR, CONSIGNMENTNOTEWEEK, ROUTENUMBER, ROUTEDESCRIPTION, STOPNUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERSTREET, CUSTOMERSTREET2, CUSTOMERZIPCODE, CUSTOMERCITY, CUSTOMERSTATE, DELIVERYDATE, CONSIGNMENTNOTELEVEL, DEPARTMENT_LINK_ID, DELIVERYPOINT_LINK_ID, EXTERNALORDERNUMBER, DEL_POINT_CODE
, DEL_POINT_DESC, DEL_POINT_STREET, DEL_POINT_ZIP, DEL_POINT_CITY, DEL_POINT_STATE, DEL_POINT_STREET2, DEL_POINT_COUNTY, DEPARTMENTNUMBER, LAYOUTCODE, CONTAINERS, CONTAINERS_EMPTY, TOTALWEIGHT, LANGUAGECODE, LANGUAGE_ID, REPORTPARAM_ID, PACKINGNOTE_ID)
as select
  plant.name PlantName, address.street plantstreet, address.zipcode plantzipcode, address.city plantcity, address.state plantstate
, plant.phoneno plantphoneno, plant.faxno plantfaxno, CN.CONSIGNMENTNOTE_ID, pn.notenumber, pn.week,
 cn.consignmentnotenumber, cn.year ConsignmentNoteYear, ds.code day_desc, dept.departmentnumber depnr
, cn.week ConsignmentNoteWeek, route.routenumber, route.description routeDescription
, (select max(routestop.stopnumber) from routestop where cu.customer_id = routestop.customer_id and
routestop.route_id = route.route_id) stopnumber, cu.customernumber
, cu.legalname customerName, ads.street customerstreet, ads.street2 customerstreet2, ads.zipcode customerzipcode, ads.city customercity, 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, 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.county del_point_county
, (select d.departmentnumber from department d where d.department_id = cn.department_link_id) departmentnumber
, (select fl.code from FORMLAYOUT fl where cu.CONSIGNMENTNOTELAYOUT_ID = fl.FORMLAYOUT_ID) LAYOUTCODE
, (select count(pnc.packingnotecontainer_id)
  from packingnote pn, packingnotecontainer pnc
  where pn.consignmentnote_id = cn.consignmentnote_id
        and pn.packingnote_id = pnc.packingnote_id
        and pnc.grossweight - pnc.tareweight > 0) Containers
, (select count(pnc.packingnotecontainer_id)
  from packingnote pn, packingnotecontainer pnc
  where pn.consignmentnote_id = cn.consignmentnote_id
        and pn.packingnote_id = pnc.packingnote_id
        and pnc.grossweight - pnc.tareweight <= 0) Containers_empty
, (select sum(pnc.grossweight - pnc.tareweight)
  from packingnote pn, packingnotecontainer pnc
  where pn.consignmentnote_id = cn.consignmentnote_id
        and pn.packingnote_id = pnc.packingnote_id) totalweight
, lan.code Languagecode, lan.language_id, rp.reportparam_id, pn.packingnote_id
from
  ConsignmentNote cn
     left outer join route on cn.route_id = route.route_id
     left outer join (deliverypoint dp left outer join address dp_addr on dp_addr.address_id = dp.deliveryaddress_id)
          on dp.deliverypoint_id = cn.deliverypoint_link_id
       inner join packingnote pn on cn.consignmentnote_id=pn.consignmentnote_id
, businessunit bu, plant, address, address ads, customer cu
, languages lan, day_desc ds, distributionpoint distrp, department dept, reportparam rp
where cn.businessunit_id = bu.businessunit_id
and bu.plant_id = plant.plant_id
and plant.address_id = address.address_id
and cn.customer_link_id = cu.customer_id
and cu.visitaddress_id = ads.address_id
and cu.consignmentnotelevel > 0
and pn.daynumber=ds.day_id
and ds.language_id=lan.language_id
and pn.distributionpoint_id=distrp.distributionpoint_id
and distrp.department_id=dept.department_id
and rp.number_value=cn.consignmentnote_id

/
create or replace view V_CONSIGNMENTNOTE_FIS
 (PLANTNAME, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTPHONENO, PLANTFAXNO, CONSIGNMENTNOTE_ID, CONSIGNMENTNOTENUMBER, CONSIGNMENTNOTEYEAR, CONSIGNMENTNOTEWEEK, ROUTENUMBER, ROUTEDESCRIPTION, STOPNUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERSTREET, CUSTOMERZIPCODE, CUSTOMERCITY, DELIVERYDATE, CONSIGNMENTNOTELEVEL, DEPARTMENT_LINK_ID, DELIVERYPOINT_LINK_ID, EXTERNALORDERNUMBER, DEL_POINT_CODE, DEL_POINT_DESC, DEL_POINT_STREET, DEL_POINT_ZIP, DEL_POINT_CITY, DEL_POINT_STATE
, DEL_POINT_STREET2, DEL_POINT_COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESC, LANGCODE, CN_LAYOUT_CODE)
as select
  plant.name PlantName, address.street plantstreet, address.zipcode plantzipcode, address.city plantcity
, plant.phoneno plantphoneno, plant.faxno plantfaxno, CN.CONSIGNMENTNOTE_ID
, cn.consignmentnotenumber, cn.year ConsignmentNoteYear
, cn.week ConsignmentNoteWeek, route.routenumber, route.description routeDescription
, (select max(routestop.stopnumber) from routestop where cu.customer_id = routestop.customer_id and
routestop.route_id = route.route_id) stopnumber, cu.customernumber
, cu.legalname customerName, ads.street customerstreet, ads.zipcode customerzipcode, ads.city customercity
, CN.DELIVERYDATE, cu.consignmentnotelevel -- check must be on department_link_id and deliverypoint_link_id
, 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, 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.county del_point_county
, d.departmentnumber, d.description departmentdesc
, languages.code LANGCODE
, (select f.code from formlayout f where f.formlayout_id= cu.consignmentnotelayout_id) cn_layout_code
from
  ConsignmentNote cn
     left outer join route on cn.route_id = route.route_id
     left outer join department d on d.department_id = cn.department_link_id
     left outer join (deliverypoint dp left outer join address dp_addr on dp_addr.address_id = dp.deliveryaddress_id)
          on dp.deliverypoint_id = cn.deliverypoint_link_id
, businessunit bu, plant, address, address ads, customer cu-- , routestop
, languages
where cn.businessunit_id = bu.businessunit_id
and bu.plant_id = plant.plant_id
and plant.address_id = address.address_id
-- and cu.customer_id = routestop.customer_id
and cn.customer_link_id = cu.customer_id
and cu.visitaddress_id = ads.address_id
and cu.consignmentnotelevel > 0

/
create or replace view V_CONSIGNMENTNOTE_LLG
 (PLANTNAME, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTPHONENO, PLANTFAXNO, PLANTSTATE, CONSIGNMENTNOTE_ID, CONSIGNMENTNOTENUMBER, CONSIGNMENTNOTEYEAR, CONSIGNMENTNOTEWEEK, ROUTENUMBER, ROUTEDESCRIPTION, STOPNUMBER, CUSTOMERNUMBER, CUSTSEARCHNAME, CUSTOMERNAME, CUSTOMERLEGALNAME, CUSTOMERSTREET, CUSTOMERSTREET2, CUSTOMERZIPCODE, CUSTOMERCITY, CUSTOMERSTATE, DELIVERYDATE, CONSIGNMENTNOTELEVEL, DEPARTMENT_LINK_ID, DELIVERYPOINT_LINK_ID, EXTERNALORDERNUMBER, DEL_POINT_CODE
, DEL_POINT_DESC, DEL_POINT_STREET, DEL_POINT_ZIP, DEL_POINT_CITY, DEL_POINT_STATE, DEL_POINT_STREET2, DEL_POINT_COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESC, BU_CODE, BU_DESC, SCANSONDELIVERYNOTE, DELIVERYDAY_DESC)
as select
  plant.name PlantName, address.street plantstreet, address.zipcode plantzipcode, address.city plantcity
, plant.phoneno plantphoneno, plant.faxno plantfaxno, address.state plantstate, CN.CONSIGNMENTNOTE_ID
, cn.consignmentnotenumber, cn.year ConsignmentNoteYear
, cn.week ConsignmentNoteWeek, route.routenumber, route.description routeDescription
, cn.stopnumber stopnumber
, cu.customernumber
, CU.SEARCHNAME custsearchname, cu.name customername
, cu.legalname customerLegalName, ads.street customerstreet, ads.street2 customerstreet2, ads.zipcode customerzipcode, ads.city customercity, 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, 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.county del_point_county
, d.departmentnumber, d.description departmentdesc
, bu.code BU_code, bu.description BU_desc, cu.scansondeliverynote
, (SELECT substr(DD.DESCRIPTION, 1, 3) FROM DAY_DESC DD, day d WHERE DD.DAY_ID = d.day_id and d.daynumber = cn.daynumber AND DD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) DELIVERYDAY_DESC
from
  ConsignmentNote cn
     left outer join route on cn.route_id = route.route_id
     left outer join department d on d.department_id = cn.department_link_id
     left outer join (deliverypoint dp left outer join address dp_addr on dp_addr.address_id = dp.deliveryaddress_id)
          on dp.deliverypoint_id = cn.deliverypoint_link_id
, businessunit bu, plant, address, address ads, customer cu
, languages
where cn.businessunit_id = bu.businessunit_id
and bu.plant_id = plant.plant_id
and plant.address_id = address.address_id
and cn.customer_link_id = cu.customer_id
and cu.visitaddress_id = ads.address_id
and cu.consignmentnotelevel > 0

/
create or replace view V_CONSIGNMENTNOTE_LTS
 (PLANTNAME, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTPHONENO, PLANTFAXNO, PLANTSTATE, PLANTEMAIL, PLANTWEBSITE, VATPLANTCOMPANY, VATBU, CONSIGNMENTNOTE_ID, CONSIGNMENTNOTENUMBER, CONSIGNMENTNOTEYEAR, CONSIGNMENTNOTEWEEK, ROUTENUMBER, ROUTEDESCRIPTION, STOPNUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERSTREET, CUSTOMERZIPCODE, CUSTOMERCITY, CUSTOMERSTATE, DELIVERYDATE, CONSIGNMENTNOTELEVEL, DEPARTMENT_LINK_ID, DELIVERYPOINT_LINK_ID, EXTERNALORDERNUMBER, DEL_POINT_CODE
, DEL_POINT_DESC, DEL_POINT_STREET, DEL_POINT_ZIP, DEL_POINT_CITY, DEL_POINT_STATE, DEL_POINT_STREET2, DEL_POINT_COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESC, BU_CODE, BU_DESC, SCANSONDELIVERYNOTE, CUSTOMERLANGUAGECODE, ROUTELISTINSTRUCTIONS, DRIVINGDAYDESC, PURCHASEORDERNO)
as select
  plant.name PlantName, address.street plantstreet, address.zipcode plantzipcode, address.city plantcity
, plant.phoneno plantphoneno, plant.faxno plantfaxno, address.state plantstate, plant.email plantemail, plant.website plantwebsite
, (select max(pcy.vatnumber) from plantcompany pcy where plant.plant_id = pcy.plant_id) VATplantcompany
, bu.vatnumber VATbu
, CN.CONSIGNMENTNOTE_ID, cn.consignmentnotenumber, cn.year ConsignmentNoteYear
, cn.week ConsignmentNoteWeek, route.routenumber, route.description routeDescription
, (select max(routestop.stopnumber) from routestop where cu.customer_id = routestop.customer_id and
routestop.route_id = route.route_id) stopnumber, cu.customernumber
, cu.name customerName, ads.street customerstreet, ads.zipcode customerzipcode, ads.city customercity, 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, 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.county del_point_county
, d.departmentnumber, d.description departmentdesc
, bu.code BU_code, bu.description BU_desc, cu.scansondeliverynote
, (select lan.code from languages lan where cu.language_id = lan.language_id) customerlanguagecode
, (select max(dbms_lob.substr( rs.routelistinstructions)) from routestop rs where cu.customer_id = rs.customer_id and
rs.route_id = route.route_id) routelistinstructions
, (select dd.description from day_desc dd where dd.day_id = route.drivingday_id and dd.language_id = cu.language_id) drivingdaydesc
, (select cpc.purchaseorder
  from contractspercustomer cpc
  where cpc.contractspercustomer_id = (select max(cp.contractspercustomer_id )
                                       from contractspercustomer cp
                                       where cp.customer_id = cu.customer_id and trunc(sysdate) between cp.dateactive and cp.dateinactive )) purchaseorderno
from
  ConsignmentNote cn
     left outer join route on cn.route_id = route.route_id
     left outer join department d on d.department_id = cn.department_link_id
     left outer join (deliverypoint dp left outer join address dp_addr on dp_addr.address_id = dp.deliveryaddress_id)
          on dp.deliverypoint_id = cn.deliverypoint_link_id
, businessunit bu, plant, address, address ads, customer cu
where cn.businessunit_id = bu.businessunit_id
and bu.plant_id = plant.plant_id
and plant.address_id = address.address_id
and cn.customer_link_id = cu.customer_id
and cu.visitaddress_id = ads.address_id
and cu.consignmentnotelevel > 0

/
create or replace view V_CONSIGNMENTNOTE_PLS
 (PLANTNAME, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTEMAIL, PLANTPHONENO, PLANTFAXNO, PLANTSTATE, CONSIGNMENTNOTE_ID, CONSIGNMENTNOTENUMBER, CONSIGNMENTNOTEYEAR, CONSIGNMENTNOTEWEEK, ROUTENUMBER, ROUTEDESCRIPTION, STOPNUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERSTREET, CUSTOMERSTREET2, CUSTOMERZIPCODE, CUSTOMERCITY, CUSTOMERSTATE, DELIVERYDATE, CONSIGNMENTNOTELEVEL, DEPARTMENT_LINK_ID, DELIVERYPOINT_LINK_ID, EXTERNALORDERNUMBER, DEL_POINT_CODE, DEL_POINT_DESC
, DEL_POINT_STREET, DEL_POINT_ZIP, DEL_POINT_CITY, DEL_POINT_STATE, DEL_POINT_STREET2, DEL_POINT_COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESC, BU_CODE, BU_DESC, SCANSONDELIVERYNOTE)
as select
  plant.name PlantName, address.street plantstreet, address.zipcode plantzipcode, address.city plantcity
, plant.email plantemail, plant.phoneno plantphoneno, plant.faxno plantfaxno, address.state plantstate, CN.CONSIGNMENTNOTE_ID
, cn.consignmentnotenumber, cn.year ConsignmentNoteYear
, cn.week ConsignmentNoteWeek, route.routenumber, route.description routeDescription
, /*(select max(routestop.stopnumber) from routestop where cu.customer_id = routestop.customer_id and
routestop.route_id = route.route_id)*/ cn.stopnumber stopnumber
, cu.customernumber
, cu.name customerName, ads.street customerstreet, ads.street2 customerstreet2, ads.zipcode customerzipcode, ads.city customercity, ads.state customerstate
, CN.DELIVERYDATE, cu.consignmentnotelevel -- check must be on department_link_id and deliverypoint_link_id
, 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, 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.county del_point_county
, d.departmentnumber, d.description departmentdesc
, bu.code BU_code, bu.description BU_desc, cu.scansondeliverynote
from
  ConsignmentNote cn
     left outer join route on cn.route_id = route.route_id
     left outer join department d on d.department_id = cn.department_link_id
     left outer join (deliverypoint dp left outer join address dp_addr on dp_addr.address_id = dp.deliveryaddress_id)
          on dp.deliverypoint_id = cn.deliverypoint_link_id
, businessunit bu, plant, address, address ads, customer cu-- , routestop
where cn.businessunit_id = bu.businessunit_id
and bu.plant_id = plant.plant_id
and plant.address_id = address.address_id-- and cu.customer_id = routestop.customer_id
and cn.customer_link_id = cu.customer_id
and cu.visitaddress_id = ads.address_id
and cu.consignmentnotelevel > 0

/
create or replace view V_CONSIGNMENTNOTE_RAS
 (PLANTNAME, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTPHONENO, PLANTFAXNO, CONSIGNMENTNOTE_ID, CONSIGNMENTNOTENUMBER, CONSIGNMENTNOTEYEAR, CONSIGNMENTNOTEWEEK, ROUTENUMBER, ROUTEDESCRIPTION, STOPNUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERSTREET, CUSTOMERZIPCODE, CUSTOMERCITY, DELIVERYDATE, CONSIGNMENTNOTELEVEL, DEPARTMENT_LINK_ID, DELIVERYPOINT_LINK_ID, EXTERNALORDERNUMBER, DEL_POINT_CODE, DEL_POINT_DESC, DEL_POINT_STREET, DEL_POINT_ZIP, DEL_POINT_CITY, DEL_POINT_STATE
, DEL_POINT_STREET2, DEL_POINT_COUNTY, DEPARTMENTNUMBER, LAYOUTCODE, CONTAINERS, LANGUAGECODE, LANGUAGE_ID)
as select
  plant.name PlantName, address.street plantstreet, address.zipcode plantzipcode, address.city plantcity
, plant.phoneno plantphoneno, plant.faxno plantfaxno, CN.CONSIGNMENTNOTE_ID
, cn.consignmentnotenumber, cn.year ConsignmentNoteYear
, cn.week ConsignmentNoteWeek, route.routenumber, route.description routeDescription
, (select max(routestop.stopnumber) from routestop where cu.customer_id = routestop.customer_id and
routestop.route_id = route.route_id) stopnumber, cu.customernumber
, cu.name customerName, ads.street customerstreet, ads.zipcode customerzipcode, ads.city customercity
, CN.DELIVERYDATE, cu.consignmentnotelevel -- check must be on department_link_id and deliverypoint_link_id
, 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, 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.county del_point_county
--, d.departmentnumber, d.description departmentdesc
, (select d.departmentnumber from department d where d.department_id = cn.department_link_id) departmentnumber
, (select fl.code from FORMLAYOUT fl where cu.CONSIGNMENTNOTELAYOUT_ID = fl.FORMLAYOUT_ID) LAYOUTCODE
/*, (select count(coalesce( v3.CONTAINER_PRIMARYID, v3.CONTAINERTYPE_DESC, v3.CONTAINERTYPE_CODE))
  from v_consignmentdeliverynotes_ras v2, V_DELIVERYNOTE_KNT v3
  where cn.consignmentnotenumber = v2.consignmentnotenumber and v2.languagecode = lan.code and v2.ORIGIN <> 3
  and v2.packingnote_id = v3.packingnote_id and v3.LANGUAGECODE = lan.code ) Containers */
, (select count(packingnote.packingnote_id)
  from packingnote
  where packingnote.consignmentnote_id = cn.consignmentnote_id) Containers
, lan.code Languagecode, lan.language_id
from
  ConsignmentNote cn
     left outer join route on cn.route_id = route.route_id
     --left outer join department d on d.department_id = cn.department_link_id
     left outer join (deliverypoint dp left outer join address dp_addr on dp_addr.address_id = dp.deliveryaddress_id)
          on dp.deliverypoint_id = cn.deliverypoint_link_id
, businessunit bu, plant, address, address ads, customer cu-- , routestop
, languages lan
where cn.businessunit_id = bu.businessunit_id
and bu.plant_id = plant.plant_id
and plant.address_id = address.address_id
-- and cu.customer_id = routestop.customer_id
and cn.customer_link_id = cu.customer_id
and cu.visitaddress_id = ads.address_id
and cu.consignmentnotelevel > 0

/
create or replace view V_CONSIGNMENTNOTE_REF_LLG
 (REFERENCE, DELIVERYVARIATIONS_ID, ORIGIN, AMOUNT, CAUSENOTE_ID, REASONCODE_ID, SOILCOUNTSUBTYPE, UPDATERENTQTY, DV_SHORTAGE, DV_CAUSENOTEID, DV_DECREASED_SOIL, PACKINGNOTE_ID, PRODUCT_ID, SIZEDEFINITION_ID, FINISHINGMETHOD_ID, LANGUAGECODE, REASONCODE)
as select dv.reference,
       dv.deliveryvariations_id,
       dv.origin,
       dv.amount,
       dv.causenote_id,
       dv.reasoncode_id,
       dv.soilcountsubtype,
       dv.updaterentqty,
       coalesce((select sum(dv1.amount)
        from deliveryvariations dv1
        where dv1.causenote_id is not null
              and dv1.causenote_id = dv.packingnote_id
              and dv1.origin = 5
              and dv1.product_id = dv.product_id
              and dv1.sizedefinition_id = dv.sizedefinition_id
              and dv1.finishingmethod_id = dv.finishingmethod_id
              and dv1.deliverydate = dv.deliverydate
              and dv.reference = dv1.reference
              ),0) dv_shortage,
        coalesce((select dv1.causenote_id
        from deliveryvariations dv1
        where dv1.causenote_id is not null
              and dv1.causenote_id = dv.packingnote_id
              and dv1.origin = 5
              and dv1.product_id = dv.product_id
              and dv1.sizedefinition_id = dv.sizedefinition_id
              and dv1.finishingmethod_id = dv.finishingmethod_id
              and dv1.deliverydate = dv.deliverydate
              and dv.reference = dv1.reference
              ),0) dv_causenoteid,
        coalesce((select sum(dv1.amount)
        from deliveryvariations dv1
        where dv1.packingnote_id = dv.packingnote_id
              and dv1.origin in (3, 4, 5)
              and dv1.amount < 0
              and dv1.product_id = dv.product_id
              and dv1.sizedefinition_id = dv.sizedefinition_id
              and dv1.finishingmethod_id = dv.finishingmethod_id),0) dv_decreased_soil,
       pnl.packingnote_id,
       pnl.product_id,
       pnl.sizedefinition_id,
       pnl.finishingmethod_id,
       l.code languagecode,
       rc.code reasoncode
  from deliveryvariations dv left outer join reasoncode rc on dv.reasoncode_id=rc.reasoncode_id, packingnoteline pnl, languages l
 where dv.packingnote_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 not(dv.amount < 0 and dv.updaterentqty ='Y')
   and (
   ((dv.origin = 1 or (dv.origin =3 and rc.inventorytrigger=11))
     and
   (select sum(dv1.amount) from deliveryvariations dv1
         where dv1.packingnote_id = pnl.packingnote_id
   and dv1.product_id = pnl.product_id
   and dv1.sizedefinition_id = pnl.sizedefinition_id
   and dv1.finishingmethod_id = pnl.finishingmethod_id
    and  ((dv1.updaterentqty = 'Y' and dv1.amount<0 ) or dv1.origin = 1)
   )>0)
   or dv.origin <>1)
   and dv.amount > 0 --and dv.soilcountsubtype <> 5
   and (select plpd.adjustcircinventory
         from productlistperdistribpoint plpd
         where plpd.distributionpoint_id = (select pn.distributionpoint_id from packingnote pn where pn.packingnote_id = pnl.packingnote_id)
         and plpd.product_id = pnl.product_id
         and plpd.sizedefinition_id = pnl.sizedefinition_id
         and plpd.finishingmethod_id = pnl.finishingmethod_id
        ) = 0
   and (pnl.standardamount + pnl.variationamount - pnl.deliveredamount) = 0

/
create or replace view V_CONSIGNMENTNOTE_WMA
 (PLANTNAME, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTPHONENO, PLANTFAXNO, CONSIGNMENTNOTE_ID, CONSIGNMENTNOTENUMBER, CONSIGNMENTNOTEYEAR, CONSIGNMENTNOTEWEEK, ROUTENUMBER, ROUTEDESCRIPTION, STOPNUMBER, CUSTOMERNUMBER, EXTRANAME1, EXTRANAME2, CUSTOMERNAME, CUSTOMERSTREET, CUSTOMERZIPCODE, CUSTOMERCITY, DELIVERYDATE, CONSIGNMENTNOTELEVEL, DEPARTMENT_LINK_ID, DELIVERYPOINT_LINK_ID, EXTERNALORDERNUMBER, DEL_POINT_CODE, DEL_POINT_DESC, DEL_POINT_STREET, DEL_POINT_ZIP
, DEL_POINT_CITY, DEL_POINT_STATE, DEL_POINT_STREET2, DEL_POINT_COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESC, CURRENCY_CODE, CURRENCY_DESC, CURRENCY_EXCHANGERATE, CURRENCY_DECIMALS, CURRENCY_INVOICEAMOUNTDECIMALS)
as select
  plant.name PlantName, address.street plantstreet, address.zipcode plantzipcode, address.city plantcity
, plant.phoneno plantphoneno, plant.faxno plantfaxno, CN.CONSIGNMENTNOTE_ID
, cn.consignmentnotenumber, cn.year ConsignmentNoteYear
, cn.week ConsignmentNoteWeek, route.routenumber, route.description routeDescription
, (select max(routestop.stopnumber) from routestop where cu.customer_id = routestop.customer_id and
routestop.route_id = route.route_id) stopnumber, cu.customernumber
, cu.extraname1, cu.extraname2
, cu.legalname customerName, ads.street customerstreet, ads.zipcode customerzipcode, ads.city customercity
, CN.DELIVERYDATE, cu.consignmentnotelevel -- check must be on department_link_id and deliverypoint_link_id
, 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, 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.county del_point_county
, d.departmentnumber, d.description departmentdesc
, cy.code currency_code, cy.description currency_desc, cy.exchangerate currency_exchangerate
, cy.decimals currency_decimals, cy.invoiceamountdecimals currency_invoiceamountdecimals
from
  ConsignmentNote cn
     left outer join route on cn.route_id = route.route_id
     left outer join department d on d.department_id = cn.department_link_id
     left outer join (deliverypoint dp left outer join address dp_addr on dp_addr.address_id = dp.deliveryaddress_id)
          on dp.deliverypoint_id = cn.deliverypoint_link_id
, businessunit bu, plant, address, address ads, customer cu-- , routestop
, currency cy
where cn.businessunit_id = bu.businessunit_id
and bu.plant_id = plant.plant_id
and plant.address_id = address.address_id
-- and cu.customer_id = routestop.customer_id
and cn.customer_link_id = cu.customer_id
and cu.visitaddress_id = ads.address_id
and cu.consignmentnotelevel > 0
and cu.currency_id = cy.currency_id

/
create or replace view V_CONSINVHEADER_SMG
 (INVOICEDATE, INVOICEDATESTR, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, DELTOCUSTNOLEGALNAME, PASSERBYCUSTOMER, CITY, ZIPCODE, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, INVOICECOMMENTS, INVOICETYPE, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, STATUSTYPE, STATUSCODE, ROUTECONTROL_ID, INVOICEHEADER_ID
, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, INVOICECOPIES, INVOICELAYOUTCODE, TAXABLE, PAYMENTTERMS_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PARENTINVOICEHEADER_ID, CREDITSQUEEZEPERC, DELTOSTREET, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, PLANTCOUNTRYDESCRIPTION, ROUNDINGAMOUNT, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER
, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, INTERNALVATNUMBER, VATNUMBER, SETSPECIAL, DELTOCOUNTRYID, DELTOCOUNTRYJOURNCODE, BILLTOCOUNTRYCODE, BILLTOSENDINVOICETO, INVCOUNTRY_ID, INVBUCOJURNALCODE, COSTCENTERPONUMBER, INVLNTYPEFIRSTLINE, CUSTTYPE, BILTOCUSTVATNR, LEGALENTITY_LEGALNAME, PLANTLANGUAGE_ID, LEGALENTITY_ID, BILLTOCUSTOMER_LINK_ID, DELTOCUSTOMER_LINK_ID, PLANT_STREET, PLANT_STREET2, PLANT_ZIPCODE, PLANT_CITY, PLANT_STATE, PLANT_PHONENO
, PLANT_FAXNO, PLANT_WEBSITE, PLANT_EMAIL, TAXFULLFIMENTDATE)
as select a.invoicedate, to_char(a.invoicedate,'DD-MON-YYYY') invoicedatestr, a.invoicedaynumber,
       a.invoicenumber, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber,
      ( case when ((select c.sendinvoiceto from customer c  where c.customer_id=a.deltocustomer_link_id)=0) then  a.deltocustomername
       else  a.billtocustomername end) billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber,
       cast((a.deltocustomername) as varchar2(40)) deltocustomername,
       ( select c.customernumber|| ' ' ||c.legalname from customer c  where c.customer_id=a.deltocustomer_link_id) deltocustnolegalname,
       ( select c.passerbycustomer from customer c  where c.customer_id=a.deltocustomer_link_id) passerbycustomer,
       a.city, a.zipcode, a.street, a.routenumber, a.stopnumber,a.depotcode,a.invoicecomments,
       a.invoicetype,a.paythisamount, a.prebillamount, a.invoicefrequency_id invoicefrequencynumber,
       b.code currencycode,  s.statustype, s.code statuscode, a.routecontrol_id, a.invoiceheader_id,
       a.creditsqueezeamount, b.invoiceamountdecimals, b.description currencydescription, a.totalamountexclvat,
       b.decimals, ihextr.billtocountrydescription, ihextr.deltocountrydescription,
       ihextr.deltocustvatnumber,ihextr.invoicecopies,ihextr.formlayoutcode invoicelayoutcode,ihextr.taxable,ihextr.paymenttermsdescription paymentterms_desc,
       a.splitupcode, a.splitupdescription,
       a.parentinvoiceheader_id,
       a.creditsqueezeperc,  a.deltostreet,  a.deltocounty, a.deltocity, a.deltozipcode,country.description PLANTCOUNTRYDESCRIPTION,
       a.roundingamount,
       (select pldesc.invoiceremark from plantinvoiceremark_desc pldesc, customer deb, businessunit dbu where deb.customer_id = a.billtocustomer_link_id and dbu.businessunit_id = deb.defaultbusinessunit_id
        and pldesc.plant_id = dbu.plant_id and pldesc.language_id = deb.language_id ) GENERALINV_REMARK_PLANT
       , (case when ((select c.sendinvoiceto from customer c where a.deltocustomer_link_id = c.customer_id)=1)
   then (select deb.remark from customer deb where deb.customer_id = a.billtocustomer_link_id)
   else  (select deb.remark from customer deb where deb.customer_id = a.deltocustomer_link_id) end) GENERALINV_REMARK_CUSTOMER
       , p.invoiceremarkstartdate, p.invoiceremarkenddate
       , e.internalvatnumber, e.vatnumber,
 coalesce((select max(pa.packingnote_id) from packingnote pa, packingnoteline pl where pa.packingnote_id=pl.packingnote_id and pl.invoiceheader_id = a.invoiceheader_id and a.invoicefrequency_id = 0 and pa.origin = 5), 0) setspecial,       --0 is not based on special order, >0 is based on special order
(select co.country_id from country co, customer c
where a.deltocustomer_link_id=c.customer_id and c.country_id=co.country_id)deltocountryid
, (select co.journalcode from country co, customer c
where a.deltocustomer_link_id=c.customer_id and c.country_id=co.country_id)deltocountryJourncode
,(select co.code from country co, customer c
where a.billtocustomer_link_id=c.customer_id and c.country_id=co.country_id) billtocountrycode
,(select c.sendinvoiceto from customer c where a.deltocustomer_link_id = c.customer_id) billtosendinvoiceto
,country.country_id invcountry_id
,country.journalcode invbucoJurnalcode
,(select costc.ponumber from costcenter costc where costc.code = a.splitupcode and costc.customer_id = a.deltocustomer_link_id) costcenterponumber
,(select il.invoicelinetype_id from invoiceline il
         where il.invoiceline_id=(select min(il1.invoiceline_id) from invoiceline il1, invoiceheader ihe
               where il1.invoiceheader_id=ihe.invoiceheader_id  and ihe.parentinvoiceheader_id=a.parentinvoiceheader_id ))invlntypefirstline
, cast(F_GetCustType_smg(a.invoiceheader_id) as varchar2(10)) custtype
, (select deb.vatnumber from customer deb where deb.customer_id = a.billtocustomer_link_id) biltocustvatnr
, (select le.legalname from legalentity le where le.legalentity_id = e.legalentity_id) LegalEntity_LegalName
, p.language_id PlantLanguage_ID, e.legalentity_id, a.billtocustomer_link_id, a.deltocustomer_link_id
, pad.street plant_street, pad.street2 plant_street2, pad.zipcode plant_zipcode, pad.city plant_city
, pad.state plant_state, p.phoneno plant_phoneno, p.faxno plant_faxno, p.website plant_website, p.email plant_email
, case when country.code in ('CZ', 'PL') then a.invoicedate
       when country.code in ('RS', 'HR') then ihextr.paymenttermsduedate
       when country.code in ('SK') then a.enddate
       when country.code in ('HU') then
            case when (ihextr.paymenttermsduedate - a.invoicedate) > 60 then a.enddate
              else ihextr.paymenttermsduedate end
  else null end TaxFullfimentDate
from currency b, businessunit e, status s, plant p, country, invoiceheader a, invoiceheaderextrainfo ihextr, address pad
where a.currency_id = b.currency_id
      and a.documenttype = 1
      and a.invoicebusinessunit_id = e.businessunit_id
      and a.status_id = s.status_id
      and e.plant_id = p.plant_id
      and p.country_id = country.country_id
      and a.invoiceheader_id = ihextr.invoiceheader_id
      and pad.address_id = p.address_id

/
create or replace view V_CONSINVOICELINE1_SMG
 (PARENTINVOICEHEADER_ID, INVOICEHEADER_ID, INVOICELINE_ID, ITEM, CODE, QTY, PRICE, AMOUNT, DISCOUNTPERCENTAGE, PRODUCTGR_CODE, SIZECODE, FINISHINGMETHODCODE, FMPRICEFACTOR, YEAR, WEEK, QUANTITY, MAXILAWEEK, STARTWEEK, ENDWEEK, ENDWEEKDATE, STARTDATE, ENDDATE, WEEKSINYEAR, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, PRICEDECIMALS, INVOICEDECIMALS, CURRENCYCODE, DSFREQUENCY)
as select h.parentinvoiceheader_id, h.invoiceheader_id,l.invoiceline_id,
       l.description item,l.code, l.billedqty qty,
       l.price, l.amount amount, l.discountpercentage,
       (select pg.code from product pr, productgroup pg where lp.product_link_id = pr.product_id and pr.productgroup_id=pg.productgroup_id)   productgr_code,
       ( select  sd.code from sizedefinition sd where sd.sizedefinition_id=lp.sizedefinition_link_id) sizecode,
       (select fm.code from finishingmethod fm where lp.finishingmethod_id = fm.finishingmethod_id) finishingmethodcode,
       coalesce((select fm.pricefactor from finishingmethod fm where lp.finishingmethod_id = fm.finishingmethod_id),1) fmpricefactor,
        cri.year,cri.week,
      ( select sum(a.standardquantity) from costreportextrainfo a, invoiceline il
       where a.invoiceline_id=il.invoiceline_id and  il.invoiceheader_id=h.invoiceheader_id
       and il.invoiceline_id=l.invoiceline_id
       and a.year=cri.year and a.week=cri.week
       and il.invoicelinetype_id=1  group by h.invoiceheader_id ,a.invoiceline_id, cri.year,cri.week)
          quantity,
        cast(( select to_char(max(ild.year*100+ild.week)) from costreportinfo ild, invoiceline il, invoiceheader a
          where ild.invoiceline_id=il.invoiceline_id
          and il.invoiceheader_id=a.invoiceheader_id
          and a.parentinvoiceheader_id = pr.invoiceheader_id
          and il.invoicelinetype_id = 1)as varchar2(6)) maxilaweek,
      h.startweek, h.endweek, to_number(getweeknumber(h.enddate)) endweekdate,h.startdate,h.enddate,
      (case  when h.startyear <> 0 then getweeksinyear(h.startyear)
          else getweeksinyear(to_number(getyearasvarchar(h.invoicedate))) end) weeksinyear,
      h.startmonth, h.endmonth, h.startyear, h.endyear,
      (select c.decimals from currency c where h.currency_id=c.currency_id) pricedecimals,
      (select c.invoiceamountdecimals from currency c where h.currency_id=c.currency_id) invoicedecimals,
      (select c.code from currency c where h.currency_id=c.currency_id) currencycode,
      ( select ds.frequency from deliveryscheme ds where ds.code=lp.deliveryschemecode) dsfrequency
from   invoiceheader h,invoicelineproduct lp, invoiceline l, invoiceheader pr, costreportextrainfo cri
where  h.invoiceheader_id = l.invoiceheader_id
       and lp.invoiceline_id = l.invoiceline_id
       and l.invoiceline_id=cri.invoiceline_id
       and h.parentinvoiceheader_id = pr.invoiceheader_id
       and l.invoicelinetype_id=1 and l.invoicelinesubtype = 6  --  only rent underuse lines
group  by pr.invoiceheader_id,h.parentinvoiceheader_id,h.invoiceheader_id,h.invoicedate,l.invoiceline_id,l.code,l.billedqty ,l.amount, lp.product_link_id, lp.sizedefinition_link_id,
          lp.finishingmethod_id,lp.weighingcategory_link_id, h.billtocustomer_link_id, h.invoicebusinessunit_id,
          l.description, l.price,l.discountpercentage,cri.year, cri.week, h.startyear, h.endyear, h.startweek,
           h.endweek,h.startmonth, h.endmonth,h.enddate,h.startdate,h.startyear,h.currency_id,lp.deliveryschemecode
union
select h.parentinvoiceheader_id, h.invoiceheader_id,l.invoiceline_id,
       l.description item,l.code, l.billedqty qty,
       l.price, l.amount amount, l.discountpercentage,
       (select pg.code from product pr, productgroup pg where lp.product_link_id = pr.product_id and pr.productgroup_id=pg.productgroup_id)   productgr_code,
       ( select  sd.code from sizedefinition sd where sd.sizedefinition_id=lp.sizedefinition_link_id) sizecode,
       (select fm.code from finishingmethod fm where lp.finishingmethod_id = fm.finishingmethod_id) finishingmethodcode,
       coalesce((select fm.pricefactor from finishingmethod fm where lp.finishingmethod_id = fm.finishingmethod_id),1) fmpricefactor,
       cri.year,cri.week,
      ( select sum(a.quantity) from costreportinfo a, invoiceline il
       where a.invoiceline_id=il.invoiceline_id and  il.invoiceheader_id=h.invoiceheader_id
       and il.invoiceline_id=l.invoiceline_id
       and a.year=cri.year and a.week=cri.week
       and il.invoicelinetype_id=1  group by h.invoiceheader_id ,a.invoiceline_id, a.year,a.week)
          quantity,
        cast(( select to_char(max(ild.year*100+ild.week)) from costreportinfo ild, invoiceline il,invoiceheader a
          where ild.invoiceline_id=il.invoiceline_id
          and il.invoiceheader_id=a.invoiceheader_id
          and a.parentinvoiceheader_id = pr.invoiceheader_id
          and il.invoicelinetype_id = 1)as varchar2(6)) maxilaweek,
      h.startweek, h.endweek, to_number(getweeknumber(h.enddate)) endweekdate,h.startdate,h.enddate,
      (case  when h.startyear <> 0 then getweeksinyear(h.startyear)
          else getweeksinyear(to_number(getyearasvarchar(h.invoicedate))) end) weeksinyear,
      h.startmonth, h.endmonth, h.startyear, h.endyear,
      (select c.decimals from currency c where h.currency_id=c.currency_id) pricedecimals,
      (select c.invoiceamountdecimals from currency c where h.currency_id=c.currency_id) invoicedecimals,
      (select c.code from currency c where h.currency_id=c.currency_id) currencycode,
      ( select ds.frequency from deliveryscheme ds where ds.code=lp.deliveryschemecode) dsfrequency
from   invoiceheader h,invoicelineproduct lp, invoiceline l, invoiceheader pr, costreportinfo cri
where  h.invoiceheader_id = l.invoiceheader_id
       and lp.invoiceline_id = l.invoiceline_id
       and l.invoiceline_id=cri.invoiceline_id
       and h.parentinvoiceheader_id = pr.invoiceheader_id
       and l.invoicelinetype_id=1 and l.invoicelinesubtype <> 6  --  all rent excepts underuse
group  by pr.invoiceheader_id,h.parentinvoiceheader_id,h.invoiceheader_id,h.invoicedate,l.invoiceline_id,l.code,l.billedqty,l.amount, lp.product_link_id, lp.sizedefinition_link_id,
          lp.finishingmethod_id,lp.weighingcategory_link_id, h.billtocustomer_link_id, h.invoicebusinessunit_id,
          l.description, l.price,l.discountpercentage,cri.year, cri.week, h.startyear, h.endyear, h.startweek,
           h.endweek,h.startmonth, h.endmonth,h.enddate,h.startdate,h.startyear,h.currency_id,lp.deliveryschemecode
union
select  pr.invoiceheader_id,h.invoiceheader_id,l.invoiceline_id,
       l.description item,l.code, l.billedqty qty,
       l.price, l.amount amount, l.discountpercentage,
         (case
         when lp.product_link_id is not null then
            (select pg.code from product pr, productgroup pg where lp.product_link_id = pr.product_id and pr.productgroup_id=pg.productgroup_id)
       else
         coalesce((select pg.code from weighingcategory wg, productgroup pg where wg.weighingcategory_id=lp.weighingcategory_link_id
         and wg.legacyweighingcategorycode=pg.code),
         (select wg.code from weighingcategory wg where wg.weighingcategory_id=lp.weighingcategory_link_id),l.code)
       end) productgr_code,
       ( select  sd.code from sizedefinition sd where sd.sizedefinition_id=lp.sizedefinition_link_id) sizecode,
       (select fm.code from finishingmethod fm where lp.finishingmethod_id = fm.finishingmethod_id) finishingmethodcode,
      coalesce((select fm.pricefactor from finishingmethod fm where lp.finishingmethod_id = fm.finishingmethod_id),1) fmpricefactor,
       null year,null week
       ,null quantity,
        cast(( select to_char(max(ild.year*100+ild.week)) from costreportinfo ild, invoiceline il,invoiceheader a
          where ild.invoiceline_id=il.invoiceline_id
          and il.invoiceheader_id=a.invoiceheader_id
          and a.parentinvoiceheader_id = pr.invoiceheader_id
          and il.invoicelinetype_id = 1)as varchar2(6)) maxilaweek,
      h.startweek, h.endweek, to_number(getweeknumber(h.enddate)) endweekdate,h.startdate,h.enddate,
      (case  when h.startyear <> 0 then getweeksinyear(h.startyear)
          else getweeksinyear(to_number(getyearasvarchar(h.invoicedate))) end) weeksinyear,
      h.startmonth, h.endmonth, h.startyear, h.endyear,
      (select c.decimals from currency c where h.currency_id=c.currency_id) pricedecimals,
      (select c.invoiceamountdecimals from currency c where h.currency_id=c.currency_id) invoicedecimals,
      (select c.code from currency c where h.currency_id=c.currency_id) currencycode,
      null dsfrequency
from   invoiceheader h,invoicelineproduct lp, invoiceline l, invoiceheader pr
where  h.invoiceheader_id = l.invoiceheader_id
       and lp.invoiceline_id = l.invoiceline_id
       and l.invoicelinetype_id <> 1  --  all lines excepts rent
       and h.parentinvoiceheader_id = pr.invoiceheader_id
group  by pr.invoiceheader_id,h.parentinvoiceheader_id,h.invoiceheader_id,h.invoicedate,l.invoiceline_id,l.code,l.billedqty,l.amount , lp.product_link_id, lp.sizedefinition_link_id,
          lp.finishingmethod_id,lp.weighingcategory_link_id, h.billtocustomer_link_id, h.invoicebusinessunit_id,
          l.description, l.price,l.discountpercentage, h.startyear, h.endyear, h.startweek,
           h.endweek,h.startmonth, h.endmonth,h.enddate,h.startdate,h.startyear,h.currency_id

/
create or replace view V_CONSINVOICELINE2_SMG
 (INVOICELINETYPE, INVOICELINETYPEDESC, CODE, DESCRIPTION, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, SUBJECTTOMINIMUM, PERCENTAGE, LANGUAGECODE, PARENTINVOICEHEADER_ID, OVERAMOUNT, INVOICELINE_SEQUENCENUMBER, SUPRESSPRINTING, PRODGRCODE)
as select  a.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,
       a.description,
       a.extend,
       sum(a.amount) amount,
       a.discountpercentage,
       a.price,
       sum(a.billedqty) billedqty,
       a.subjecttominimum,
       c.percentage,
       LANGUAGES.CODE LANGUAGECODE,
       f.parentinvoiceheader_id,
       c.overamount,
       (SELECT pilt.sequencenumber
          from plantinvoicelinetype pilt
         where pilt.plant_id =bu.plant_id
           and pilt.invoicelinetype_id = a.invoicelinetype_id) InvoiceLine_SequenceNumber,
       (SELECT pilt.suppressprinting
          from plantinvoicelinetype pilt--, businessunit bu, invoiceheader h
         where pilt.plant_id =bu.plant_id
           and pilt.invoicelinetype_id = a.invoicelinetype_id) supressprinting --502161
     ,'' Prodgrcode
   from invoiceline a
   LEFT OUTER JOIN invoicelinevarious c ON (a.invoiceline_id = c.invoiceline_id)
   ,invoiceheader f, businessunit bu, LANGUAGES
 where a.invoiceheader_id = f.invoiceheader_id
   and f.invoicebusinessunit_id = bu.businessunit_id
   and f.parentinvoiceheader_id is not null
   and not exists( select b.invoiceline_id from invoicelineproduct b where a.invoiceline_id = b.invoiceline_id)
   and f.documenttype = 1
   and a.invoicelinetype_id <> 18
   group by  f.parentinvoiceheader_id,a.invoicelinetype_id,a.code,a.description,a.extend, a.discountpercentage,
       a.price,a.subjecttominimum,
       c.percentage, c.overamount,bu.plant_id,LANGUAGES.LANGUAGE_ID,LANGUAGES.CODE

/
create or replace view V_CONSINVOICE_CHILD_NLI
 (INVOICEHEADER_ID, INVOICENUMBER, PARENTINVOICEHEADER_ID, INVOICELINETYPE_ID, AMOUNT, PAYTHISAMOUNT, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, CURRENCYCODE, TAXGROUPCODE, IL_CHILD_TAXRATE)
as select
  ih_child.invoiceheader_id
, ih_child.invoicenumber
, ih_child.parentinvoiceheader_id
, il_child.invoicelinetype_id
, il_child.amount
, ih_child.paythisamount
, ih_child.deltocustomernumber
, ih_child.deltocustomername
, c.code currencycode
, il_child.taxgroupcode
, to_number((select tg.taxrate from turnovergroup tog, taxgroup tg where
                    il_child.turnovergroup_id = tog.turnovergroup_id and tog.taxgroup_id = tg.taxgroup_id
                     ),'9999.99') il_child_taxrate
from
 status
, invoiceheader ih_child
, invoiceline il_child
, currency c
where
ih_child.status_id = status.status_id
and status.statustype = 'IN'
and status.code = '2'
and ih_child.currency_id = c.currency_id
and ih_child.invoiceheader_id <> ih_child.parentinvoiceheader_id
and ih_child.parentinvoiceheader_id is not null
and il_child.invoiceheader_id = ih_child.invoiceheader_id

/
create or replace view V_CONSINVOICE_DNAPPENDIX_REO
 (INVOICEHEADER_ID, NOTENUMBER)
as select distinct ih.invoiceheader_id, pn.notenumber
from Packingnote pn, status statusPN, invoiceheader ih
     , Packingnoteline pnl
where pn.status_id = statusPN.status_id
    and statusPN.statustype = 'PN'
        and statusPN.code = '30'
and pnl.invoiceheader_id = ih.parentinvoiceheader_id
and pn.packingnote_id = pnl.packingnote_id

/
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_CONSOLCOSTREPORT_SNG
 (BILLTOCOUNTRYDESCRIPTION, PAYMENTTERMS_DESC, DELTOCUSTVATNUMBER, CONTACTPERSONNAME, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, ENDWEEK, ENDDATE, STARTWEEK, STARTDATE, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, CITY, ZIPCODE, STREET, DELTOSTREET, DELTOZIPCODE, DELTOCUSTOMERNAME, DELTOCUSTOMERNUMBER, DELTOCITY, HOUSENUMBER, HOUSENUMBEREXT, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL
, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, INVOICECOMMENTS, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, PREBILLAMOUNT, PURCHASEORDER, CURRENCYCODE, INVOICEAMOUNTDECIMALS, DECIMALS, COLLECTIONRESPEMPLOYEE, BILLTOLEGALNAME, INVOICEDATE, INVOICENUMBER, LINENUMBER, PARENTINVOICEHEADER_ID, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT
, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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)
as select ihtr.billtocountrydescription,
			 ihtr.paymenttermsdescription paymentterms_desc,
			 ihtr.deltocustvatnumber,
			 f.contactpersonname,
			 (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 = f.DELTOCUSTOMER_LINK_ID)) GENERALINV_REMARK_CUSTOMER,
       f.endweek, f.enddate, f.startweek, f.startdate,
       f.billtocustomernumber, f.billtocustomername, f.city, f.zipcode, f.street,
			 f.deltostreet, f.deltozipcode, f.deltocustomername, f.deltocustomernumber, f.deltocity,
			 f.housenumber, f.housenumberext,
			 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,
			 f.nextperiodstartdate, f.nextperiodenddate, f.nextperiodstartweek, f.nextperiodendweek,
			 f.invoicecomments, p.invoiceremarkstartdate, p.invoiceremarkenddate,
			 f.prebillamount, f.purchaseorder,
			 crr.code currencycode, crr.invoiceamountdecimals, crr.decimals,
			 (select empl.name from customerbillinginfo cbi, employee empl
          where cbi.customer_id = f.billtocustomer_link_id
                and empl.employee_id = cbi.collectionresponsible_id) collectionRespEmployee
       , (select bc.legalname from customer bc where f.billtocustomer_link_id = bc.customer_id) BillToLegalName,
       f.invoicedate, f.invoicenumber, a.linenumber, ih.parentinvoiceheader_id,
       (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.adjustmentpermited, 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
from   invoiceheader ih,
       invoiceheader f,
			 invoiceline a left outer join costcenterinvoiceline ccil on ccil.invoiceline_id = a.invoiceline_id
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, businessunit bu, plant p, address x, currency crr, invoiceheaderextrainfo ihtr
where  a.invoiceheader_id = f.invoiceheader_id
       and f.invoicebusinessunit_id = bu.businessunit_id
			 and f.currency_id = crr.currency_id
			 and bu.plant_id = p.plant_id
			 and p.address_id = x.address_id
			 and ihtr.invoiceheader_id = f.invoiceheader_id
and    f.parentinvoiceheader_id = ih.invoiceheader_id
and languages.language_id = (select cu.language_id from customer cu where cu.customer_id = ih.billtocustomer_link_id)
and    f.documenttype = 1

/
create or replace view V_CONSOLIDATEDINVOICE
 (INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOSTREET, DELTOSTREET2, DELTOCITY, DELTOCOUNTY, DELTOSTATE, DELTOZIPCODE, CREDITSQUEEZEPERC, NETPAYMENTDAYS, PAYMENTDISCOUNTDAYS, PLANTADDRESS, PLANTPHONE, PLANTCITY, PLANTSTATE, PLANTZIPCODE, CONTACTPERSONNAME, COSTCENTERCODE, CONTACTPERSONPHONE, STREET, STREET2, ZIPCODE, CITY, STATE, INVOICENUMBER, ACTIVITYREFERENCE, SEQ, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEDATE
, DELTOCUVATNUMBER, INVOICESTARTPERIOD, INVOICEENDPERIOD, PAYTHISAMOUNT, PREBILLAMOUNT, CREDITSQUEEZEAMOUNT, 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, DELTOCUSTLANG, PAYMENTTERMSDUEDATE, DISCOUNTDAYS, DISCOUNTDAYS2, PAYMENTDISCOUNT, PAYMENTDISCOUNT2, INVOICELAYOUTCODE, PLANTCODE, PURCHASEORDER, TOTALAMOUNTEXCLVAT)
as select
  ih.invoiceheader_id, ih.parentinvoiceheader_id, ih.billtocustomernumber, ih.billtocustomername, bill.extraname1, bill.extraname2,
  ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltocounty, ih.deltostate, ih.deltozipcode,
  ih.creditsqueezeperc, ih.netpaymentdays, ih.paymentdiscountdays,
     (select a.street from address a where a.address_id = p.address_id) plantaddress,
  p.phoneno plantphone,
  (select a.city from address a where a.address_id = p.address_id) plantcity,
  (select a.state from address a where a.address_id = p.address_id) plantstate,
  (select a.zipcode from address a where a.address_id = p.address_id) plantzipcode,
   ( 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
, ih.contactpersonphone, CONCATENATEWITHSIGN( ih.street, '   ', ih.street2) street, ih.street2, ih.zipcode, ih.city, ih.state
, ih.invoicenumber,ih.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, ih.invoicedate
, coalesce(dell.vatnumber, bill.vatnumber) DelToCuVatNumber
, coalesce((select invoiceheader.startdate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0 ), -- 0 means Direct invoice in invoicefrequency table
            (select invoiceheader.invoicedate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceStartPeriod
, coalesce((select invoiceheader.enddate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0  ),
            (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber < ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 ),
             (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber = ih.invoicenumber -- this is for the first record when invoiceheader.invoicenumber = ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceEndPeriod
, ih.paythisamount, ih.prebillamount, ih.creditsqueezeamount
, (select description from paymentterms_desc pdesc where pdesc.paymentterms_id = customerbillinginfo.paymentterms_id
and pdesc.language_id = coalesce(dell.language_id, bill.language_id)) paymenttermsDesc
, cast (customerbillingcomment.description as varchar2(30)) CustomerRelatedMessage, ih.invoicecomments GeneralInvoiceMessage
, case coalesce(customerbillingcomment.description, ' ')
       when coalesce(ih.invoicecomments, ' ') then 'Y' else 'N'
            end SuppressCustomerRelatedMessage
, currency.code currencyCode, currency.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 = customerbillinginfo.consolidatedinvoicelayout_id) CONS_INV_LAYOUT_CODE
, ih.nextperiodstartdate, ih.nextperiodenddate
, ih.splitupcode
, ih.splitupdescription
, (select languages.code from languages where languages.language_id = DELL.LANGUAGE_ID) deltocustlang
, ihextr.paymenttermsduedate
,ihextr.discountdays
,ihextr.discountdays2
,ihextr.paymentdiscount
,ihextr.paymentdiscount2
,ihextr.formlayoutcode invoicelayoutcode
,p.code plantcode
, ih.purchaseorder
, ih.totalamountexclvat
from
  invoiceheader ih
  left outer join
             ( customer dell left outer join customerbillingcomment
                                  on customerbillingcomment.customer_id = dell.customer_id
                                     and customerbillingcomment.type = 1 )
       on ih.deltocustomer_link_id = dell.customer_id
, customer bill, customerbillinginfo, status, currency
, businessunit b, plant p, country c, invoiceheaderextrainfo ihextr
where
    ih.billtocustomer_link_id = bill.customer_id
and bill.customer_id = customerbillinginfo.customer_id    -- and customerbillinginfo.consolidatedinvoice = 'Y'
and ih.status_id = status.status_id
    and status.statustype = 'IN'
    and status.code = '2'
and ih.parentinvoiceheader_id is not null
and ih.currency_id = currency.currency_id
and b.businessunit_id = ih.invoicebusinessunit_id
and b.plant_id = p.plant_id
and p.country_id = c.country_id
and ih.invoiceheader_id = ihextr.invoiceheader_id

/
create or replace view V_CONSOLIDATEDINVOICE_ANG
 (INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOSTREET, DELTOSTREET2, DELTOCITY, DELTOCOUNTY, DELTOSTATE, DELTOZIPCODE, CREDITSQUEEZEPERC, NETPAYMENTDAYS, PAYMENTDISCOUNTDAYS, REALCOLLECTIONTYPE, CONTACTPERSONNAME, CONTACTPERSONPHONE, STREET, STREET2, ZIPCODE, CITY, STATE, INVOICENUMBER, ACTIVITYREFERENCE, SEQ, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEDATE, DELTOCUVATNUMBER, INVOICESTARTPERIOD, INVOICEENDPERIOD
, PAYTHISAMOUNT, PREBILLAMOUNT, CREDITSQUEEZEAMOUNT, PAYMENTTERMSDESC, CUSTOMERRELATEDMESSAGE, GENERALINVOICEMESSAGE, SUPPRESSCUSTOMERRELATEDMESSAGE, CURRENCYCODE, INVOICEAMOUNTDECIMALS, INVOICETYPE, ROUNDINGAMOUNT, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, PLANTCOUNTRY_DESC, PAYMENTTYPE, INVOICEADDRESS_ID, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, PLANTCODE, PLANTNAME, PLANTSTREET
, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BANKACCOUNT, CONS_INV_LAYOUT_CODE, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, SPLITUPCODE, SPLITUPDESCRIPTION, DELTOCUSTLANG, PAYMENTTERMSDUEDATE, DISCOUNTDAYS, DISCOUNTDAYS2, PAYMENTDISCOUNT, PAYMENTDISCOUNT2, INVOICELAYOUTCODE, PURCHASEORDER, TOTALAMOUNTEXCLVAT, CLUSTERCODE)
as select
  ih.invoiceheader_id, ih.parentinvoiceheader_id, ih.billtocustomernumber, ih.billtocustomername, bill.extraname1, bill.extraname2,
  ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltocounty, ih.deltostate, ih.deltozipcode,
  ih.creditsqueezeperc, ih.netpaymentdays, ih.paymentdiscountdays, ih.realcollectiontype
, ( 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.contactpersonphone, --CONCATENATEWITHSIGN( ih.street, '   ', ih.street2)
 ih.street, ih.street2, ih.zipcode, ih.city, ih.state
, ih.invoicenumber,ih.activityreference, cast(GETSUBSTRING(ih.invoicenumber, -3) as varchar2(3)) Seq
, coalesce(ih.deltocustomernumber, ih.billtocustomernumber) deltocustomernumber
, coalesce(ih.deltocustomername, ih.billtocustomername) deltocustomername, ih.invoicedate
, coalesce(dell.vatnumber, bill.vatnumber) DelToCuVatNumber
, coalesce((select invoiceheader.startdate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0 ), -- 0 means Direct invoice in invoicefrequency table
            (select invoiceheader.invoicedate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceStartPeriod
, coalesce((select invoiceheader.enddate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0  ),
            (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber < ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 ),
             (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber = ih.invoicenumber -- this is for the first record when invoiceheader.invoicenumber = ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceEndPeriod
, ih.paythisamount, ih.prebillamount, ih.creditsqueezeamount
, (select description from paymentterms_desc pdesc where pdesc.paymentterms_id = customerbillinginfo.paymentterms_id
and pdesc.language_id = coalesce(dell.language_id, bill.language_id)) paymenttermsDesc
, customerbillingcomment.description CustomerRelatedMessage, ih.invoicecomments GeneralInvoiceMessage
, case coalesce(customerbillingcomment.description, ' ')
       when coalesce(ih.invoicecomments, ' ') then 'Y' else 'N'
            end SuppressCustomerRelatedMessage
, currency.code currencyCode, currency.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,
       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
, ihextr.bankaccount
, (select fl.code from formlayout fl where fl.formlayout_id = customerbillinginfo.consolidatedinvoicelayout_id) CONS_INV_LAYOUT_CODE
, ih.nextperiodstartdate, ih.nextperiodenddate
, ih.splitupcode
, ih.splitupdescription
, (select languages.code from languages where languages.language_id = DELL.LANGUAGE_ID) deltocustlang
, ihextr.paymenttermsduedate
, ihextr.discountdays
, ihextr.discountdays2
, ihextr.paymentdiscount
, ihextr.paymentdiscount2
, ihextr.formlayoutcode invoicelayoutcode
, ih.purchaseorder
, ih.totalamountexclvat
, (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
from
  invoiceheader ih
  left outer join
             ( customer dell left outer join customerbillingcomment
                                  on customerbillingcomment.customer_id = dell.customer_id
                                     and customerbillingcomment.type = 1 )
       on ih.deltocustomer_link_id = dell.customer_id
, customer bill, customerbillinginfo, status, currency
, businessunit b, plant p, address x, country c, invoiceheaderextrainfo ihextr
where
    ih.billtocustomer_link_id = bill.customer_id
and bill.customer_id = customerbillinginfo.customer_id    -- and customerbillinginfo.consolidatedinvoice = 'Y'
and ih.status_id = status.status_id
    and status.statustype = 'IN'
    and status.code = '2'
and ih.parentinvoiceheader_id is not null
and ih.currency_id = currency.currency_id
and b.businessunit_id = ih.invoicebusinessunit_id
and b.plant_id = p.plant_id
and p.address_id = x.address_id
and p.country_id = c.country_id
and ih.invoiceheader_id = ihextr.invoiceheader_id

/
create or replace view V_CONSOLIDATEDINVOICE_BHB
 (INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOSTREET, DELTOSTREET2, DELTOCITY, DELTOCOUNTY, DELTOSTATE, DELTOZIPCODE, CREDITSQUEEZEPERC, NETPAYMENTDAYS, PAYMENTDISCOUNTDAYS, CONTACTPERSONNAME, CONTACTPERSONPHONE, STREET, STREET2, ZIPCODE, CITY, STATE, INVOICENUMBER, ACTIVITYREFERENCE, SEQ, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEDATE, DELTOCUVATNUMBER, INVOICESTARTPERIOD, INVOICEENDPERIOD, PAYTHISAMOUNT
, PREBILLAMOUNT, CREDITSQUEEZEAMOUNT, 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, DELTOCUSTLANG, PAYMENTTERMSDUEDATE, INTERNALVATNUMBER, VATNUMBER, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, LNDRY_BANK_IDCODE, LNDRY_BANK_DESC, LNDRY_BANK_INTERNID, LNDRY_BANK_LNDRYBANKACCOUNT, LNDRY_BANK_IBANNO, INVOICEBUSINESSUNITDESC)
as select
  ih.invoiceheader_id, ih.parentinvoiceheader_id, ih.billtocustomernumber, CAST(ih.billtocustomername AS VARCHAR2(30)) billtocustomername, bill.extraname1, bill.extraname2,
  ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltocounty, ih.deltostate, ih.deltozipcode,
  ih.creditsqueezeperc, ih.netpaymentdays, ih.paymentdiscountdays
, ( 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.contactpersonphone, CONCATENATEWITHSIGN( ih.street, '   ', ih.street2) street, ih.street2, ih.zipcode, ih.city, ih.state
, ih.invoicenumber,ih.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, ih.invoicedate
, coalesce(dell.vatnumber, bill.vatnumber) DelToCuVatNumber
, coalesce((select invoiceheader.startdate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0 ), -- 0 means Direct invoice in invoicefrequency table
            (select invoiceheader.invoicedate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceStartPeriod
, coalesce((select invoiceheader.enddate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0  ),
            (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber < ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 ),
             (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber = ih.invoicenumber -- this is for the first record when invoiceheader.invoicenumber = ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceEndPeriod
, ih.paythisamount, ih.prebillamount, ih.creditsqueezeamount
, (select description from paymentterms_desc pdesc where pdesc.paymentterms_id = customerbillinginfo.paymentterms_id
and pdesc.language_id = coalesce(dell.language_id, bill.language_id)) paymenttermsDesc
, customerbillingcomment.description CustomerRelatedMessage, ih.invoicecomments GeneralInvoiceMessage
, case coalesce(customerbillingcomment.description, ' ')
       when coalesce(ih.invoicecomments, ' ') then 'Y' else 'N'
            end SuppressCustomerRelatedMessage
, currency.code currencyCode, currency.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 = customerbillinginfo.consolidatedinvoicelayout_id) CONS_INV_LAYOUT_CODE
, ih.nextperiodstartdate, ih.nextperiodenddate
, ih.splitupcode
, ih.splitupdescription
, (select languages.code from languages where languages.language_id = DELL.LANGUAGE_ID) deltocustlang
, ihextr.paymenttermsduedate
, b.internalvatnumber, b.vatnumber,p.code PlantCode
, p.name plantname, x.street plantstreet,x.street2 plantstreet2, x.zipcode plantzipcode, x.city plantcity
,p.phoneno plantphone
,p.faxno plantfax, p.website plantwebsite, p.email plantemail
,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,
b.DESCRIPTION invoicebusinessunitdesc
from
  invoiceheader ih
  left outer join
             ( customer dell left outer join customerbillingcomment
                                  on customerbillingcomment.customer_id = dell.customer_id
                                     and customerbillingcomment.type = 1 )
       on ih.deltocustomer_link_id = dell.customer_id
, customer bill, customerbillinginfo, status, currency
, businessunit b, plant p left outer join address x on p.address_id = x.address_id, country c, invoiceheaderextrainfo ihextr
        LEFT OUTER JOIN bankinstitution Lbank ON ihextr.laundrybankinstitution_id = Lbank.bankinstitution_id
where
    ih.billtocustomer_link_id = bill.customer_id
and bill.customer_id = customerbillinginfo.customer_id    -- and customerbillinginfo.consolidatedinvoice = 'Y'
and ih.status_id = status.status_id
    and status.statustype = 'IN'
    and status.code = '2'
and ih.parentinvoiceheader_id is not null
and ih.currency_id = currency.currency_id
and b.businessunit_id = ih.invoicebusinessunit_id
and b.plant_id = p.plant_id
and p.country_id = c.country_id
and ih.invoiceheader_id = ihextr.invoiceheader_id

/
create or replace view V_CONSOLIDATEDINVOICE_CBD
 (INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOSTREET, DELTOSTREET2, DELTOCITY, DELTOCOUNTY, DELTOSTATE, DELTOZIPCODE, CREDITSQUEEZEPERC, NETPAYMENTDAYS, PAYMENTDISCOUNTDAYS, CONTACTPERSONNAME, CONTACTPERSONPHONE, STREET, STREET2, ZIPCODE, CITY, STATE, INVOICENUMBER, ACTIVITYREFERENCE, SEQ, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEDATE, DELTOCUVATNUMBER, INVOICESTARTPERIOD, INVOICEENDPERIOD, PAYTHISAMOUNT
, PREBILLAMOUNT, CREDITSQUEEZEAMOUNT, 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, DELTOCUSTLANG, PAYMENTTERMSDUEDATE, BUDESCRIPTION, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTPHONENO, PLANTFAXNO, EMPLOYEENAME, EMPLOYEEPHONENO, EMPLOYEEMOBILENO, EMPLOYEEFAXNO, EMPLOYEEEMAIL, CUST_BANK_IDCODE, CUST_BANK_INTERNID, LNDRY_BANK_INTERNID, LNDRY_BANK_IBANNO, IBANNO, SALEAREA)
as select
  ih.invoiceheader_id, ih.parentinvoiceheader_id, ih.billtocustomernumber, ih.billtocustomername, bill.extraname1, bill.extraname2,
  ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltocounty, ih.deltostate, ih.deltozipcode,
  ih.creditsqueezeperc, ih.netpaymentdays, ih.paymentdiscountdays
, ( 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.contactpersonphone, ih.street, ih.street2, ih.zipcode, ih.city, ih.state
, ih.invoicenumber,ih.activityreference, cast(GETSUBSTRING(ih.invoicenumber, -3) as varchar2(3)) Seq
, coalesce(ih.deltocustomernumber, ih.billtocustomernumber )deltocustomernumber
, coalesce(ih.deltocustomername, ih.billtocustomername) deltocustomername, ih.invoicedate
, coalesce(dell.vatnumber, bill.vatnumber) DelToCuVatNumber
, ih.startdate InvoiceStartPeriod
, ih.enddate InvoiceEndPeriod
, ih.paythisamount, ih.prebillamount, ih.creditsqueezeamount
, (select description from paymentterms_desc pdesc where pdesc.paymentterms_id = customerbillinginfo.paymentterms_id
and pdesc.language_id = coalesce(dell.language_id, bill.language_id)) paymenttermsDesc
, customerbillingcomment.description CustomerRelatedMessage, ih.invoicecomments GeneralInvoiceMessage
, case coalesce(customerbillingcomment.description, ' ')
       when coalesce(ih.invoicecomments, ' ') then 'Y' else 'N'
            end SuppressCustomerRelatedMessage
, currency.code currencyCode, currency.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 = customerbillinginfo.consolidatedinvoicelayout_id) CONS_INV_LAYOUT_CODE
, ih.nextperiodstartdate, ih.nextperiodenddate
, ih.splitupcode
, ih.splitupdescription
, (select languages.code from languages where languages.language_id = DELL.LANGUAGE_ID) deltocustlang
, ihextr.paymenttermsduedate
, b.description budescription, p.code plantcode, p.name plantname
, p.website plantwebsite, p.email plantemail, plantaddress.street plantstreet
, plantaddress.zipcode plantzipcode, plantaddress.city plantcity, p.phoneno plantphoneno, p.faxno plantfaxno
, emp.name employeename, emp.phoneno employeephoneno, emp.mobileno employeemobileno, emp.faxno employeefaxno, emp.email employeeemail
, cbank.idcode cust_bank_idcode
, cbank.internalidcode cust_bank_internid
, lbank.internalidcode lndry_bank_internid
, lbank.ibanno lndry_bank_ibanno
, ihextr.ibanno
, Dell.Salesarea_Id Salearea
from
  invoiceheader ih
  left outer join customer dell
       left outer join customerbillingcomment on customerbillingcomment.customer_id = dell.customer_id and customerbillingcomment.type = 1
       left outer join employee emp on dell.serviceemployee_id = emp.employee_id
  on ih.deltocustomer_link_id = dell.customer_id
 -- left outer join brekd on ih.billtocustomernumber = brekd.customernumber
, customer bill, customerbillinginfo, status, currency
, businessunit b, plant p, address plantaddress, country c
, 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)
where
    ih.billtocustomer_link_id = bill.customer_id
and bill.customer_id = customerbillinginfo.customer_id    -- and customerbillinginfo.consolidatedinvoice = 'Y'
and ih.status_id = status.status_id
    and status.statustype = 'IN'
    and status.code = '2'
and ih.parentinvoiceheader_id is not null
and ih.currency_id = currency.currency_id
and b.businessunit_id = ih.invoicebusinessunit_id
and b.plant_id = p.plant_id
and p.country_id = c.country_id
and ih.invoiceheader_id = ihextr.invoiceheader_id
and p.address_id = plantaddress.address_id

/
create or replace view V_CONSOLIDATEDINVOICE_CVL
 (INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOSTREET, DELTOSTREET2, DELTOCITY, DELTOCOUNTY, DELTOSTATE, DELTOZIPCODE, CREDITSQUEEZEPERC, NETPAYMENTDAYS, PAYMENTDISCOUNTDAYS, CONTACTPERSONNAME, CONTACTPERSONPHONE, STREET, STREET2, ZIPCODE, CITY, STATE, INVOICENUMBER, SEQ, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEDATE, DELTOCUVATNUMBER, INVOICESTARTPERIOD, INVOICEENDPERIOD, PAYTHISAMOUNT, PREBILLAMOUNT, CREDITSQUEEZEAMOUNT
, PAYMENTTERMSDESC, CUSTOMERRELATEDMESSAGE, GENERALINVOICEMESSAGE, SUPPRESSCUSTOMERRELATEDMESSAGE, CURRENCYCODE, INVOICEAMOUNTDECIMALS, INVOICETYPE, ROUNDINGAMOUNT, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, PLANTCOUNTRY_DESC, TOTALAMOUNTEXCLVAT, MAX_VAT_PERC, TOTAL_OVERAMOUNT, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, INVCONSOLIDATEDLAYOUTCODE)
as select
  ih.invoiceheader_id, ih.parentinvoiceheader_id, ih.billtocustomernumber, ih.billtocustomername, ih.extraname1, ih.extraname2,
  ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltocounty, ih.deltostate, ih.deltozipcode,
  ih.creditsqueezeperc, ih.netpaymentdays, ih.paymentdiscountdays
, ( 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.contactpersonphone, ih.street, ih.street2, ih.zipcode, ih.city, ih.state
, ih.invoicenumber, cast(GETSUBSTRING(ih.invoicenumber, -3) as varchar2(3)) Seq
, coalesce(ih.deltocustomernumber, ih.billtocustomernumber )deltocustomernumber
, coalesce(ih.deltocustomername, ih.billtocustomername) deltocustomername, ih.invoicedate
, coalesce(dell.vatnumber, bill.vatnumber) DelToCuVatNumber
, coalesce((select invoiceheader.startdate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0 ), -- 0 means Direct invoice in invoicefrequency table
            (select invoiceheader.invoicedate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id = 0 ) ) InvoiceStartPeriod
, coalesce((select invoiceheader.enddate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0  ),
            (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber < ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 ),
             (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber = ih.invoicenumber -- this is for the first record when invoiceheader.invoicenumber = ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceEndPeriod
, ih.paythisamount, ih.prebillamount, ih.creditsqueezeamount
, (select description from paymentterms_desc pdesc where pdesc.paymentterms_id = customerbillinginfo.paymentterms_id
and pdesc.language_id = coalesce(dell.language_id, bill.language_id)) paymenttermsDesc
, customerbillingcomment.description CustomerRelatedMessage, ih.invoicecomments GeneralInvoiceMessage
, case coalesce(customerbillingcomment.description, ' ')
       when coalesce(ih.invoicecomments, ' ') then 'Y' else 'N'
            end SuppressCustomerRelatedMessage
, currency.code currencyCode, currency.invoiceamountdecimals, ih.invoicetype, IH.ROUNDINGAMOUNT
, ihextr.billtocountrydescription, ihextr.deltocountrydescription, c.description plantcountry_desc
, ih.totalamountexclvat
, (select max(ilv.percentage) from invoiceline il, invoicelinevarious ilv, invoicelinetype ilt
          where il.invoicelinetype_id = ilt.invoicelinetype_id and ilt.type = 18
                and il.invoiceline_id = ilv.invoiceline_id
                and il.invoiceheader_id = ih.invoiceheader_id) MAX_VAT_Perc
, (select SUM(ilv.overamount) from invoiceline il, invoicelinevarious ilv, invoicelinetype ilt
          where il.invoicelinetype_id = ilt.invoicelinetype_id and ilt.type = 18
                and il.invoiceline_id = ilv.invoiceline_id
                and il.invoiceheader_id = ih.invoiceheader_id) Total_OverAmount
, (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,
(select fl.code from formlayout fl where customerbillinginfo.consolidatedinvoicelayout_id = fl.formlayout_id ) invconsolidatedlayoutcode
from
  invoiceheader ih
  left outer join
             ( customer dell left outer join customerbillingcomment
                                  on customerbillingcomment.customer_id = dell.customer_id
                                     and customerbillingcomment.type = 1 )
       on ih.deltocustomer_link_id = dell.customer_id
, customer bill, customerbillinginfo
, status, currency
, businessunit b, plant p, country c, invoiceheaderextrainfo ihextr
where
    ih.billtocustomer_link_id = bill.customer_id
and bill.customer_id = customerbillinginfo.customer_id
    -- and customerbillinginfo.consolidatedinvoice = 'Y'
and ih.status_id = status.status_id
    and status.statustype = 'IN'
    and status.code = '2'
and ih.parentinvoiceheader_id is not null
and ih.currency_id = currency.currency_id
and b.businessunit_id = ih.invoicebusinessunit_id
and b.plant_id = p.plant_id
and p.country_id = c.country_id
and ih.invoiceheader_id = ihextr.invoiceheader_id

/
create or replace view V_CONSOLIDATEDINVOICE_DFD
 (INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOSTREET, DELTOSTREET2, DELTOCITY, DELTOCOUNTY, DELTOSTATE, DELTOZIPCODE, CREDITSQUEEZEPERC, NETPAYMENTDAYS, PAYMENTDISCOUNTDAYS, CONTACTPERSONNAME, CONTACTPERSONPHONE, STREET, STREET2, ZIPCODE, CITY, STATE, INVOICENUMBER, ACTIVITYREFERENCE, SEQ, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEDATE, DELTOCUVATNUMBER, INVOICESTARTPERIOD, INVOICEENDPERIOD, PAYTHISAMOUNT
, PREBILLAMOUNT, CREDITSQUEEZEAMOUNT, TOTALAMOUNTEXCLVAT, PAYMENTTERMSDESC, CUSTOMERRELATEDMESSAGE, GENERALINVOICEMESSAGE, SUPPRESSCUSTOMERRELATEDMESSAGE, CURRENCYCODE, INVOICEAMOUNTDECIMALS, INVOICETYPE, ROUNDINGAMOUNT, DELTOCOUNTRYCODE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, PLANTCOUNTRY_DESC, PAYMENTTYPE, INVOICEADDRESS_ID, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, BANKACCOUNT
, CONS_INV_LAYOUT_CODE, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, SPLITUPCODE, SPLITUPDESCRIPTION, DELTOCUSTLANG, PAYMENTTERMSDUEDATE, DISCOUNTDAYS, DISCOUNTDAYS2, PAYMENTDISCOUNT, PAYMENTDISCOUNT2, INVOICELAYOUTCODE, PLANTCODE, ACCEPTGIROCODELINE, DISCOUNTDESCMIN, DISCOUNTSAMOUNT, SPECIALCHARGESAMOUNT, TAXESAMOUNT, TAXESPERCENTAGE, AMOUNTBEFOREDISC)
as select
  ih.invoiceheader_id, ih.parentinvoiceheader_id, ih.billtocustomernumber, ih.billtocustomername, bill.extraname1, bill.extraname2,
  ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltocounty, ih.deltostate, ih.deltozipcode,
  ih.creditsqueezeperc, ih.netpaymentdays, ih.paymentdiscountdays
, ( 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.contactpersonphone, CONCATENATEWITHSIGN( ih.street, '   ', ih.street2) street, ih.street2, ih.zipcode, ih.city, ih.state
, ih.invoicenumber,ih.activityreference
, case
    when ih.parentinvoiceheader_id = ih.invoiceheader_id then '999'
    else cast(GETSUBSTRING(ih.invoicenumber, -3) as varchar2(3)) end Seq
, coalesce(ih.deltocustomernumber, ih.billtocustomernumber )deltocustomernumber
, coalesce(ih.deltocustomername, ih.billtocustomername) deltocustomername, ih.invoicedate
, coalesce(dell.vatnumber, bill.vatnumber) DelToCuVatNumber
, coalesce((select invoiceheader.startdate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0 ), -- 0 means Direct invoice in invoicefrequency table
            (select invoiceheader.invoicedate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceStartPeriod
, coalesce((select invoiceheader.enddate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0  ),
            (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber < ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 ),
             (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber = ih.invoicenumber -- this is for the first record when invoiceheader.invoicenumber = ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceEndPeriod
, ih.paythisamount, ih.prebillamount, ih.creditsqueezeamount
, ih.totalamountexclvat
, (select description from paymentterms_desc pdesc where pdesc.paymentterms_id = customerbillinginfo.paymentterms_id
and pdesc.language_id = coalesce(dell.language_id, bill.language_id)) paymenttermsDesc
, customerbillingcomment.description CustomerRelatedMessage, ih.invoicecomments GeneralInvoiceMessage
, case coalesce(customerbillingcomment.description, ' ')
       when coalesce(ih.invoicecomments, ' ') then 'Y' else 'N'
            end SuppressCustomerRelatedMessage
, currency.code currencyCode, currency.invoiceamountdecimals, ih.invoicetype, IH.ROUNDINGAMOUNT
, (select ct.code from country ct, customer c where ct.country_id = c.country_id and c.customer_id = ih.deltocustomer_link_id) deltocountrycode
, 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 = customerbillinginfo.consolidatedinvoicelayout_id) CONS_INV_LAYOUT_CODE
, ih.nextperiodstartdate, ih.nextperiodenddate
, ih.splitupcode
, ih.splitupdescription
, (select languages.code from languages where languages.language_id = DELL.LANGUAGE_ID) deltocustlang
, ihextr.paymenttermsduedate
,ihextr.discountdays
,ihextr.discountdays2
,ihextr.paymentdiscount
,ihextr.paymentdiscount2
,ihextr.formlayoutcode invoicelayoutcode
,p.code plantcode
, ihextr.acceptgirocodeline
, coalesce((select min(il.description)
            from invoiceline il, invoiceheader ihchild
            where il.invoiceheader_id = ihchild.invoiceheader_id
                  and ihchild.parentinvoiceheader_id = ih.invoiceheader_id and il.invoicelinetype_id = 16 and il.code like 'RA%'), 'Rabat') discountdescmin
, coalesce((select sum(il.amount)
            from invoiceline il, invoiceheader ihchild
            where il.invoiceheader_id = ihchild.invoiceheader_id
                  and ihchild.parentinvoiceheader_id = ih.invoiceheader_id and il.invoicelinetype_id = 16 and il.code like 'RA%'), 0 ) discountsamount
, coalesce((select sum(il.amount)
            from invoiceline il, invoiceheader ihchild
            where il.invoiceheader_id = ihchild.invoiceheader_id
                  and ihchild.parentinvoiceheader_id = ih.invoiceheader_id
                  and il.invoicelinetype_id = 16
                  and il.code in ('MILJO1','MILJO2','MILJO3','MILJO4','MILJO5','MILJO7','MILJO8','MILJO9')), 0 ) specialchargesamount
, coalesce((select sum(il.amount)
            from invoiceline il, invoiceheader ihchild
            where il.invoiceheader_id = ihchild.invoiceheader_id
                  and ihchild.parentinvoiceheader_id = ih.invoiceheader_id and il.invoicelinetype_id = 18), 0 ) taxesamount
, coalesce((select max(ilv.percentage)
            from invoiceline il, invoicelinevarious ilv, invoiceheader ihchild
            where il.invoiceheader_id = ihchild.invoiceheader_id
                  and ihchild.parentinvoiceheader_id = ih.invoiceheader_id and il.invoicelinetype_id = 18 and il.invoiceline_id = ilv.invoiceline_id), 0 ) taxespercentage
, coalesce((select sum(il.amount)
            from invoiceline il, invoiceheader ihchild
            where il.invoiceheader_id = ihchild.invoiceheader_id
                  and ihchild.parentinvoiceheader_id = ih.invoiceheader_id and il.invoicelinetype_id not in (16, 18)), 0) amountbeforedisc
from
  invoiceheader ih
  left outer join
             ( customer dell left outer join customerbillingcomment
                                  on customerbillingcomment.customer_id = dell.customer_id
                                     and customerbillingcomment.type = 1 )
       on ih.deltocustomer_link_id = dell.customer_id
, customer bill, customerbillinginfo, status, currency
, businessunit b, plant p, country c, invoiceheaderextrainfo ihextr
where
    ih.billtocustomer_link_id = bill.customer_id
and bill.customer_id = customerbillinginfo.customer_id    -- and customerbillinginfo.consolidatedinvoice = 'Y'
and ih.status_id = status.status_id
    and status.statustype = 'IN'
    and status.code = '2'
and ih.parentinvoiceheader_id is not null
and ih.currency_id = currency.currency_id
and b.businessunit_id = ih.invoicebusinessunit_id
and b.plant_id = p.plant_id
and p.country_id = c.country_id
and ih.invoiceheader_id = ihextr.invoiceheader_id

/
create or replace view V_CONSOLIDATEDINVOICE_ELI
 (INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOSTREET, DELTOSTREET2, DELTOCITY, DELTOCOUNTY, DELTOSTATE, DELTOZIPCODE, CREDITSQUEEZEPERC, NETPAYMENTDAYS, PAYMENTDISCOUNTDAYS, PLANTADDRESS, PLANTPHONE, PLANTFAX, PLANTCITY, PLANTSTATE, PLANTZIPCODE, CONTACTPERSONNAME, COSTCENTERCODE, CONTACTPERSONPHONE, STREET, STREET2, ZIPCODE, CITY, STATE, INVOICENUMBER, ACTIVITYREFERENCE, SEQ, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME
, INVOICEDATE, DELTOCUVATNUMBER, INVOICESTARTPERIOD, INVOICEENDPERIOD, PAYTHISAMOUNT, PREBILLAMOUNT, CREDITSQUEEZEAMOUNT, 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, DELTOCUSTLANG, PAYMENTTERMSDUEDATE, DISCOUNTDAYS, DISCOUNTDAYS2, PAYMENTDISCOUNT, PAYMENTDISCOUNT2, INVOICELAYOUTCODE, PLANTCODE, PURCHASEORDER, TOTALAMOUNTEXCLVAT, 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, CONTRACTCODE, CONTRACTSTARTDATE, CONTRACTENDDATE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, SALESPERSON)
as select
  ih.invoiceheader_id, ih.parentinvoiceheader_id, ih.billtocustomernumber, ih.billtocustomername, bill.extraname1, bill.extraname2,
  ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltocounty, ih.deltostate, ih.deltozipcode,
  ih.creditsqueezeperc, ih.netpaymentdays, ih.paymentdiscountdays,
  a.street plantaddress,
  p.phoneno plantphone, p.faxno plantfax,
  a.city plantcity,
  a.state plantstate,
  a.zipcode plantzipcode,
   ( 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
, ih.contactpersonphone, CONCATENATEWITHSIGN( ih.street, '   ', ih.street2) street, ih.street2, ih.zipcode, ih.city, ih.state
, ih.invoicenumber,ih.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, ih.invoicedate
, coalesce(dell.vatnumber, bill.vatnumber) DelToCuVatNumber
, coalesce((select invoiceheader.startdate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0 ), -- 0 means Direct invoice in invoicefrequency table
            (select invoiceheader.invoicedate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceStartPeriod
, coalesce((select invoiceheader.enddate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0  ),
            (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber < ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 ),
             (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber = ih.invoicenumber -- this is for the first record when invoiceheader.invoicenumber = ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceEndPeriod
, ih.paythisamount, ih.prebillamount, ih.creditsqueezeamount
, (select description from paymentterms_desc pdesc where pdesc.paymentterms_id = customerbillinginfo.paymentterms_id
and pdesc.language_id = coalesce(dell.language_id, bill.language_id)) paymenttermsDesc
, cast (customerbillingcomment.description as varchar2(30)) CustomerRelatedMessage, ih.invoicecomments GeneralInvoiceMessage
, case coalesce(customerbillingcomment.description, ' ')
       when coalesce(ih.invoicecomments, ' ') then 'Y' else 'N'
            end SuppressCustomerRelatedMessage
, currency.code currencyCode, currency.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 = customerbillinginfo.consolidatedinvoicelayout_id) CONS_INV_LAYOUT_CODE
, ih.nextperiodstartdate, ih.nextperiodenddate
, ih.splitupcode
, ih.splitupdescription
, (select languages.code from languages where languages.language_id = DELL.LANGUAGE_ID) deltocustlang
, ihextr.paymenttermsduedate
,ihextr.discountdays
,ihextr.discountdays2
,ihextr.paymentdiscount
,ihextr.paymentdiscount2
,ihextr.formlayoutcode invoicelayoutcode
,p.code plantcode
, ih.purchaseorder
, ih.totalamountexclvat,
 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.contractcode, ih.contractstartdate, ih.contractenddate
, b.code invoicebusinessunitcode, b.description invoicebusinessunitdesc
,      ( select emp.name from   employee emp
         where  emp.dateactive <= ih.invoicedate
            and (emp.dateinactive is null or emp.dateinactive > ih.invoicedate)
            and emp.employee_id in (select cpc.salesemployee_id from   contractspercustomer cpc
                                    where  cpc.customer_id = ih.billtocustomer_link_id
                                           and cpc.code = ih.contractcode)       ) SalesPerson
from
  invoiceheader ih
  left outer join
             ( customer dell left outer join customerbillingcomment
                                  on customerbillingcomment.customer_id = dell.customer_id
                                     and customerbillingcomment.type = 1 )
       on ih.deltocustomer_link_id = dell.customer_id
, customer bill, customerbillinginfo, status, currency
, businessunit b, plant p, address a, country c, 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)
where
    ih.billtocustomer_link_id = bill.customer_id
and bill.customer_id = customerbillinginfo.customer_id    -- and customerbillinginfo.consolidatedinvoice = 'Y'
and ih.status_id = status.status_id
    and status.statustype = 'IN'
    and status.code = '2'
and ih.parentinvoiceheader_id is not null
and ih.currency_id = currency.currency_id
and b.businessunit_id = ih.invoicebusinessunit_id
and b.plant_id = p.plant_id
and p.country_id = c.country_id
and ih.invoiceheader_id = ihextr.invoiceheader_id
and a.address_id = p.address_id

/
create or replace view V_CONSOLIDATEDINVOICE_LINE
 (INVOICEHEADER_ID, PERCENTAGE, INVOICELINETYPE, INVOICELINETYPEDESC, OVERAMOUNT, AMOUNT, LANGUAGECODE)
as select
  il.invoiceheader_id, ilv.percentage, ilt.type invoicelinetype
, ( SELECT DESCRIPTION FROM invoicelinetype_DESC iltdesc WHERE iltdesc.invoicelinetype_id = il.invoicelinetype_id
AND iltdesc.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) invoicelinetypedesc
, ilv.overamount, il.amount
, languages.code languageCode
from
  invoiceheader ih, invoiceline il, invoicelinevarious ilv, invoicelinetype ilt
, languages
where
    ih.parentinvoiceheader_id = il.invoiceheader_id
and ih.parentinvoiceheader_id = ih.invoiceheader_id
and ih.documenttype = 1
and il.invoiceline_id = ilv.invoiceline_id
and il.invoicelinetype_id = ilt.invoicelinetype_id

/
create or replace view V_CONSOLIDATEDINVOICE_LINE_ELI
 (INVOICEHEADER_ID, PERCENTAGE, INVOICELINETYPE, INVOICELINETYPEDESC, OVERAMOUNT, AMOUNT, LANGUAGECODE)
as select
  il.invoiceheader_id, ilv.percentage, ilt.type invoicelinetype
, ( SELECT DESCRIPTION FROM invoicelinetype_DESC iltdesc WHERE iltdesc.invoicelinetype_id = il.invoicelinetype_id
AND iltdesc.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) invoicelinetypedesc
, ilv.overamount, il.amount
, languages.code languageCode
from
  invoiceheader ih, invoiceline il, invoicelinevarious ilv, invoicelinetype ilt
, languages
where
    ih.parentinvoiceheader_id = il.invoiceheader_id
and ih.parentinvoiceheader_id = ih.invoiceheader_id
and ih.documenttype = 1
and il.invoiceline_id = ilv.invoiceline_id
and il.invoicelinetype_id = ilt.invoicelinetype_id

/
create or replace view V_CONSOLIDATEDINVOICE_LINE_NLI
 (INVOICEHEADER_ID, PERCENTAGE, INVOICELINETYPE, INVOICELINETYPEDESC, OVERAMOUNT, AMOUNT, LANGUAGECODE, IL_TAXRATE)
as select
  il.invoiceheader_id, ilv.percentage, ilt.type invoicelinetype
, ( SELECT DESCRIPTION FROM invoicelinetype_DESC iltdesc WHERE iltdesc.invoicelinetype_id = il.invoicelinetype_id
AND iltdesc.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) invoicelinetypedesc
, ilv.overamount, il.amount
, languages.code languageCode
, to_number((select tg.taxrate from turnovergroup tog, taxgroup tg where il.turnovergroup_id = tog.turnovergroup_id
                    and tog.taxgroup_id = tg.taxgroup_id))--,'9999.99')
il_taxrate
from
  invoiceheader ih, invoiceline il, invoicelinevarious ilv, invoicelinetype ilt
, languages
where
    ih.parentinvoiceheader_id = il.invoiceheader_id
and ih.parentinvoiceheader_id = ih.invoiceheader_id
and ih.documenttype = 1
and il.invoiceline_id = ilv.invoiceline_id
and il.invoicelinetype_id = ilt.invoicelinetype_id

/
create or replace view V_CONSOLIDATEDINVOICE_LLG
 (INVOICEFREQUENCYNUMBER, INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOSTREET, DELTOSTREET2, DELTOCITY, DELTOCOUNTY, DELTOSTATE, DELTOZIPCODE, CREDITSQUEEZEPERC, NETPAYMENTDAYS, PAYMENTDISCOUNTDAYS, CONTACTPERSONNAME, CONTACTPERSONPHONE, BILLTOSTREET, BILLTOSTREET2, BILLTOZIPCODE, CITY, BILLTOSTATE, INVOICENUMBER, ACTIVITYREFERENCE, SEQ, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEDATE, DELTOCUVATNUMBER, INVOICESTARTPERIOD
, INVOICEENDPERIOD, PAYTHISAMOUNT, PREBILLAMOUNT, CREDITSQUEEZEAMOUNT, 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, STARTDATE, ENDDATE, SPLITUPCODE, SPLITUPDESCRIPTION, DELTOCUSTLANG, PAYMENTTERMSDUEDATE, DISCOUNTDAYS, DISCOUNTDAYS2, PAYMENTDISCOUNT, PAYMENTDISCOUNT2, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, PURCHASEORDER, INVOICELAYOUTCODE, BILLTOSEARCHNAME, BILLTOLEGALNAME, BILLTOLEGACYCUSTNUMBER, BILLTOCHAINDESCR, IL_CHILD_BILLTOCUSTNUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, AMOUNT, LANGUAGECODE
, TOTALAMOUNTEXCLVAT)
as select ih.invoicefrequency_id invoicefrequencynumber,
  ih.invoiceheader_id, ih.parentinvoiceheader_id, ih.billtocustomernumber, ih.billtocustomername, bill.extraname1, bill.extraname2,
  ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltocounty, ih.deltostate, ih.deltozipcode,
  ih.creditsqueezeperc, ih.netpaymentdays, ih.paymentdiscountdays
, ( 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.contactpersonphone, ih.street billtostreet, ih.street2 billtostreet2, ih.zipcode billtozipcode, ih.city, ih.state billtostate
, ih.invoicenumber,ih.activityreference, cast(GETSUBSTRING(ih.invoicenumber, -3) as varchar2(3)) Seq
, coalesce(ih_child.deltocustomernumber, ih_child.billtocustomernumber )deltocustomernumber
, coalesce(ih_child.deltocustomername, ih_child.billtocustomername) deltocustomername, ih.invoicedate
, coalesce(dell.vatnumber, bill.vatnumber) DelToCuVatNumber
, coalesce((select invoiceheader.startdate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0 ), -- 0 means Direct invoice in invoicefrequency table
            (select invoiceheader.invoicedate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceStartPeriod
, coalesce((select invoiceheader.enddate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0  ),
            (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber < ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 ),
             (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber = ih.invoicenumber -- this is for the first record when invoiceheader.invoicenumber = ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceEndPeriod
, ih.paythisamount, ih.prebillamount, ih.creditsqueezeamount
, (select description from paymentterms_desc pdesc where pdesc.paymentterms_id = customerbillinginfo.paymentterms_id
and pdesc.language_id = coalesce(dell.language_id, bill.language_id)) paymenttermsDesc
, customerbillingcomment.description CustomerRelatedMessage, ih.invoicecomments GeneralInvoiceMessage
, case coalesce(customerbillingcomment.description, ' ')
       when coalesce(ih.invoicecomments, ' ') then 'Y' else 'N'
            end SuppressCustomerRelatedMessage
, currency.code currencyCode, currency.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 = customerbillinginfo.consolidatedinvoicelayout_id) CONS_INV_LAYOUT_CODE
, ih.nextperiodstartdate, ih.nextperiodenddate
, ih.startdate, ih.enddate
, ih.splitupcode
, ih.splitupdescription
, (select languages.code from languages where languages.language_id = DELL.LANGUAGE_ID) deltocustlang
, ihextr.paymenttermsduedate
, ihextr.discountdays
, ihextr.discountdays2
, ihextr.paymentdiscount
, ihextr.paymentdiscount2
, b.code invoicebusinessunitcode
, b.description invoicebusinessunitdesc
, ih.purchaseorder
, ihextr.formlayoutcode invoicelayoutcode
, (select c.searchname from customer c where c.customer_id = ih.billtocustomer_link_id) billtosearchname
, (select c.legalname from customer c where c.customer_id = ih.billtocustomer_link_id) billtolegalname
, (select c.legacycustomernumber from customer c where c.customer_id = ih.billtocustomer_link_id) billtolegacycustnumber
, (select ch.name from customer c, chain ch where ch.chain_id = c.chain_id and c.customer_id = ih.billtocustomer_link_id ) billtochaindescr
, ih_child.billtocustomernumber il_child_billtocustnumber
, (CASE WHEN ilt_child.TYPE = 1 AND il_child.invoicelinesubtype = 13
      THEN 1.6
      WHEN ilt_child.TYPE = 1 AND il_child.invoicelinesubtype = 8
        then 1.8  --corrections
      when ilt_child.type = 1 and il_child.invoicelinesubtype = 43
        then 1.43 --excess
      WHEN ilt_child.type = 1 AND il_child.invoicelinesubtype = 41
        then 1.41 --new loan
      WHEN ilt_child.type = 1 AND il_child.invoicelinesubtype = 42
        then 1.42 --outstanding loan
      ELSE ilt_child.TYPE
END)  invoicelinetype
, ( SELECT DESCRIPTION FROM invoicelinetype_DESC z WHERE z.invoicelinetype_id = il_child.invoicelinetype_id AND z.LANGUAGE_ID = l.LANGUAGE_ID) invoicelinetypedesc
, il_child.amount
, l.code languagecode
, ih.totalamountexclvat
from
  invoiceheader ih
  left outer join
             ( customer dell left outer join customerbillingcomment
                                  on customerbillingcomment.customer_id = dell.customer_id
                                     and customerbillingcomment.type = 1 )
       on ih.deltocustomer_link_id = dell.customer_id
, customer bill, customerbillinginfo, status, currency
, businessunit b, plant p, country c, invoiceheaderextrainfo ihextr
, invoiceheader ih_child
, invoiceline il_child
, invoicelinetype ilt_child
, languages l
where
    ih.billtocustomer_link_id = bill.customer_id
and bill.customer_id = customerbillinginfo.customer_id    -- and customerbillinginfo.consolidatedinvoice = 'Y'
and ih.status_id = status.status_id
    and status.statustype = 'IN'
    and status.code = '2'
and ih.parentinvoiceheader_id is not null
and ih.currency_id = currency.currency_id
and b.businessunit_id = ih.invoicebusinessunit_id
and b.plant_id = p.plant_id
and p.country_id = c.country_id
and ih.invoiceheader_id = ihextr.invoiceheader_id
and ih_child.parentinvoiceheader_id = ih.invoiceheader_id
and il_child.invoiceheader_id = ih_child.invoiceheader_id
and il_child.invoicelinetype_id = ilt_child.invoicelinetype_id

/
create or replace view V_CONSOLIDATEDINVOICE_LTS
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, HOUSENUMBER, HOUSENUMBEREXT, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS
, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL
, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, ADJUSTMENT_REASONCODE, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET
, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, COLLECTIONRESPEMPLOYEE
, DELTO_CONTACTPERSONNAME, CUSTOMER_LANGUAGECODE, BILLTOLEGALNAME)
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, a.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,
       0 housenumber, --send 0 so it will not appear double on the invoice
       a.housenumberext,
       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,
       p2.code plantcode, p2.name plantname, x.street plantstreet,x.street2 plantstreet2, x.zipcode plantzipcode,
       x.city plantcity, x.state plantstate, x.county plantcounty, p2.phoneno plantphone,
       p2.faxno plantfax, p2.website plantwebsite, p2.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,
       ihextr.billtocountrydescription, ihextr.deltocountrydescription,
       ihextr.deltocustvatnumber,
       ihextr.customermarkinggarment, ihextr.taxable, ihextr.siccode, ihextr.invoicecopies
       , ihextr.attachinvoicecopies, ihextr.paymenttermsdescription paymentterms_desc,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       rc.code Adjustment_ReasonCode
       , a.splitupcode, a.splitupdescription,
       ihs.personidentification, ihs.signature
       , 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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,
       a.nextperiodstartweek, a.nextperiodendweek,
       ihextr.paymenttype, ihextr.discountdays, ihextr.paymentdiscount, ihextr.discountdays2, ihextr.paymentdiscount2
       , cast(SS1.VALUE as numeric) WEIGHTDECIMALSMANUALINPUT
       , (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
       , (select empl.name from customerbillinginfo cbi, employee empl
          where cbi.customer_id = a.billtocustomer_link_id
                and empl.employee_id = cbi.collectionresponsible_id) collectionRespEmployee
, (select MIN(cp.name) from contactperson cp
   where cp.customer_id = a.deltocustomer_link_id
         and cp.contactpersonnumber = (select min(cpp.contactpersonnumber)
                                    from contactperson cpp where cpp.customer_id = a.deltocustomer_link_id)) delto_contactpersonname,
  lg.code customer_languagecode
, (select bc.legalname from customer bc where a.billtocustomer_link_id = bc.customer_id) BillToLegalName
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),
      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),
      customer cu, languages lg, plant p2
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 p2.address_id = x.address_id
      and p2.code = '07'
      and p.country_id = country.country_id
      and a.invoiceheader_id = ihextr.invoiceheader_id
      and a.deltocustomer_link_id = cu.customer_id
      and cu.language_id = lg.language_id

/
create or replace view V_CONSOLIDATEDINVOICE_MFM
 (INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOSTREET, DELTOSTREET2, DELTOCITY, DELTOCOUNTY, DELTOSTATE, DELTOZIPCODE, CREDITSQUEEZEPERC, NETPAYMENTDAYS, PAYMENTDISCOUNTDAYS, CONTACTPERSONNAME, CONTACTPERSONPHONE, STREET, STREET2, ZIPCODE, CITY, STATE, INVOICENUMBER, ACTIVITYREFERENCE, SEQ, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEDATE, DELTOCUVATNUMBER, INVOICESTARTPERIOD, INVOICEENDPERIOD, PAYTHISAMOUNT
, PREBILLAMOUNT, CREDITSQUEEZEAMOUNT, PAYMENTTERMSDESC, CUSTOMERRELATEDMESSAGE, GENERALINVOICEMESSAGE, SUPPRESSCUSTOMERRELATEDMESSAGE, CURRENCYCODE, INVOICEAMOUNTDECIMALS, INVOICETYPE, ROUNDINGAMOUNT, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, PAYMENTTYPE, INVOICEADDRESS_ID, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, BANKACCOUNT, CONS_INV_LAYOUT_CODE, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE
, SPLITUPCODE, SPLITUPDESCRIPTION, DELTOCUSTLANG, PAYMENTTERMSDUEDATE, DISCOUNTDAYS, DISCOUNTDAYS2, PAYMENTDISCOUNT, PAYMENTDISCOUNT2, INVOICELAYOUTCODE, INVOICEBUSINESSUNITCODE, INTERNALVATNUMBER, VATNUMBER, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, PLANTCOUNTRY, DEFPLANTDEPART, PURCHASEORDER, TOTALAMOUNTEXCLVAT, LNDRY_BANK_IDCODE, LNDRY_BANK_DESC, LNDRY_BANK_INTERNID
, LNDRY_BANK_LNDRYBANKACCOUNT, LNDRY_BANK_IBANNO)
as select
  ih.invoiceheader_id, ih.parentinvoiceheader_id, ih.billtocustomernumber, ih.billtocustomername, bill.extraname1, bill.extraname2,
  ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltocounty, ih.deltostate, ih.deltozipcode,
  ih.creditsqueezeperc, ih.netpaymentdays, ih.paymentdiscountdays
, ( 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.contactpersonphone, CONCATENATEWITHSIGN( ih.street, '   ', ih.street2) street, ih.street2, ih.zipcode, ih.city, ih.state
, ih.invoicenumber,ih.activityreference, cast(GETSUBSTRING(ih.invoicenumber, -3) as varchar2(3)) Seq
, coalesce(ih.deltocustomernumber, ih.billtocustomernumber )deltocustomernumber
, coalesce(ih.deltocustomername, ih.billtocustomername) deltocustomername, ih.invoicedate
, coalesce(dell.vatnumber, bill.vatnumber) DelToCuVatNumber
, coalesce((select invoiceheader.startdate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0 ), -- 0 means Direct invoice in invoicefrequency table
            (select invoiceheader.invoicedate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceStartPeriod
, coalesce((select invoiceheader.enddate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0  ),
            (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber < ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 ),
             (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber = ih.invoicenumber -- this is for the first record when invoiceheader.invoicenumber = ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceEndPeriod
, ih.paythisamount, ih.prebillamount, ih.creditsqueezeamount
, (select description from paymentterms_desc pdesc where pdesc.paymentterms_id = customerbillinginfo.paymentterms_id
and pdesc.language_id = coalesce(dell.language_id, bill.language_id)) paymenttermsDesc
, customerbillingcomment.description CustomerRelatedMessage, ih.invoicecomments GeneralInvoiceMessage
, /*case coalesce(customerbillingcomment.description, ' ')
       when coalesce(ih.invoicecomments, ' ') then 'Y' else 'N'
            end*/'Y' SuppressCustomerRelatedMessage
, currency.code currencyCode, currency.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 = customerbillinginfo.consolidatedinvoicelayout_id) CONS_INV_LAYOUT_CODE
, ih.nextperiodstartdate, ih.nextperiodenddate
, ih.splitupcode
, ih.splitupdescription
, (select languages.code from languages where languages.language_id = DELL.LANGUAGE_ID) deltocustlang
, ihextr.paymenttermsduedate
,ihextr.discountdays
,ihextr.discountdays2
,ihextr.paymentdiscount
,ihextr.paymentdiscount2
,ihextr.formlayoutcode invoicelayoutcode, b.code invoicebusinessunitcode, b.internalvatnumber, b.vatnumber
,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,
       (select c.description from country c where p.country_id = c.country_id) plantcountry,
       (select pd.description from plantdepartment pd, plant p2, businessunit bu2, customer c2
        where pd.plant_id = p2.plant_id and pd.defaultplantdepartment = 'Y'
        and p2.plant_id = bu2.plant_id
        and bu2.businessunit_id = c2.defaultbusinessunit_id
        and c2.customer_id = ih.billtocustomer_link_id) defplantdepart
, ih.purchaseorder
, ih.totalamountexclvat,
 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
  invoiceheader ih
  left outer join
             ( customer dell left outer join customerbillingcomment
                                  on customerbillingcomment.customer_id = dell.customer_id
                                     and customerbillingcomment.type = 1 )
       on ih.deltocustomer_link_id = dell.customer_id
, customer bill, customerbillinginfo, status, currency
, businessunit b, plant p, invoiceheaderextrainfo ihextr
        LEFT OUTER JOIN bankinstitution Lbank ON (ihextr.laundrybankinstitution_id = Lbank.bankinstitution_id)
, address x
where
    ih.billtocustomer_link_id = bill.customer_id
and bill.customer_id = customerbillinginfo.customer_id    -- and customerbillinginfo.consolidatedinvoice = 'Y'
and ih.status_id = status.status_id
    and status.statustype = 'IN'
    and status.code = '2'
and ih.parentinvoiceheader_id is not null
and ih.currency_id = currency.currency_id
and b.businessunit_id = ih.invoicebusinessunit_id
and b.plant_id = p.plant_id
and p.address_id = x.address_id
and ih.invoiceheader_id = ihextr.invoiceheader_id

/
create or replace view V_CONSOLIDATEDINVOICE_NAF
 (INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOSTREET, DELTOSTREET2, DELTOCITY, DELTOCOUNTY, DELTOSTATE, DELTOZIPCODE, CREDITSQUEEZEPERC, NETPAYMENTDAYS, PAYMENTDISCOUNTDAYS, CONTACTPERSONNAME, CONTACTPERSONPHONE, STREET, STREET2, ZIPCODE, CITY, STATE, INVOICENUMBER, ACTIVITYREFERENCE, SEQ, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEDATE, DELTOCUVATNUMBER, INVOICESTARTPERIOD, INVOICEENDPERIOD, PAYTHISAMOUNT
, PREBILLAMOUNT, CREDITSQUEEZEAMOUNT, 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, DELTOCUSTLANG, PAYMENTTERMSDUEDATE, DISCOUNTDAYS, DISCOUNTDAYS2, PAYMENTDISCOUNT, PAYMENTDISCOUNT2, INVOICELAYOUTCODE, PLANTCODE, PURCHASEORDER, TOTALAMOUNTEXCLVAT, DISCOUNTAMT)
as select
  ih.invoiceheader_id, ih.parentinvoiceheader_id, ih.billtocustomernumber, ih.billtocustomername, bill.extraname1, bill.extraname2,
  ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltocounty, ih.deltostate, ih.deltozipcode,
  ih.creditsqueezeperc, ih.netpaymentdays, ih.paymentdiscountdays
, ( 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.contactpersonphone, CONCATENATEWITHSIGN( ih.street, '   ', ih.street2) street, ih.street2, ih.zipcode, ih.city, ih.state
, ih.invoicenumber,ih.activityreference, cast(GETSUBSTRING(ih.invoicenumber, -3) as varchar2(3)) Seq
, coalesce(ih.deltocustomernumber, ih.billtocustomernumber )deltocustomernumber
, coalesce(ih.deltocustomername, ih.billtocustomername) deltocustomername, ih.invoicedate
, coalesce(dell.vatnumber, bill.vatnumber) DelToCuVatNumber
, coalesce((select invoiceheader.startdate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0 ), -- 0 means Direct invoice in invoicefrequency table
            (select invoiceheader.invoicedate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceStartPeriod
, coalesce((select invoiceheader.enddate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0  ),
            (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber < ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 ),
             (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber = ih.invoicenumber -- this is for the first record when invoiceheader.invoicenumber = ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceEndPeriod
, ih.paythisamount, ih.prebillamount, ih.creditsqueezeamount
, (select description from paymentterms_desc pdesc where pdesc.paymentterms_id = customerbillinginfo.paymentterms_id
and pdesc.language_id = coalesce(dell.language_id, bill.language_id)) paymenttermsDesc
, customerbillingcomment.description CustomerRelatedMessage, ih.invoicecomments GeneralInvoiceMessage
, case coalesce(customerbillingcomment.description, ' ')
       when coalesce(ih.invoicecomments, ' ') then 'Y' else 'N'
            end SuppressCustomerRelatedMessage
, currency.code currencyCode, currency.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 = customerbillinginfo.consolidatedinvoicelayout_id) CONS_INV_LAYOUT_CODE
, ih.nextperiodstartdate, ih.nextperiodenddate
, ih.splitupcode
, ih.splitupdescription
, (select languages.code from languages where languages.language_id = DELL.LANGUAGE_ID) deltocustlang
, ihextr.paymenttermsduedate
,ihextr.discountdays
,ihextr.discountdays2
,ihextr.paymentdiscount
,ihextr.paymentdiscount2
,ihextr.formlayoutcode invoicelayoutcode
,p.code plantcode
, ih.purchaseorder
, ih.totalamountexclvat
, case when ih.invoiceheader_id = ih.parentinvoiceheader_id then 0
 else (select sum(il.amount) from invoiceline il where il.invoiceheader_id = ih.invoiceheader_id and il.invoicelinetype_id = 16 and il.billedqty = 0 )
 end DiscountAmt
from
  invoiceheader ih
  left outer join
             ( customer dell left outer join customerbillingcomment
                                  on customerbillingcomment.customer_id = dell.customer_id
                                     and customerbillingcomment.type = 1 )
       on ih.deltocustomer_link_id = dell.customer_id
, customer bill, customerbillinginfo, status, currency
, businessunit b, plant p, country c, invoiceheaderextrainfo ihextr
where
    ih.billtocustomer_link_id = bill.customer_id
and bill.customer_id = customerbillinginfo.customer_id    -- and customerbillinginfo.consolidatedinvoice = 'Y'
and ih.status_id = status.status_id
    and status.statustype = 'IN'
    and status.code = '2'
and ih.parentinvoiceheader_id is not null
and ih.currency_id = currency.currency_id
and b.businessunit_id = ih.invoicebusinessunit_id
and b.plant_id = p.plant_id
and p.country_id = c.country_id
and ih.invoiceheader_id = ihextr.invoiceheader_id

/
create or replace view V_CONSOLIDATEDINVOICE_PHS
 (INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOSTREET, DELTOSTREET2, DELTOCITY, DELTOCOUNTY, DELTOSTATE, DELTOZIPCODE, CREDITSQUEEZEPERC, NETPAYMENTDAYS, PAYMENTDISCOUNTDAYS, CONTACTPERSONNAME, CONTACTPERSONPHONE, STREET, STREET2, ZIPCODE, CITY, STATE, INVOICENUMBER, SEQ, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEDATE, DELTOCUVATNUMBER, INVOICESTARTPERIOD, INVOICEENDPERIOD, PAYTHISAMOUNT, PREBILLAMOUNT, CREDITSQUEEZEAMOUNT
, 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, DELTOCUSTLANG, PURCHASEORDER)
as select
  ih.invoiceheader_id, ih.parentinvoiceheader_id, ih.billtocustomernumber, ih.billtocustomername, ih.extraname1, ih.extraname2,
  ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltocounty, ih.deltostate, ih.deltozipcode,
  ih.creditsqueezeperc, ih.netpaymentdays, ih.paymentdiscountdays
, ( 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.contactpersonphone, CONCATENATEWITHSIGN( ih.street, '   ', ih.street2) street, ih.street2, ih.zipcode, ih.city, ih.state
, ih.invoicenumber, cast(GETSUBSTRING(ih.invoicenumber, -3) as varchar2(3)) Seq
, coalesce(ih.deltocustomernumber, ih.billtocustomernumber )deltocustomernumber
, coalesce(ih.deltocustomername, ih.billtocustomername) deltocustomername, ih.invoicedate
, coalesce(dell.vatnumber, bill.vatnumber) DelToCuVatNumber
, coalesce((select invoiceheader.startdate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0 ), -- 0 means Direct invoice in invoicefrequency table
            (select invoiceheader.invoicedate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceStartPeriod
, coalesce((select invoiceheader.enddate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0  ),
            (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber < ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 ),
             (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber = ih.invoicenumber -- this is for the first record when invoiceheader.invoicenumber = ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceEndPeriod
, ih.paythisamount, ih.prebillamount, ih.creditsqueezeamount
, (select description from paymentterms_desc pdesc where pdesc.paymentterms_id = customerbillinginfo.paymentterms_id
and pdesc.language_id = coalesce(dell.language_id, bill.language_id)) paymenttermsDesc
, customerbillingcomment.description CustomerRelatedMessage, ih.invoicecomments GeneralInvoiceMessage
, case coalesce(customerbillingcomment.description, ' ')
       when coalesce(ih.invoicecomments, ' ') then 'Y' else 'N'
            end SuppressCustomerRelatedMessage
, currency.code currencyCode, currency.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 = customerbillinginfo.consolidatedinvoicelayout_id) CONS_INV_LAYOUT_CODE
, ih.nextperiodstartdate, ih.nextperiodenddate
, ih.splitupcode
, ih.splitupdescription
, (select languages.code from languages where languages.language_id = DELL.LANGUAGE_ID) deltocustlang
, ih.purchaseorder
from
  invoiceheader ih
  left outer join
             ( customer dell left outer join customerbillingcomment
                                  on customerbillingcomment.customer_id = dell.customer_id
                                     and customerbillingcomment.type = 1 )
       on ih.deltocustomer_link_id = dell.customer_id
, customer bill, customerbillinginfo, status, currency
, businessunit b, plant p, country c, invoiceheaderextrainfo ihextr
where
    ih.billtocustomer_link_id = bill.customer_id
and bill.customer_id = customerbillinginfo.customer_id    -- and customerbillinginfo.consolidatedinvoice = 'Y'
and ih.status_id = status.status_id
    and status.statustype = 'IN'
    and status.code = '2'
and ih.parentinvoiceheader_id is not null
and ih.currency_id = currency.currency_id
and b.businessunit_id = ih.invoicebusinessunit_id
and b.plant_id = p.plant_id
and p.country_id = c.country_id
and ih.invoiceheader_id = ihextr.invoiceheader_id

/
create or replace view V_CONSOLIDATEDINVOICE_REO
 (INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOSTREET, DELTOSTREET2, DELTOCITY, DELTOCOUNTY, DELTOSTATE, DELTOZIPCODE, CREDITSQUEEZEPERC, NETPAYMENTDAYS, PAYMENTDISCOUNTDAYS, CONTACTPERSONNAME, CONTACTPERSONPHONE, STREET, STREET2, ZIPCODE, CITY, STATE, INVOICENUMBER, SEQ, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEDATE, DELTOCUVATNUMBER, INVOICESTARTPERIOD, INVOICEENDPERIOD, PAYTHISAMOUNT, PREBILLAMOUNT, CREDITSQUEEZEAMOUNT
, 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, TOTALAMOUNTEXCLVAT, MAX_PERCENTAGE, VAT_AMOUNT
, INTERNALVATNUMBER, VATNUMBER, SPLITUPCODE, SPLITUPDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, LNDRY_BANK_IDCODE, LNDRY_BANK_DESC, LNDRY_BANK_INTERNID, LNDRY_BANK_LNDRYBANKACCOUNT, LNDRY_BANK_IBANNO, ACCEPTGIROLINE, ACCEPTGIROREF, SERVICEEMPLOYEE)
as select
  ih.invoiceheader_id, ih.parentinvoiceheader_id, ih.billtocustomernumber, ih.billtocustomername, ih.extraname1, ih.extraname2,
  ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltocounty, ih.deltostate, ih.deltozipcode,
  ih.creditsqueezeperc, ih.netpaymentdays, ih.paymentdiscountdays
, ( 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.contactpersonphone, CONCATENATEWITHSIGN( ih.street, '   ', ih.street2) street, ih.street2, ih.zipcode, ih.city, ih.state
, ih.invoicenumber, cast(GETSUBSTRING(ih.invoicenumber, -3) as varchar2(3)) Seq
, coalesce(ih.deltocustomernumber, ih.billtocustomernumber )deltocustomernumber
, coalesce(ih.deltocustomername, ih.billtocustomername) deltocustomername, ih.invoicedate
, coalesce(dell.vatnumber, bill.vatnumber) DelToCuVatNumber
, coalesce((select invoiceheader.startdate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0 ), -- 0 means Direct invoice in invoicefrequency table
            (select invoiceheader.invoicedate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id = 0 ) ) InvoiceStartPeriod
, coalesce((select invoiceheader.enddate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0  ),
            (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber < ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 ),
             (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber = ih.invoicenumber -- this is for the first record when invoiceheader.invoicenumber = ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceEndPeriod
, ih.paythisamount, ih.prebillamount, ih.creditsqueezeamount
, (select description from paymentterms_desc pdesc where pdesc.paymentterms_id = customerbillinginfo.paymentterms_id
and pdesc.language_id = coalesce(dell.language_id, bill.language_id)) paymenttermsDesc
, customerbillingcomment.description CustomerRelatedMessage, ih.invoicecomments GeneralInvoiceMessage
, case coalesce(customerbillingcomment.description, ' ')
       when coalesce(ih.invoicecomments, ' ') then 'Y' else 'N'
            end SuppressCustomerRelatedMessage
, currency.code currencyCode, currency.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 = customerbillinginfo.consolidatedinvoicelayout_id) cons_inv_layout_code
, ih.totalamountexclvat
, coalesce((select max(ilv.percentage) from invoiceline il, invoicelinevarious ilv where
  il.invoiceheader_id = ih.parentinvoiceheader_id and il.invoiceline_id = ilv.invoiceline_id), 0) max_percentage
, coalesce((select SUM(il.amount) from invoiceline il where
  il.invoiceheader_id = ih.parentinvoiceheader_id), 0) VAT_AMOUNT
, b.internalvatnumber, b.vatnumber, ih.splitupcode, ih.splitupdescription, 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,
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,
cast(ihextr.acceptgirocodeline as varchar(60)) acceptgiroline
,cast(ihextr.acceptgiroreference as varchar(60)) acceptgiroref
,( select emp.name
   from   employee emp
   where  emp.employee_id = ( select btc.serviceemployee_id
                              from   customer btc
                              where  btc.customer_id = ( select cl.customer_id
                                                         from   customer_link cl
                                                         where  cl.customer_link_id = ih.billtocustomer_link_id )
                            )
 ) serviceemployee
from
  invoiceheader ih
  left outer join
             ( customer dell left outer join customerbillingcomment
                                  on customerbillingcomment.customer_id = dell.customer_id
                                     and customerbillingcomment.type = 1 )
       on ih.deltocustomer_link_id = dell.customer_id
, customer bill, customerbillinginfo
, status, currency
, businessunit b, plant p, address x, country c, invoiceheaderextrainfo ihextr
        LEFT OUTER JOIN bankinstitution Lbank ON ihextr.laundrybankinstitution_id = Lbank.bankinstitution_id
where
    ih.billtocustomer_link_id = bill.customer_id
and bill.customer_id = customerbillinginfo.customer_id
    -- and customerbillinginfo.consolidatedinvoice = 'Y'
and ih.status_id = status.status_id
    and status.statustype = 'IN'
    and status.code = '2'
and ih.parentinvoiceheader_id is not null
and ih.currency_id = currency.currency_id
and b.businessunit_id = ih.invoicebusinessunit_id
and b.plant_id = p.plant_id
and p.country_id = c.country_id
and ih.invoiceheader_id = ihextr.invoiceheader_id
and p.address_id=x.address_id

/
create or replace view V_CONSOLIDATEDINVOICE_REV
 (INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOSTREET, DELTOSTREET2, DELTOCITY, DELTOCOUNTY, DELTOSTATE, DELTOZIPCODE, CREDITSQUEEZEPERC, NETPAYMENTDAYS, PAYMENTDISCOUNTDAYS, CONTACTPERSONNAME, CONTACTPERSONPHONE, STREET, STREET2, ZIPCODE, CITY, STATE, INVOICENUMBER, SEQ, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEDATE, DELTOCUVATNUMBER, INVOICESTARTPERIOD, INVOICEENDPERIOD, PAYTHISAMOUNT, PREBILLAMOUNT, CREDITSQUEEZEAMOUNT
, 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, TOTALAMOUNTEXCLVAT, MAX_PERCENTAGE, VAT_AMOUNT
, INTERNALVATNUMBER, VATNUMBER, SPLITUPCODE, SPLITUPDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, LNDRY_BANK_IDCODE, LNDRY_BANK_DESC, LNDRY_BANK_INTERNID, LNDRY_BANK_LNDRYBANKACCOUNT, LNDRY_BANK_IBANNO, INVOICEBUCODE, INVOICEBUDESC, DIVISIONDESC, REGIONDESC, PAYMENTTERMSDUEDATE)
as select
  ih.invoiceheader_id, ih.parentinvoiceheader_id, ih.billtocustomernumber, ih.billtocustomername, ih.extraname1, ih.extraname2,
  ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltocounty, ih.deltostate, ih.deltozipcode,
  ih.creditsqueezeperc, ih.netpaymentdays, ih.paymentdiscountdays
, ( 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.contactpersonphone, concatenatewithsign( ih.street, '   ', ih.street2) street, ih.street2, ih.zipcode, ih.city, ih.state
, ih.invoicenumber, cast(getsubstring(ih.invoicenumber, -3) as varchar2(3)) seq
, coalesce(ih.deltocustomernumber, ih.billtocustomernumber )deltocustomernumber
, coalesce(ih.deltocustomername, ih.billtocustomername) deltocustomername, ih.invoicedate
, coalesce(dell.vatnumber, bill.vatnumber) deltocuvatnumber
, coalesce((select invoiceheader.startdate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0 ), -- 0 means direct invoice in invoicefrequency table
            (select invoiceheader.invoicedate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id = 0 ) ) invoicestartperiod
, coalesce((select invoiceheader.enddate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0  ),
            (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber < ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 ),
             (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber = ih.invoicenumber -- this is for the first record when invoiceheader.invoicenumber = ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 )) invoiceendperiod
, ih.paythisamount, ih.prebillamount, ih.creditsqueezeamount
, (select description from paymentterms_desc pdesc where pdesc.paymentterms_id = customerbillinginfo.paymentterms_id
and pdesc.language_id = coalesce(dell.language_id, bill.language_id)) paymenttermsdesc
, customerbillingcomment.description customerrelatedmessage, ih.invoicecomments generalinvoicemessage
, case coalesce(customerbillingcomment.description, ' ')
       when coalesce(ih.invoicecomments, ' ') then 'y' else 'n'
            end suppresscustomerrelatedmessage
, currency.code currencycode, currency.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 = customerbillinginfo.consolidatedinvoicelayout_id) cons_inv_layout_code
, ih.totalamountexclvat
, coalesce((select max(ilv.percentage) from invoiceline il, invoicelinevarious ilv where
  il.invoiceheader_id = ih.parentinvoiceheader_id and il.invoiceline_id = ilv.invoiceline_id), 0) max_percentage
, coalesce((select sum(il.amount) from invoiceline il where
  il.invoiceheader_id = ih.parentinvoiceheader_id), 0) vat_amount
, b.internalvatnumber, b.vatnumber, ih.splitupcode, ih.splitupdescription, 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,
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
, b.code invoicebucode, b.description invoicebudesc
, (select dd.description from division_desc dd where b.division_id = dd.division_id and dd.language_id = bill.language_id) divisiondesc
, (select rd.description from region_desc rd where b.region_id = rd.region_id and rd.language_id = bill.language_id) regiondesc
,ihextr.paymenttermsduedate
from
  invoiceheader ih
  left outer join
             ( customer dell left outer join customerbillingcomment
                                  on customerbillingcomment.customer_id = dell.customer_id
                                     and customerbillingcomment.type = 1 )
       on ih.deltocustomer_link_id = dell.customer_id
, customer bill, customerbillinginfo
, status, currency
, businessunit b, plant p, address x, country c, invoiceheaderextrainfo ihextr
        left outer join bankinstitution lbank on ihextr.laundrybankinstitution_id = lbank.bankinstitution_id
where
    ih.billtocustomer_link_id = bill.customer_id
and bill.customer_id = customerbillinginfo.customer_id    -- and customerbillinginfo.consolidatedinvoice = 'y'
and ih.status_id = status.status_id
    and status.statustype = 'IN'
    and status.code = '2'
and ih.parentinvoiceheader_id is not null
and ih.currency_id = currency.currency_id
and b.businessunit_id = ih.invoicebusinessunit_id
and b.plant_id = p.plant_id
and p.country_id = c.country_id
and ih.invoiceheader_id = ihextr.invoiceheader_id
and p.address_id=x.address_id

/
create or replace view V_CONSOLIDATEDINVOICE_RRA
 (INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOSTREET, DELTOSTREET2, DELTOCITY, DELTOCOUNTY, DELTOSTATE, DELTOZIPCODE, CREDITSQUEEZEPERC, NETPAYMENTDAYS, PAYMENTDISCOUNTDAYS, CONTACTPERSONNAME, CONTACTPERSONPHONE, STREET, STREET2, ZIPCODE, CITY, STATE, INVOICENUMBER, SEQ, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEDATE, DELTOCUVATNUMBER, INVOICESTARTPERIOD, INVOICEENDPERIOD, PAYTHISAMOUNT, PREBILLAMOUNT, CREDITSQUEEZEAMOUNT
, 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, TOTALAMOUNTEXCLVAT, MAX_PERCENTAGE, VAT_AMOUNT
, INVOICEBUSINESSUNITCODE)
as select
  ih.invoiceheader_id, ih.parentinvoiceheader_id, ih.billtocustomernumber, ih.billtocustomername, ih.extraname1, ih.extraname2,
  ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltocounty, ih.deltostate, ih.deltozipcode,
  ih.creditsqueezeperc, ih.netpaymentdays, ih.paymentdiscountdays
, ( 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.contactpersonphone, CONCATENATEWITHSIGN( ih.street, '   ', ih.street2) street, ih.street2, ih.zipcode, ih.city, ih.state
, ih.invoicenumber, cast(GETSUBSTRING(ih.invoicenumber, -3) as varchar2(3)) Seq
, coalesce(ih.deltocustomernumber, ih.billtocustomernumber )deltocustomernumber
, coalesce(ih.deltocustomername, ih.billtocustomername) deltocustomername, ih.invoicedate
, coalesce(dell.vatnumber, bill.vatnumber) DelToCuVatNumber
, coalesce((select invoiceheader.startdate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0 ), -- 0 means Direct invoice in invoicefrequency table
            (select invoiceheader.invoicedate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id = 0 ) ) InvoiceStartPeriod
, coalesce((select invoiceheader.enddate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0  ),
            (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber < ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 ),
             (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber = ih.invoicenumber -- this is for the first record when invoiceheader.invoicenumber = ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceEndPeriod
, ih.paythisamount, ih.prebillamount, ih.creditsqueezeamount
, (select description from paymentterms_desc pdesc where pdesc.paymentterms_id = customerbillinginfo.paymentterms_id
and pdesc.language_id = coalesce(dell.language_id, bill.language_id)) paymenttermsDesc
, customerbillingcomment.description CustomerRelatedMessage, ih.invoicecomments GeneralInvoiceMessage
, case coalesce(customerbillingcomment.description, ' ')
       when coalesce(ih.invoicecomments, ' ') then 'Y' else 'N'
            end SuppressCustomerRelatedMessage
, currency.code currencyCode, currency.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 = customerbillinginfo.consolidatedinvoicelayout_id) cons_inv_layout_code
, ih.totalamountexclvat
, coalesce((select max(ilv.percentage) from invoiceline il, invoicelinevarious ilv where
  il.invoiceheader_id = ih.parentinvoiceheader_id and il.invoiceline_id = ilv.invoiceline_id), 0) max_percentage
, coalesce((select SUM(il.amount) from invoiceline il where
  il.invoiceheader_id = ih.parentinvoiceheader_id), 0) VAT_AMOUNT
, b.code InvoiceBusinessUnitCode
from
  invoiceheader ih
  left outer join
             ( customer dell left outer join customerbillingcomment
                                  on customerbillingcomment.customer_id = dell.customer_id
                                     and customerbillingcomment.type = 1 )
       on ih.deltocustomer_link_id = dell.customer_id
, customer bill, customerbillinginfo, status, currency
, businessunit b, plant p, country c, invoiceheaderextrainfo ihextr
where
    ih.billtocustomer_link_id = bill.customer_id
and bill.customer_id = customerbillinginfo.customer_id
    -- and customerbillinginfo.consolidatedinvoice = 'Y'
and ih.status_id = status.status_id
    and status.statustype = 'IN'
    and status.code = '2'
and ih.parentinvoiceheader_id is not null
and ih.currency_id = currency.currency_id
and b.businessunit_id = ih.invoicebusinessunit_id
and b.plant_id = p.plant_id
and p.country_id = c.country_id
and ih.invoiceheader_id = ihextr.invoiceheader_id

/
create or replace view V_CONSOLIDATEDINVOICE_RUS
 (INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOSTREET, DELTOSTREET2, DELTOCITY, DELTOCOUNTY, DELTOSTATE, DELTOZIPCODE, CREDITSQUEEZEPERC, NETPAYMENTDAYS, PAYMENTDISCOUNTDAYS, CONTACTPERSONNAME, CONTACTPERSONPHONE, STREET, STREET2, ZIPCODE, CITY, STATE, INVOICENUMBER, SEQ, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEDATE, DELTOCUVATNUMBER, INVOICESTARTPERIOD, INVOICEENDPERIOD, PAYTHISAMOUNT, PREBILLAMOUNT, CREDITSQUEEZEAMOUNT
, 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, TOTALAMOUNTEXCLVAT, MAX_PERCENTAGE, VAT_AMOUNT
, INTERNALVATNUMBER, VATNUMBER, SPLITUPCODE, SPLITUPDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, LNDRY_BANK_IDCODE, LNDRY_BANK_DESC, LNDRY_BANK_INTERNID, LNDRY_BANK_LNDRYBANKACCOUNT, LNDRY_BANK_IBANNO, REFERENCE)
as select
  ih.invoiceheader_id, ih.parentinvoiceheader_id, ih.billtocustomernumber, ih.billtocustomername, ih.extraname1, ih.extraname2,
  ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltocounty, ih.deltostate, ih.deltozipcode,
  ih.creditsqueezeperc, ih.netpaymentdays, ih.paymentdiscountdays
, ( 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.contactpersonphone, CONCATENATEWITHSIGN( ih.street, '   ', ih.street2) street, ih.street2, ih.zipcode, ih.city, ih.state
, ih.invoicenumber, cast(GETSUBSTRING(ih.invoicenumber, -3) as varchar2(3)) Seq
, coalesce(ih.deltocustomernumber, ih.billtocustomernumber )deltocustomernumber
, coalesce(ih.deltocustomername, ih.billtocustomername) deltocustomername, ih.invoicedate
, coalesce(dell.vatnumber, bill.vatnumber) DelToCuVatNumber
, coalesce((select invoiceheader.startdate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0 ), -- 0 means Direct invoice in invoicefrequency table
            (select invoiceheader.invoicedate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id = 0 ) ) InvoiceStartPeriod
, coalesce((select invoiceheader.enddate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0  ),
            (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber < ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 ),
             (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber = ih.invoicenumber -- this is for the first record when invoiceheader.invoicenumber = ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceEndPeriod
, ih.paythisamount, ih.prebillamount, ih.creditsqueezeamount
, (select description from paymentterms_desc pdesc where pdesc.paymentterms_id = customerbillinginfo.paymentterms_id
and pdesc.language_id = coalesce(dell.language_id, bill.language_id)) paymenttermsDesc
, customerbillingcomment.description CustomerRelatedMessage, ih.invoicecomments GeneralInvoiceMessage
, case coalesce(customerbillingcomment.description, ' ')
       when coalesce(ih.invoicecomments, ' ') then 'Y' else 'N'
            end SuppressCustomerRelatedMessage
, currency.code currencyCode, currency.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 = customerbillinginfo.consolidatedinvoicelayout_id) cons_inv_layout_code
, ih.totalamountexclvat
, coalesce((select max(ilv.percentage) from invoiceline il, invoicelinevarious ilv where
  il.invoiceheader_id = ih.parentinvoiceheader_id and il.invoiceline_id = ilv.invoiceline_id), 0) max_percentage
, coalesce((select SUM(il.amount) from invoiceline il where
  il.invoiceheader_id = ih.parentinvoiceheader_id), 0) VAT_AMOUNT
, b.internalvatnumber, b.vatnumber, ih.splitupcode, ih.splitupdescription, 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,
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.reference
from
  invoiceheader ih
  left outer join
             ( customer dell left outer join customerbillingcomment
                                  on customerbillingcomment.customer_id = dell.customer_id
                                     and customerbillingcomment.type = 1 )
       on ih.deltocustomer_link_id = dell.customer_id
, customer bill, customerbillinginfo
, status, currency
, businessunit b, plant p, address x, country c, invoiceheaderextrainfo ihextr
        LEFT OUTER JOIN bankinstitution Lbank ON ihextr.laundrybankinstitution_id = Lbank.bankinstitution_id
where
    ih.billtocustomer_link_id = bill.customer_id
and bill.customer_id = customerbillinginfo.customer_id
    -- and customerbillinginfo.consolidatedinvoice = 'Y'
and ih.status_id = status.status_id
    and status.statustype = 'IN'
    and status.code = '2'
and ih.parentinvoiceheader_id is not null
and ih.currency_id = currency.currency_id
and b.businessunit_id = ih.invoicebusinessunit_id
and b.plant_id = p.plant_id
and p.country_id = c.country_id
and ih.invoiceheader_id = ihextr.invoiceheader_id
and p.address_id=x.address_id

/
create or replace view V_CONSOLIDATEDINVOICE_STI
 (INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOSTREET, DELTOSTREET2, DELTOCITY, DELTOCOUNTY, DELTOSTATE, DELTOZIPCODE, CREDITSQUEEZEPERC, NETPAYMENTDAYS, PAYMENTDISCOUNTDAYS, CONTACTPERSONNAME, CONTACTPERSONPHONE, STREET, STREET2, ZIPCODE, CITY, STATE, INVOICENUMBER, SEQ, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEDATE, DELTOCUVATNUMBER, INVOICESTARTPERIOD, INVOICEENDPERIOD, PAYTHISAMOUNT, PREBILLAMOUNT, CREDITSQUEEZEAMOUNT
, 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, TOTALAMOUNTEXCLVAT, MAX_PERCENTAGE, VAT_AMOUNT
, INTERNALVATNUMBER, VATNUMBER, SPLITUPCODE, SPLITUPDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, LNDRY_BANK_IDCODE, LNDRY_BANK_DESC, LNDRY_BANK_INTERNID, LNDRY_BANK_LNDRYBANKACCOUNT, LNDRY_BANK_IBANNO, TAXRATE, PONUMBER, INV_AMOUNT, KID)
as select
  ih.invoiceheader_id, ih.parentinvoiceheader_id, ih.billtocustomernumber, ih.billtocustomername  billtocustomername, ih.extraname1, ih.extraname2,
  ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltocounty, ih.deltostate, ih.deltozipcode,
  ih.creditsqueezeperc, ih.netpaymentdays, ih.paymentdiscountdays
, ( 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.contactpersonphone, ih.street  street, ih.street2  street2, ih.zipcode, ih.city, ih.state
, ih.invoicenumber, cast(GETSUBSTRING(ih.invoicenumber, -3) as varchar2(3)) Seq
, coalesce(ih.deltocustomernumber, ih.billtocustomernumber )  deltocustomernumber
, coalesce(ih.deltocustomername, ih.billtocustomername)  deltocustomername, ih.invoicedate
, coalesce(dell.vatnumber, bill.vatnumber) DelToCuVatNumber
, coalesce((select invoiceheader.startdate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0 ), -- 0 means Direct invoice in invoicefrequency table
            (select invoiceheader.invoicedate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id = 0 ) ) InvoiceStartPeriod
, coalesce((select invoiceheader.enddate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0  ),
            (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber < ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 ),
             (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber = ih.invoicenumber -- this is for the first record when invoiceheader.invoicenumber = ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceEndPeriod
, ih.paythisamount, ih.prebillamount, ih.creditsqueezeamount
, (select description from paymentterms_desc pdesc where pdesc.paymentterms_id = customerbillinginfo.paymentterms_id
and pdesc.language_id = coalesce(dell.language_id, bill.language_id)) paymenttermsDesc
, customerbillingcomment.description CustomerRelatedMessage, ih.invoicecomments GeneralInvoiceMessage
, case coalesce(customerbillingcomment.description, ' ')
       when coalesce(ih.invoicecomments, ' ') then 'Y' else 'N'
            end SuppressCustomerRelatedMessage
, currency.code currencyCode, currency.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 = customerbillinginfo.consolidatedinvoicelayout_id) cons_inv_layout_code
, ih.totalamountexclvat
, coalesce((select max(ilv.percentage) from invoiceline il, invoicelinevarious ilv where
  il.invoiceheader_id = ih.parentinvoiceheader_id and il.invoiceline_id = ilv.invoiceline_id), 0) max_percentage
, coalesce((select SUM(il.amount) from invoiceline il where
  il.invoiceheader_id = ih.parentinvoiceheader_id), 0) VAT_AMOUNT
, b.internalvatnumber, b.vatnumber, ih.splitupcode, ih.splitupdescription, 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,
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
, (select MAX(TAXRATE) FROM  taxgroup t where t.code = 'MOMS') TAXRATE
,(select max(cpc.purchaseorder) from contractspercustomer cpc
where cpc.customer_id = ih.billtocustomer_link_id
and  ih.startdate >=  cpc.dateactive and ih.enddate <= cpc.dateinactive) PONumber
, coalesce((select SUM(il.amount) from invoiceline il where
  il.invoiceheader_id = ih.invoiceheader_id), 0) INV_AMOUNT
,(ih.invoicenumber* 10 + F_MOD10DIM(ih.invoicenumber, LENGTH(TO_CHAR(ih.invoicenumber)))) KID
from
  invoiceheader ih
  left outer join
             ( customer dell left outer join customerbillingcomment
                                  on customerbillingcomment.customer_id = dell.customer_id
                                     and customerbillingcomment.type = 1 )
       on ih.deltocustomer_link_id = dell.customer_id
, customer bill, customerbillinginfo
, status, currency
, businessunit b, plant p, address x, country c, invoiceheaderextrainfo ihextr
        LEFT OUTER JOIN bankinstitution Lbank ON ihextr.laundrybankinstitution_id = Lbank.bankinstitution_id
where
    ih.billtocustomer_link_id = bill.customer_id
and bill.customer_id = customerbillinginfo.customer_id
    -- and customerbillinginfo.consolidatedinvoice = 'Y'
and ih.status_id = status.status_id
    and status.statustype = 'IN'
    and status.code = '2'
and ih.parentinvoiceheader_id is not null
and ih.currency_id = currency.currency_id
and b.businessunit_id = ih.invoicebusinessunit_id
and b.plant_id = p.plant_id
and p.country_id = c.country_id
and ih.invoiceheader_id = ihextr.invoiceheader_id
and p.address_id=x.address_id

/
create or replace view V_CONSOLIDATEDINVOICE_STK
 (INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOSTREET, DELTOSTREET2, DELTOCITY, DELTOCOUNTY, DELTOSTATE, DELTOZIPCODE, CREDITSQUEEZEPERC, NETPAYMENTDAYS, PAYMENTDISCOUNTDAYS, CONTACTPERSONNAME, CONTACTPERSONPHONE, STREET, STREET2, ZIPCODE, CITY, STATE, INVOICENUMBER, ACTIVITYREFERENCE, SEQ, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEDATE, DELTOCUVATNUMBER, INVOICESTARTPERIOD, INVOICEENDPERIOD, PAYTHISAMOUNT
, PREBILLAMOUNT, CREDITSQUEEZEAMOUNT, 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, DELTOCUSTLANG, PAYMENTTERMSDUEDATE, INVOICELAYOUTCODE)
as select
  ih.invoiceheader_id, ih.parentinvoiceheader_id, ih.billtocustomernumber, ih.billtocustomername, ih.extraname1, ih.extraname2,
  ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltocounty, ih.deltostate, ih.deltozipcode,
  ih.creditsqueezeperc, ih.netpaymentdays, ih.paymentdiscountdays
, ( 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.contactpersonphone, CONCATENATEWITHSIGN( ih.street, '   ', ih.street2) street, ih.street2, ih.zipcode, ih.city, ih.state
, ih.invoicenumber,ih.activityreference, cast(GETSUBSTRING(ih.invoicenumber, -3) as varchar2(3)) Seq
, coalesce(ih.deltocustomernumber, ih.billtocustomernumber )deltocustomernumber
, coalesce(ih.deltocustomername, ih.billtocustomername) deltocustomername, ih.invoicedate
, coalesce(dell.vatnumber, bill.vatnumber) DelToCuVatNumber
, coalesce((select invoiceheader.startdate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0 ), -- 0 means Direct invoice in invoicefrequency table
            (select invoiceheader.invoicedate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceStartPeriod
, coalesce((select invoiceheader.enddate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0  ),
            (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber < ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 ),
             (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber = ih.invoicenumber -- this is for the first record when invoiceheader.invoicenumber = ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceEndPeriod
, ih.paythisamount, ih.prebillamount, ih.creditsqueezeamount
, (select paymenttermsdescription from invoiceheaderextrainfo ihei where ihei.invoiceheader_id = ih.invoiceheader_id
/*and pdesc.language_id = coalesce(dell.language_id, bill.language_id)*/) paymenttermsDesc
, customerbillingcomment.description CustomerRelatedMessage, ih.invoicecomments GeneralInvoiceMessage
, case coalesce(customerbillingcomment.description, ' ')
       when coalesce(ih.invoicecomments, ' ') then 'Y' else 'N'
            end SuppressCustomerRelatedMessage
, currency.code currencyCode, currency.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 = customerbillinginfo.consolidatedinvoicelayout_id) CONS_INV_LAYOUT_CODE
, ih.nextperiodstartdate, ih.nextperiodenddate
, ih.splitupcode
, ih.splitupdescription
, (select languages.code from languages where languages.language_id = DELL.LANGUAGE_ID) deltocustlang
, ihextr.paymenttermsduedate
, ihextr.formlayoutcode invoicelayoutcode
from
  invoiceheader ih
  left outer join
             ( customer dell left outer join customerbillingcomment
                                  on customerbillingcomment.customer_id = dell.customer_id
                                     and customerbillingcomment.type = 1 )
       on ih.deltocustomer_link_id = dell.customer_id
, customer bill, customerbillinginfo, status, currency
, businessunit b, plant p, country c, invoiceheaderextrainfo ihextr
where
    ih.billtocustomer_link_id = bill.customer_id
and bill.customer_id = customerbillinginfo.customer_id    -- and customerbillinginfo.consolidatedinvoice = 'Y'
and ih.status_id = status.status_id
    and status.statustype = 'IN'
    and status.code = '2'
and ih.parentinvoiceheader_id is not null
and ih.currency_id = currency.currency_id
and b.businessunit_id = ih.invoicebusinessunit_id
and b.plant_id = p.plant_id
and p.country_id = c.country_id
and ih.invoiceheader_id = ihextr.invoiceheader_id

/
create or replace view V_CONSOLIDATEDINVOICE_TIL
 (INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOSTREET, DELTOSTREET2, DELTOCITY, DELTOCOUNTY, DELTOSTATE, DELTOZIPCODE, CREDITSQUEEZEPERC, NETPAYMENTDAYS, PAYMENTDISCOUNTDAYS, CONTACTPERSONNAME, CONTACTPERSONPHONE, STREET, STREET2, ZIPCODE, CITY, STATE, INVOICENUMBER, SEQ, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEDATE, DELTOCUVATNUMBER, INVOICESTARTPERIOD, INVOICEENDPERIOD, PAYTHISAMOUNT, PREBILLAMOUNT, CREDITSQUEEZEAMOUNT
, 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, TOTALAMOUNTEXCLVAT, MAX_PERCENTAGE, VAT_AMOUNT
, INTERNALVATNUMBER, VATNUMBER, SPLITUPCODE, SPLITUPDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, LNDRY_BANK_IDCODE, LNDRY_BANK_DESC, LNDRY_BANK_INTERNID, LNDRY_BANK_LNDRYBANKACCOUNT, LNDRY_BANK_IBANNO, TAXRATE, PONUMBER, INV_AMOUNT, KID)
as select
  ih.invoiceheader_id, ih.parentinvoiceheader_id, ih.billtocustomernumber, CAST(ih.billtocustomername AS VARCHAR2(60))  billtocustomername, ih.extraname1, ih.extraname2,
  ih.deltostreet, ih.deltostreet2, ih.deltocity, ih.deltocounty, ih.deltostate, ih.deltozipcode,
  ih.creditsqueezeperc, ih.netpaymentdays, ih.paymentdiscountdays
, ( 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.contactpersonphone, ih.street  street, ih.street2  street2, ih.zipcode, ih.city, ih.state
, ih.invoicenumber, cast(GETSUBSTRING(ih.invoicenumber, -3) as varchar2(3)) Seq
, coalesce(ih.deltocustomernumber, ih.billtocustomernumber )  deltocustomernumber
, CAST(coalesce(ih.deltocustomername, ih.billtocustomername) AS VARCHAR2(60))  deltocustomername, ih.invoicedate
, coalesce(dell.vatnumber, bill.vatnumber) DelToCuVatNumber
, coalesce((select invoiceheader.startdate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0 ), -- 0 means Direct invoice in invoicefrequency table
            (select invoiceheader.invoicedate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id = 0 ) ) InvoiceStartPeriod
, coalesce((select invoiceheader.enddate from invoiceheader
                  where ih.invoiceheader_id = invoiceheader.invoiceheader_id
                  and invoiceheader.invoicefrequency_id <> 0  ),
            (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber < ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 ),
             (select max(invoiceheader.invoicedate) from invoiceheader
                  where  invoiceheader.billtocustomer_link_id = ih.billtocustomer_link_id
                  and invoiceheader.invoicenumber = ih.invoicenumber -- this is for the first record when invoiceheader.invoicenumber = ih.invoicenumber
                  and invoiceheader.invoicefrequency_id = 0 )) InvoiceEndPeriod
, ih.paythisamount, ih.prebillamount, ih.creditsqueezeamount
, (select description from paymentterms_desc pdesc where pdesc.paymentterms_id = customerbillinginfo.paymentterms_id
and pdesc.language_id = coalesce(dell.language_id, bill.language_id)) paymenttermsDesc
, customerbillingcomment.description CustomerRelatedMessage, ih.invoicecomments GeneralInvoiceMessage
, case coalesce(customerbillingcomment.description, ' ')
       when coalesce(ih.invoicecomments, ' ') then 'Y' else 'N'
            end SuppressCustomerRelatedMessage
, currency.code currencyCode, currency.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 = customerbillinginfo.consolidatedinvoicelayout_id) cons_inv_layout_code
, ih.totalamountexclvat
, coalesce((select max(ilv.percentage) from invoiceline il, invoicelinevarious ilv where
  il.invoiceheader_id = ih.parentinvoiceheader_id and il.invoiceline_id = ilv.invoiceline_id), 0) max_percentage
, coalesce((select SUM(il.amount) from invoiceline il where
  il.invoiceheader_id = ih.parentinvoiceheader_id), 0) VAT_AMOUNT
, b.internalvatnumber, b.vatnumber, ih.splitupcode, ih.splitupdescription, 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, CAST(p.email AS VARCHAR2(60)) plantemail,
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
, (select MAX(TAXRATE) FROM  taxgroup t where t.code = 'MOMS') TAXRATE
,(select max(cpc.purchaseorder) from contractspercustomer cpc
where cpc.customer_id = ih.billtocustomer_link_id
and  ih.startdate >=  cpc.dateactive and ih.enddate <= cpc.dateinactive) PONumber
, coalesce((select SUM(il.amount) from invoiceline il where
  il.invoiceheader_id = ih.invoiceheader_id), 0) INV_AMOUNT
, F_GetKIDFrom2Z( ih.billtocustomernumber,ih.invoicenumber) KID
from
  invoiceheader ih
  left outer join
             ( customer dell left outer join customerbillingcomment
                                  on customerbillingcomment.customer_id = dell.customer_id
                                     and customerbillingcomment.type = 1 )
       on ih.deltocustomer_link_id = dell.customer_id
, customer bill, customerbillinginfo
, status, currency
, businessunit b, plant p, address x, country c, invoiceheaderextrainfo ihextr
        LEFT OUTER JOIN bankinstitution Lbank ON ihextr.laundrybankinstitution_id = Lbank.bankinstitution_id
where
    ih.billtocustomer_link_id = bill.customer_id
and bill.customer_id = customerbillinginfo.customer_id
    -- and customerbillinginfo.consolidatedinvoice = 'Y'
and ih.status_id = status.status_id
    and status.statustype = 'IN'
    and status.code = '2'
and ih.parentinvoiceheader_id is not null
and ih.currency_id = currency.currency_id
and b.businessunit_id = ih.invoicebusinessunit_id
and b.plant_id = p.plant_id
and p.country_id = c.country_id
and ih.invoiceheader_id = ihextr.invoiceheader_id
and p.address_id=x.address_id

/
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_CONTACTPERSON_BCH
 (CUSTOMERNUMBER, CUSTOMERNAME, CPNAME, CONTACTPERSONNUMBER, CPFUNCTION, CP_PHONE, CP_FAX, CP_EMAIL, CP_MOBILEPHONE, ACTIVE)
as select c.customernumber, c.name customername,
       cp.name cpname, cp.contactpersonnumber,
       (select cf.description from contactpersonfunction_desc cf
        where cf.contactpersonfunction_id = cp.contactpersonfunction_id and cf.language_id = c.language_id) cpfunction,
        cp.phone cp_phone, cp.fax cp_fax, cp.email cp_email, cp.mobilephone cp_mobilephone, cp.active
from contactperson cp, customer c
where cp.customer_id = c.customer_id

/
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((GETCURRENTDATE() - GETDATEONLY(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 <= GETCURRENTDATE() and ct.dateinactive > GETCURRENTDATE() )
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((GETCURRENTDATE()-GETDATEONLY(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 <= GETCURRENTDATE() and ct.dateinactive > GETCURRENTDATE() )
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
 (CORRECTEDNOTENUMBER, NOTENUMBER, 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, DRIVINGDAY_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)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER, PACKINGNOTE.NOTENUMBER,
PACKINGNOTE.SEQUENCENUMBER,
PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK,
PACKINGNOTE.STOPNUMBER,
PACKINGNOTE.PACKINGNOTE_ID,
PACKINGNOTE.ENDDATEFORUSE, PACKINGNOTE.ORIGIN,
PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME, CUSTOMER.PHONENO,
ADDRESS.STREET CUSTOMERSTREET, ADDRESS.ZIPCODE CUSTOMERZIP, ADDRESS.CITY CUSTOMERCITY,
ADDRESS.STREET2 CUSTOMERSTREET2, ADDRESS.STATE CUSTOMERSTATE, ADDRESS.COUNTY CUSTOMERCOUNTY,
MAILADRESS.STREET MAIL_STREET, MAILADRESS.ZIPCODE MAIL_ZIPCODE, MAILADRESS.CITY MAIL_CITY,
MAILADRESS.STATE MAIL_STATE, MAILADRESS.COUNTY MAIL_COUNTY, MAILADRESS.STREET2 MAIL_STREET2,
DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
PROCESSBU.DESCRIPTION BUDESCRIPTION,
PLANT.NAME PLANTNAME,
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
(SELECT DD.DESCRIPTION FROM DAY_DESC DD WHERE DD.DAY_ID = ROUTE.DRIVINGDAY_ID AND DD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) DRIVINGDAY_DESC,
ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION ROUTEDESCRIPTION, ROUTE.LOADINGDOCK,
LANGUAGES.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,
DEPOT.DESCRIPTION DEPOTDESCRIPTION
, DISTRIBUTIONPOINT.Remarkonpackingnote, DISTRIBUTIONPOINT.Remarkondeliverynote
, (select lan.code from languages lan where CUSTOMER.language_id = lan.language_id) LanguageCodeCustomer
--,	CAST(PACKINGNOTE.WEEK AS VARCHAR2(2)) DeliveryWeek
, DISTRIBUTIONPOINT.Labelcolor cp_labelcolor, DISTRIBUTIONPOINT.Internalremarkfortransplabel
, DISTRIBUTIONPOINT.Transplabinternalremarkenddate, DISTRIBUTIONPOINT.Externalremarkfortransplabel
, DISTRIBUTIONPOINT.Transplabexternalremarkenddate, DISTRIBUTIONPOINT.Nooftransportlabels
, (select dud.usageday_id from departmentusageday dud where dud.department_id = department.department_id and dud.day_id = route.drivingday_id) usagedaynumber
, (select dd.description from departmentusageday dud, day_desc dd where dud.department_id = department.department_id and dud.usageday_id = dd.day_id and dud.day_id = route.drivingday_id and dd.language_id = languages.language_id) usagedaydesc
, CUSTOMER.labelcolor cu_labelcolor,
route.drivingday_id day_id
FROM  CUSTOMER,
        ADDRESS, DEPARTMENT, DISTRIBUTIONPOINT, ADDRESS MAILADRESS,
        PLANT, ADDRESS PLANTADDRESS,
        BUSINESSUNIT PROCESSBU, DELIVERYPOINT,
        PACKINGNOTE
        LEFT OUTER JOIN ROUTE
        LEFT OUTER JOIN DEPOT ON ROUTE.DEPOT_ID=DEPOT.DEPOT_ID    --TODO7736
        ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID,
        LANGUAGES,
        ADDRESS DELPOINT_ADDRESS
  WHERE PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
	AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
	AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND CUSTOMER.VISITADDRESS_ID = ADDRESS.ADDRESS_ID
	AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
	AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND CUSTOMER.MAILADDRESS_ID = MAILADRESS.ADDRESS_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = DELPOINT_ADDRESS.ADDRESS_ID

/
create or replace view V_CONTAINERSTICKERADV_LTS
 (CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, PHONENO, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTREET2, CUSTOMERSTATE, CUSTOMERCOUNTY, DEPARTMENT_ID, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, 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, DEPOTDESCRIPTION, REMARKONPACKINGNOTE, REMARKONDELIVERYNOTE, LANGUAGECODECUSTOMER, DRIVINGDAY_ID, USAGEDAYNUMBER, USAGEDAYDESC, LABELCOLOR, INTERNALREMARKFORTRANSPLABEL, TRANSPLABINTERNALREMARKENDDATE, EXTERNALREMARKFORTRANSPLABEL, TRANSPLABEXTERNALREMARKENDDATE, NOOFTRANSPORTLABELS, CU_LABELCOLOR)
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,
       d.DEPARTMENT_ID, d.DEPARTMENTNUMBER, d.DESCRIPTION DEPARTMENTDESCRIPTION,
       dp.DISTRIBUTIONPOINTNUMBER, dp.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
       dvp.DELIVERYPOINT_ID, dvp.CODE DELIVERYPOINTCODE, dvp.DESCRIPTION DELIVERYPOINTDESCRIPTION,
       (SELECT DD.DESCRIPTION FROM DAY_DESC DD WHERE DD.DAY_ID = R.DRIVINGDAY_ID AND DD.LANGUAGE_ID = L.LANGUAGE_ID) DRIVINGDAY_DESC,
       R.ROUTENUMBER, R.DESCRIPTION ROUTEDESCRIPTION, R.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, DE.DESCRIPTION DEPOTDESCRIPTION
, dp.Remarkonpackingnote, dp.Remarkondeliverynote
, (select lan.code from languages lan where c.language_id = lan.language_id) LanguageCodeCustomer
, r.drivingday_id
, (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 = l.language_id) usagedaydesc
, dp.labelcolor, dp.internalremarkfortransplabel
, dp.transplabinternalremarkenddate, dp.externalremarkfortransplabel
, dp.transplabexternalremarkenddate, dp.nooftransportlabels
, c.labelcolor cu_labelcolor
from customer c, department d, distributionpoint dp, deliverypoint dvp, address a,
     ROUTE R LEFT OUTER JOIN DEPOT DE ON R.DEPOT_ID=DE.DEPOT_ID
     , LANGUAGES L, REPORTPARAM RP
     , ADDRESS DELPOINT_ADDRESS
where c.customer_id = d.customer_id
      and d.department_id = dp.department_id
      and dp.deliverypoint_id = dvp.deliverypoint_id
      and c.visitaddress_id = a.address_id
      and RP.Number_Value = dp.distributionpoint_id
      and RP.Number_Value1 = R.Route_Id
      and RP.String_Value2 = L.CODE
      AND DVP.DELIVERYADDRESS_ID = DELPOINT_ADDRESS.ADDRESS_ID

/
create or replace view V_CONTAINERSTICKER_AAA
 (CORRECTEDNOTENUMBER, NOTENUMBER, SEQUENCENUMBER, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, STOPNUMBER, PACKINGNOTE_ID, ENDDATEFORUSE, ORIGIN, PRODUCTIONDATE, NUMBEROFGARMENTSINLOCKER, NUMBEROFLOCKERS, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, PHONENO, SEARCHNAME, 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, DRIVINGDAY_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, PLANTDEPARTMENTCODE)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER, PACKINGNOTE.NOTENUMBER,
PACKINGNOTE.SEQUENCENUMBER,
PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK,
PACKINGNOTE.STOPNUMBER,
PACKINGNOTE.PACKINGNOTE_ID,
PACKINGNOTE.ENDDATEFORUSE, PACKINGNOTE.ORIGIN,
PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME, CUSTOMER.PHONENO, CUSTOMER.SEARCHNAME,
ADDRESS.STREET CUSTOMERSTREET, ADDRESS.ZIPCODE CUSTOMERZIP, ADDRESS.CITY CUSTOMERCITY,
ADDRESS.STREET2 CUSTOMERSTREET2, ADDRESS.STATE CUSTOMERSTATE, ADDRESS.COUNTY CUSTOMERCOUNTY,
MAILADRESS.STREET MAIL_STREET, MAILADRESS.ZIPCODE MAIL_ZIPCODE, MAILADRESS.CITY MAIL_CITY,
MAILADRESS.STATE MAIL_STATE, MAILADRESS.COUNTY MAIL_COUNTY, MAILADRESS.STREET2 MAIL_STREET2,
DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
PROCESSBU.DESCRIPTION BUDESCRIPTION,
PLANT.NAME PLANTNAME,
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
(SELECT DD.DESCRIPTION FROM DAY_DESC DD WHERE DD.DAY_ID = ROUTE.DRIVINGDAY_ID AND DD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) DRIVINGDAY_DESC,
ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION ROUTEDESCRIPTION, ROUTE.LOADINGDOCK,
LANGUAGES.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,
DEPOT.DESCRIPTION DEPOTDESCRIPTION
, DISTRIBUTIONPOINT.Remarkonpackingnote, DISTRIBUTIONPOINT.Remarkondeliverynote
, (select lan.code from languages lan where CUSTOMER.language_id = lan.language_id) LanguageCodeCustomer
--,	CAST(PACKINGNOTE.WEEK AS VARCHAR2(2)) DeliveryWeek
, DISTRIBUTIONPOINT.Labelcolor cp_labelcolor, DISTRIBUTIONPOINT.Internalremarkfortransplabel
, DISTRIBUTIONPOINT.Transplabinternalremarkenddate, DISTRIBUTIONPOINT.Externalremarkfortransplabel
, DISTRIBUTIONPOINT.Transplabexternalremarkenddate, DISTRIBUTIONPOINT.Nooftransportlabels
, (select dud.usageday_id from departmentusageday dud where dud.department_id = department.department_id and dud.day_id = route.drivingday_id) usagedaynumber
, (select dd.description from departmentusageday dud, day_desc dd where dud.department_id = department.department_id and dud.usageday_id = dd.day_id and dud.day_id = route.drivingday_id and dd.language_id = languages.language_id) usagedaydesc
, CUSTOMER.labelcolor cu_labelcolor,
route.drivingday_id day_id
, (select pd.code from plantdepartment pd where packingnote.plantdepartment_id = pd.plantdepartment_id) plantdepartmentcode
FROM  CUSTOMER,
        ADDRESS, DEPARTMENT, DISTRIBUTIONPOINT, ADDRESS MAILADRESS,
        PLANT, ADDRESS PLANTADDRESS,
        BUSINESSUNIT PROCESSBU, DELIVERYPOINT,
        PACKINGNOTE
        LEFT OUTER JOIN ROUTE
        LEFT OUTER JOIN DEPOT ON ROUTE.DEPOT_ID=DEPOT.DEPOT_ID    --TODO7736
        ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID,
        LANGUAGES,
        ADDRESS DELPOINT_ADDRESS
  WHERE PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
	AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
	AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND CUSTOMER.VISITADDRESS_ID = ADDRESS.ADDRESS_ID
	AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
	AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND CUSTOMER.MAILADDRESS_ID = MAILADRESS.ADDRESS_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = DELPOINT_ADDRESS.ADDRESS_ID

/
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, DRIVINGDAY_DESC, ROUTENUMBER, ROUTEDESCRIPTION, LOADINGDOCK, REPORTPARAM_ID, TIMESTAMP, COPY_NUMBER, LANGUAGECODE, DELPOINT_STREET, DELPOINT_STREET2
, DELPOINT_ZIPCODE, DELPOINT_CITY, DELPOINT_STATE, DELPOINT_COUNTY, DUMMYGRP, DEPOTDESCRIPTION, USAGEDAYNUMBER, USAGEDAYDESC, CP_LABELCOLOR, INTERNALREMARKFORTRANSPLABEL, TRANSPLABINTERNALREMARKENDDATE, EXTERNALREMARKFORTRANSPLABEL, TRANSPLABEXTERNALREMARKENDDATE, NOOFTRANSPORTLABELS, CU_LABELCOLOR)
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,
       d.DEPARTMENT_ID,
       d.DEPARTMENTNUMBER,
       d.DESCRIPTION DEPARTMENTDESCRIPTION,
       dp.DISTRIBUTIONPOINTNUMBER,
       dp.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
       dvp.DELIVERYPOINT_ID,
       dvp.CODE DELIVERYPOINTCODE,
       dvp.DESCRIPTION DELIVERYPOINTDESCRIPTION,
       (SELECT DD.DESCRIPTION
          FROM DAY_DESC DD
         WHERE DD.DAY_ID = R.DRIVINGDAY_ID
           AND DD.LANGUAGE_ID = L.LANGUAGE_ID) DRIVINGDAY_DESC,
       R.ROUTENUMBER,
       R.DESCRIPTION ROUTEDESCRIPTION,
       R.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,
       DE.DESCRIPTION DEPOTDESCRIPTION,
       (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 = l.language_id) usagedaydesc,
       dp.labelcolor cp_labelcolor,
       dp.internalremarkfortransplabel,
       dp.transplabinternalremarkenddate,
       dp.externalremarkfortransplabel,
       dp.transplabexternalremarkenddate,
       dp.nooftransportlabels,
       c.labelcolor cu_labelcolor
  from customer          c,
       department        d,
       distributionpoint dp,
       deliverypoint     dvp,
       address           a,
       ROUTE             R
  LEFT OUTER JOIN DEPOT DE
    ON R.DEPOT_ID = DE.DEPOT_ID --TODO7736
 , LANGUAGES L, REPORTPARAM RP, ADDRESS DELPOINT_ADDRESS
 where c.customer_id = d.customer_id
   and d.department_id = dp.department_id
   and dvp.deliverypoint_id = decode(rp.number_value4, 0, dp.deliverypoint_id, rp.number_value4) -- ABS-49087
   and c.visitaddress_id = a.address_id
   and RP.Number_Value = dp.distributionpoint_id
   and RP.Number_Value1 = R.Route_Id
   and RP.String_Value2 = L.CODE
   AND DVP.DELIVERYADDRESS_ID = DELPOINT_ADDRESS.ADDRESS_ID

/
create or replace view V_CONTAINERSTICKER_ADV_SMG
 (CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, SEARCHNAME, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTREET2, CUSTOMERSTATE, CUSTOMERCOUNTY, MAIL_STREET, DEPARTMENT_ID, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINT_ID, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, CODEONLABEL, REPORTPARAM_ID, TIMESTAMP, COPY_NUMBER, LANGUAGECODE, DELPOINT_STREET, DELPOINT_STREET2, DELPOINT_ZIPCODE, DELPOINT_CITY
, DELPOINT_STATE, DELPOINT_COUNTY, DUMMYGRP, TRANSPORTARTICLEDESCRIPTION, PLCODE)
as select c.CUSTOMER_ID,
       insertspace_after_x_characters(c.CUSTOMERNUMBER,3) CUSTOMERNUMBER,
       c.NAME CUSTOMERNAME,
       c.searchname,
       a.STREET CUSTOMERSTREET,
       a.ZIPCODE CUSTOMERZIP,
       a.CITY CUSTOMERCITY,
       a.STREET2 CUSTOMERSTREET2,
       a.STATE CUSTOMERSTATE,
       a.COUNTY CUSTOMERCOUNTY,
       mailaddress.street mail_street,
       d.DEPARTMENT_ID,
       d.DEPARTMENTNUMBER,
       d.DESCRIPTION DEPARTMENTDESCRIPTION,
       dp.DISTRIBUTIONPOINTNUMBER,
       dp.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
       dvp.DELIVERYPOINT_ID,
       dvp.CODE DELIVERYPOINTCODE,
       dvp.DESCRIPTION DELIVERYPOINTDESCRIPTION,
       R.CODEONLABEL,
       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,
       (select tad.description from transportarticle_desc tad, transportarticle ta, standarddelivery sdd where tad.transportarticle_id = ta.transportarticle_id and tad.language_id = l.language_id and sdd.distributionpoint_id = dp.distributionpoint_id and sdd.sequencenumber = 1 and sdd.transportarticle_id = ta.transportarticle_id) transportarticledescription
       ,( select p.code from plant p where R.Plant_id=p.plant_id)plcode
  from customer          c,
       department        d,
       distributionpoint dp,
       deliverypoint     dvp,
       address           a,
       address           mailaddress
  , LANGUAGES L
  , REPORTPARAM RP left outer join ROUTE R on  RP.Number_Value1 = R.Route_Id
  , ADDRESS DELPOINT_ADDRESS
 where c.customer_id = d.customer_id
   and d.department_id = dp.department_id
   and dp.deliverypoint_id = dvp.deliverypoint_id
   and c.visitaddress_id = a.address_id
   and RP.Number_Value = dp.distributionpoint_id
   and RP.String_Value2 = L.CODE
   and DVP.DELIVERYADDRESS_ID = DELPOINT_ADDRESS.ADDRESS_ID
   and C.MAILADDRESS_ID = MAILADDRESS.ADDRESS_ID
   and RP.Number_Value4 = 0
 union
  select c.CUSTOMER_ID,
       insertspace_after_x_characters(c.CUSTOMERNUMBER,3) CUSTOMERNUMBER,
       c.NAME CUSTOMERNAME,
       c.searchname,
       a.STREET CUSTOMERSTREET,
       a.ZIPCODE CUSTOMERZIP,
       a.CITY CUSTOMERCITY,
       a.STREET2 CUSTOMERSTREET2,
       a.STATE CUSTOMERSTATE,
       a.COUNTY CUSTOMERCOUNTY,
       mailaddress.street mail_street,
       d.DEPARTMENT_ID,
       d.DEPARTMENTNUMBER,
       d.DESCRIPTION DEPARTMENTDESCRIPTION,
       dp.DISTRIBUTIONPOINTNUMBER,
       dp.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
       dvp.DELIVERYPOINT_ID,
       dvp.CODE DELIVERYPOINTCODE,
       dvp.DESCRIPTION DELIVERYPOINTDESCRIPTION,
       R.CODEONLABEL,
       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,
       (select tad.description from transportarticle_desc tad where tad.transportarticle_id = ta.transportarticle_id and tad.language_id = l.language_id) transportarticledescription
       ,( select p.code from plant p where R.Plant_id=p.plant_id)plcode
  from customer          c,
       department        d,
       distributionpoint dp,
       deliverypoint     dvp,
       address           a,
       address           mailaddress
  , LANGUAGES L
  , REPORTPARAM RP left outer join ROUTE R on  RP.Number_Value1 = R.Route_Id
  , ADDRESS DELPOINT_ADDRESS
  , standarddelivery sdd, transportarticle ta
 where c.customer_id = d.customer_id
   and d.department_id = dp.department_id
   and c.visitaddress_id = a.address_id
   and RP.Number_Value = dp.distributionpoint_id
   and RP.Number_Value4 = dvp.deliverypoint_id
   and RP.String_Value2 = L.CODE
   and DVP.DELIVERYADDRESS_ID = DELPOINT_ADDRESS.ADDRESS_ID
   and C.MAILADDRESS_ID = MAILADDRESS.ADDRESS_ID
   and sdd.distributionpoint_id = dp.distributionpoint_id
  and sdd.sequencenumber = 1
  and sdd.transportarticle_id = ta.transportarticle_id

/
create or replace view V_CONTAINERSTICKER_ADV_STX
 (CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, PHONENO, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTREET2, CUSTOMERSTATE, CUSTOMERCOUNTY, DEPARTMENT_ID, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, 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, DEPOTDESCRIPTION, USAGEDAYNUMBER, USAGEDAYDESC, CP_LABELCOLOR, INTERNALREMARKFORTRANSPLABEL, TRANSPLABINTERNALREMARKENDDATE, EXTERNALREMARKFORTRANSPLABEL, TRANSPLABEXTERNALREMARKENDDATE, NOOFTRANSPORTLABELS, CU_LABELCOLOR, BATCHNUMBER)
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,
       d.DEPARTMENT_ID, d.DEPARTMENTNUMBER, d.DESCRIPTION DEPARTMENTDESCRIPTION,
       dp.DISTRIBUTIONPOINTNUMBER, dp.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
       dvp.DELIVERYPOINT_ID, dvp.CODE DELIVERYPOINTCODE, dvp.DESCRIPTION DELIVERYPOINTDESCRIPTION,
       (SELECT DD.DESCRIPTION FROM DAY_DESC DD WHERE DD.DAY_ID = R.DRIVINGDAY_ID AND DD.LANGUAGE_ID = L.LANGUAGE_ID) DRIVINGDAY_DESC,
       R.ROUTENUMBER, R.DESCRIPTION ROUTEDESCRIPTION, R.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, DE.DESCRIPTION DEPOTDESCRIPTION
, (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 = l.language_id) usagedaydesc
, dp.labelcolor cp_labelcolor, dp.internalremarkfortransplabel
, dp.transplabinternalremarkenddate, dp.externalremarkfortransplabel
, dp.transplabexternalremarkenddate, dp.nooftransportlabels
, c.labelcolor cu_labelcolor
, (select max(ds.batchnumber) from deliveryscan ds, packingnote pn where ds.packingnote_id = pn.Packingnote_Id and pn.ROUTE_ID = R.ROUTE_ID
  and pn.DISTRIBUTIONPOINT_ID = dp.DISTRIBUTIONPOINT_ID AND pn.DELIVERYPOINT_ID = dvp.DELIVERYPOINT_ID) BatchNumber
from customer c, department d, distributionpoint dp, deliverypoint dvp, address a,
     ROUTE R LEFT OUTER JOIN DEPOT DE ON R.DEPOT_ID=DE.DEPOT_ID   --TODO7736
     , LANGUAGES L, REPORTPARAM RP
     ,  ADDRESS DELPOINT_ADDRESS
where c.customer_id = d.customer_id
      and d.department_id = dp.department_id
      and dp.deliverypoint_id = dvp.deliverypoint_id
      and c.visitaddress_id = a.address_id
      and RP.Number_Value = dp.distributionpoint_id
      and RP.Number_Value1 = R.Route_Id
      and RP.String_Value2 = L.CODE
      AND DVP.DELIVERYADDRESS_ID = DELPOINT_ADDRESS.ADDRESS_ID

/
create or replace view V_CONTAINERSTICKER_BDE
 (CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, PHONENO, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTREET2, CUSTOMERSTATE, CUSTOMERCOUNTY, DEPARTMENT_ID, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, 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, ROUTESTOP_ID, STOPNUMBER, PLANTDEPARTMENTCODE, PLANTDEPARTMENTDESCRIPTION, REMARK, NUMBERSTICKERS, TRANSPORTARTICLECODE, TRANSPORTARTICLEDESC, DUMMYGRP)
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,
       d.DEPARTMENT_ID, d.DEPARTMENTNUMBER, d.DESCRIPTION DEPARTMENTDESCRIPTION,
       dp.DISTRIBUTIONPOINTNUMBER, dp.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
       dvp.DELIVERYPOINT_ID, dvp.CODE DELIVERYPOINTCODE, dvp.DESCRIPTION DELIVERYPOINTDESCRIPTION,
       (SELECT DD.DESCRIPTION FROM DAY_DESC DD WHERE DD.DAY_ID = R.DRIVINGDAY_ID AND DD.LANGUAGE_ID = L.LANGUAGE_ID) DRIVINGDAY_DESC,
       R.ROUTENUMBER, R.DESCRIPTION ROUTEDESCRIPTION, R.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
, rs.routestop_id, rs.stopnumber
, pd.Code PlantDepartmentCode, pd.Description PlantDepartmentDescription
, cps.remark, cps.numberstickers
, ta.Code TransportArticleCode
, (select tad.Description from transportarticle_desc tad where ta.transportarticle_id = tad.transportarticle_id and tad.language_id = l.language_id) TransportArticleDesc
, RP.String_Value dummyGRP
from customer c, department d, distributionpoint dp, deliverypoint dvp, address a
     , ROUTE R, LANGUAGES L, REPORTPARAM RP, ADDRESS DELPOINT_ADDRESS
     , Routestop RS, StandardDelivery sd, PlantDepartment pd
     , ContainersPerStop cps, TransportArticle ta, Stop st
where c.customer_id = d.customer_id
      and d.department_id = dp.department_id
      and dp.deliverypoint_id = dvp.deliverypoint_id
      and c.visitaddress_id = a.address_id
      and RP.Number_Value = dp.distributionpoint_id
      and RP.Number_Value1 = R.Route_Id
      and RP.String_Value2 = L.CODE
      AND DVP.DELIVERYADDRESS_ID = DELPOINT_ADDRESS.ADDRESS_ID
      and rs.route_id = r.route_id and st.routestop_id = rs.routestop_id
      and rs.customer_id = c.customer_id
      and dp.distributionpoint_id = sd.distributionpoint_id
      and pd.plantdepartment_id = sd.plantdepartment_id
      and cps.stop_id  = st.stop_id
      and cps.distributionpoint_link_id = dp.distributionpoint_id
      and ta.transportarticle_id = cps.transportarticle_id
--order by RP.Reportparam_Id, c.customernumber, d.departmentnumber, dp.distributionpointnumber, rp.copy_number

/
create or replace view V_CONTAINERSTICKER_CIW
 (CORRECTEDNOTENUMBER, NOTENUMBER, 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, DRIVINGDAY_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)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER, PACKINGNOTE.NOTENUMBER,
PACKINGNOTE.SEQUENCENUMBER,
PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK,
PACKINGNOTE.STOPNUMBER,
PACKINGNOTE.PACKINGNOTE_ID,
PACKINGNOTE.ENDDATEFORUSE, PACKINGNOTE.ORIGIN,
PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME, CUSTOMER.PHONENO,
ADDRESS.STREET CUSTOMERSTREET, ADDRESS.ZIPCODE CUSTOMERZIP, ADDRESS.CITY CUSTOMERCITY,
ADDRESS.STREET2 CUSTOMERSTREET2, ADDRESS.STATE CUSTOMERSTATE, ADDRESS.COUNTY CUSTOMERCOUNTY,
MAILADRESS.STREET MAIL_STREET, MAILADRESS.ZIPCODE MAIL_ZIPCODE, MAILADRESS.CITY MAIL_CITY,
MAILADRESS.STATE MAIL_STATE, MAILADRESS.COUNTY MAIL_COUNTY, MAILADRESS.STREET2 MAIL_STREET2,
DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
PROCESSBU.DESCRIPTION BUDESCRIPTION,
PLANT.NAME PLANTNAME,
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
(SELECT DD.DESCRIPTION FROM DAY_DESC DD WHERE DD.DAY_ID = ROUTE.DRIVINGDAY_ID AND DD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) DRIVINGDAY_DESC,
ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION ROUTEDESCRIPTION, ROUTE.LOADINGDOCK,
LANGUAGES.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,
DEPOT.DESCRIPTION DEPOTDESCRIPTION
, DISTRIBUTIONPOINT.Remarkonpackingnote, DISTRIBUTIONPOINT.Remarkondeliverynote
, (select lan.code from languages lan where CUSTOMER.language_id = lan.language_id) LanguageCodeCustomer
--,  CAST(PACKINGNOTE.WEEK AS VARCHAR2(2)) DeliveryWeek
, DISTRIBUTIONPOINT.Labelcolor cp_labelcolor, DISTRIBUTIONPOINT.Internalremarkfortransplabel
, DISTRIBUTIONPOINT.Transplabinternalremarkenddate, DISTRIBUTIONPOINT.Externalremarkfortransplabel
, DISTRIBUTIONPOINT.Transplabexternalremarkenddate, DISTRIBUTIONPOINT.Nooftransportlabels
, (select dud.usageday_id from departmentusageday dud where dud.department_id = department.department_id and dud.day_id = route.drivingday_id) usagedaynumber
, (select dd.description from departmentusageday dud, day_desc dd where dud.department_id = department.department_id and dud.usageday_id = dd.day_id and dud.day_id = route.drivingday_id and dd.language_id = languages.language_id) usagedaydesc
, CUSTOMER.labelcolor cu_labelcolor
FROM  CUSTOMER,
        ADDRESS, DEPARTMENT, DISTRIBUTIONPOINT, ADDRESS MAILADRESS,
        PLANT, ADDRESS PLANTADDRESS,
        BUSINESSUNIT PROCESSBU, DELIVERYPOINT,
        PACKINGNOTE
        LEFT OUTER JOIN ROUTE
        LEFT OUTER JOIN DEPOT ON ROUTE.DEPOT_ID=DEPOT.DEPOT_ID    --TODO7736
        ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID,
        LANGUAGES,
        ADDRESS DELPOINT_ADDRESS
  WHERE PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
  AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
  AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND CUSTOMER.VISITADDRESS_ID = ADDRESS.ADDRESS_ID
  AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND CUSTOMER.MAILADDRESS_ID = MAILADRESS.ADDRESS_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = DELPOINT_ADDRESS.ADDRESS_ID

/
create or replace view V_CONTAINERSTICKER_DFD
 (BARCODE, PACKINGNOTE_ID, NOTENUMBER, DELIVERYDATE, CUSTOMERNUMBER, CUSTOMERNAME, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, ROUTENUMBER, STOPNUMBER)
as SELECT
       PC.BAGLABELIDCODE BARCODE,
       P.PACKINGNOTE_ID,
       P.NOTENUMBER,
       P.DELIVERYDATE,
       C.CUSTOMERNUMBER,
       C.NAME CUSTOMERNAME,
       DELP.CODE DELIVERYPOINTCODE,
       DELP.DESCRIPTION DELIVERYPOINTDESCRIPTION,
       R.ROUTENUMBER,
       P.STOPNUMBER
 FROM PACKINGNOTE P
       LEFT OUTER JOIN ROUTE R ON P.ROUTE_ID = R.ROUTE_ID,
       PACKINGNOTECONTAINER PC,
       CUSTOMER C,
       DEPARTMENT D,
       DISTRIBUTIONPOINT DP,
       DELIVERYPOINT DELP
       WHERE PC.PACKINGNOTE_ID = P.PACKINGNOTE_ID
   AND DP.DISTRIBUTIONPOINT_ID = P.DISTRIBUTIONPOINT_ID
   AND D.DEPARTMENT_ID = DP.DEPARTMENT_ID
   AND C.CUSTOMER_ID = D.CUSTOMER_ID
   AND DELP.DELIVERYPOINT_ID = P.DELIVERYPOINT_ID
   AND PC.BAGLABELIDCODE IS NOT NULL

/
create or replace view V_CONTAINERSTICKER_LTS
 (CORRECTEDNOTENUMBER, NOTENUMBER, 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, DRIVINGDAY_DESC, ROUTENUMBER, ROUTEDESCRIPTION, LOADINGDOCK, LANGUAGECODE, DELPOINT_STREET, DELPOINT_STREET2, DELPOINT_ZIPCODE, DELPOINT_CITY, DELPOINT_STATE, DELPOINT_COUNTY, DEPOTDESCRIPTION, REMARKONPACKINGNOTE, REMARKONDELIVERYNOTE, LANGUAGECODECUSTOMER, DELIVERYWEEK, LABELCOLOR, INTERNALREMARKFORTRANSPLABEL
, TRANSPLABINTERNALREMARKENDDATE, EXTERNALREMARKFORTRANSPLABEL, TRANSPLABEXTERNALREMARKENDDATE, NOOFTRANSPORTLABELS, DRIVINGDAY_ID, USAGEDAYNUMBER, USAGEDAYDESC, CU_LABELCOLOR)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER, PACKINGNOTE.NOTENUMBER,
PACKINGNOTE.SEQUENCENUMBER,
PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK,
PACKINGNOTE.STOPNUMBER,
PACKINGNOTE.PACKINGNOTE_ID,
PACKINGNOTE.ENDDATEFORUSE, PACKINGNOTE.ORIGIN,
PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME, CUSTOMER.PHONENO,
ADDRESS.STREET CUSTOMERSTREET, ADDRESS.ZIPCODE CUSTOMERZIP, ADDRESS.CITY CUSTOMERCITY,
ADDRESS.STREET2 CUSTOMERSTREET2, ADDRESS.STATE CUSTOMERSTATE, ADDRESS.COUNTY CUSTOMERCOUNTY,
MAILADRESS.STREET MAIL_STREET, MAILADRESS.ZIPCODE MAIL_ZIPCODE, MAILADRESS.CITY MAIL_CITY,
MAILADRESS.STATE MAIL_STATE, MAILADRESS.COUNTY MAIL_COUNTY, MAILADRESS.STREET2 MAIL_STREET2,
DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
PROCESSBU.DESCRIPTION BUDESCRIPTION,
PLANT.NAME PLANTNAME,
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
(SELECT DD.DESCRIPTION FROM DAY_DESC DD WHERE DD.DAY_ID = ROUTE.DRIVINGDAY_ID AND DD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) DRIVINGDAY_DESC,
ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION ROUTEDESCRIPTION, ROUTE.LOADINGDOCK,
LANGUAGES.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,
DEPOT.DESCRIPTION DEPOTDESCRIPTION
, DISTRIBUTIONPOINT.Remarkonpackingnote, DISTRIBUTIONPOINT.Remarkondeliverynote
, (select lan.code from languages lan where CUSTOMER.language_id = lan.language_id) LanguageCodeCustomer
,	CAST(PACKINGNOTE.WEEK AS VARCHAR2(2)) DeliveryWeek
, DISTRIBUTIONPOINT.Labelcolor, DISTRIBUTIONPOINT.Internalremarkfortransplabel
, DISTRIBUTIONPOINT.Transplabinternalremarkenddate, DISTRIBUTIONPOINT.Externalremarkfortransplabel
, DISTRIBUTIONPOINT.Transplabexternalremarkenddate, DISTRIBUTIONPOINT.Nooftransportlabels
, route.drivingday_id
, (select dud.usageday_id from departmentusageday dud where dud.department_id = department.department_id and dud.day_id = route.drivingday_id) usagedaynumber
, (select dd.description from departmentusageday dud, day_desc dd where dud.department_id = department.department_id and dud.usageday_id = dd.day_id and dud.day_id = route.drivingday_id and dd.language_id = languages.language_id) usagedaydesc
, CUSTOMER.labelcolor cu_labelcolor
FROM  CUSTOMER,
        ADDRESS, DEPARTMENT, DISTRIBUTIONPOINT, ADDRESS MAILADRESS,
        PLANT, ADDRESS PLANTADDRESS,
        BUSINESSUNIT PROCESSBU, DELIVERYPOINT,
        PACKINGNOTE
        LEFT OUTER JOIN ROUTE
        LEFT OUTER JOIN DEPOT ON ROUTE.DEPOT_ID=DEPOT.DEPOT_ID
        ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID,
        LANGUAGES, ADDRESS DELPOINT_ADDRESS
  WHERE PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
	AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
	AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND CUSTOMER.VISITADDRESS_ID = ADDRESS.ADDRESS_ID
	AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
	AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND CUSTOMER.MAILADDRESS_ID = MAILADRESS.ADDRESS_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = DELPOINT_ADDRESS.ADDRESS_ID

/
create or replace view V_CONTAINERSTICKER_REV
 (CORRECTEDNOTENUMBER, NOTENUMBER, 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, DRIVINGDAY_DESC, ROUTENUMBER, ROUTEDESCRIPTION, LOADINGDOCK, LANGUAGECODE, DELPOINT_STREET, DELPOINT_STREET2, DELPOINT_ZIPCODE, DELPOINT_CITY, DELPOINT_STATE, DELPOINT_COUNTY, DEPOTDESCRIPTION, STARTTIME, ENDTIME, TOBEDELIVEREDAMOUNT, DELIVEREDAMOUNT, PRODUCTCODE, PRODUCTDESC, PACKINGEMPLOYEE
, ARRIVALTIME)
as select
packingnote.correctednotenumber, packingnote.notenumber,
packingnote.sequencenumber,
packingnote.deliverydate,
packingnote.originaldeliverydate, packingnote.remark,
packingnote.stopnumber,
packingnote.packingnote_id,
packingnote.enddateforuse, packingnote.origin,
packingnote.productiondate productiondate,
packingnote.numberofgarmentsinlocker, packingnote.numberoflockers,
customer.customernumber, customer.name customername, customer.legalname, customer.phoneno,
address.street customerstreet, address.zipcode customerzip, address.city customercity,
address.street2 customerstreet2, address.state customerstate, address.county customercounty,
mailadress.street mail_street, mailadress.zipcode mail_zipcode, mailadress.city mail_city,
mailadress.state mail_state, mailadress.county mail_county, mailadress.street2 mail_street2,
department.departmentnumber, department.description departmentdescription,
distributionpoint.distributionpointnumber, distributionpoint.description distributionpointdescription,
deliverypoint.code deliverypointcode, deliverypoint.description deliverypointdescription,
processbu.description budescription,
plant.name plantname,
plantaddress.street plantstreet, plantaddress.zipcode plantzipcode,
plantaddress.city plantcity, plant.phoneno plantphoneno, plant.faxno plantfaxno,
(select dd.description from day_desc dd where dd.day_id = route.drivingday_id and dd.language_id = languages.language_id) drivingday_desc,
route.routenumber, route.description routedescription, route.loadingdock,
languages.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,
depot.description depotdescription
, route.starttime, route.endtime, pnl.tobedeliveredamount, pnl.deliveredamount
, (select pr.code from product pr where pnl.product_id = pr.product_id) ProductCode
, (select prd.description from product_desc prd where pnl.product_id = prd.product_id and prd.language_id = languages.language_id) ProductDesc
, (select emp.name from employee emp where packingnote.employee_id = emp.employee_id) PackingEmployee
, (select to_char(st.arrivaltime,'fmhh24fm:MI') from stop st where st.stop_id = packingnote.stop_id) ArrivalTime
from  customer,
        address, department, distributionpoint, address mailadress,
        plant, address plantaddress,
        businessunit processbu, deliverypoint,
        packingnote
        left outer join route
             left outer join depot on route.depot_id=depot.depot_id    --todo7736
        on packingnote.route_id = route.route_id
        left outer join packingnoteline pnl on packingnote.packingnote_id = pnl.packingnote_id,
        languages,
        address delpoint_address
  where packingnote.distributionpoint_id = distributionpoint.distributionpoint_id
  and distributionpoint.department_id = department.department_id
  and department.customer_id = customer.customer_id
  and customer.visitaddress_id = address.address_id
  and packingnote.deliverypoint_id = deliverypoint.deliverypoint_id
  and packingnote.processbusinessunit_id = processbu.businessunit_id
  and processbu.plant_id = plant.plant_id
  and plant.address_id = plantaddress.address_id
  and customer.mailaddress_id = mailadress.address_id
  and deliverypoint.deliveryaddress_id = delpoint_address.address_id

/
create or replace view V_CONTAINERSTICKER_SMG
 (CORRECTEDNOTENUMBER, NOTENUMBER, SEQUENCENUMBER, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, STOPNUMBER, PACKINGNOTE_ID, ENDDATEFORUSE, ORIGIN, PRODUCTIONDATE, NUMBEROFGARMENTSINLOCKER, NUMBEROFLOCKERS, CUSTOMERNUMBER, CUSTOMERNAME, SEARCHNAME, 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, DRIVINGDAY_DESC, ROUTENUMBER, ROUTEDESCRIPTION, LOADINGDOCK, CODEONLABEL, LANGUAGECODE, DELPOINT_STREET, DELPOINT_STREET2, DELPOINT_ZIPCODE, DELPOINT_CITY, DELPOINT_STATE, DELPOINT_COUNTY, LANGUAGECODECUSTOMER, USAGEDAYNUMBER, USAGEDAYDESC, CU_LABELCOLOR, TRANSPORTARTICLEDESCRIPTION, PLCODE
)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER, PACKINGNOTE.NOTENUMBER,
PACKINGNOTE.SEQUENCENUMBER,
PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK,
PACKINGNOTE.STOPNUMBER,
PACKINGNOTE.PACKINGNOTE_ID,
PACKINGNOTE.ENDDATEFORUSE, PACKINGNOTE.ORIGIN,
PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
insertspace_after_x_characters(CUSTOMER.CUSTOMERNUMBER,3) CUSTOMERNUMBER,
CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.SEARCHNAME, CUSTOMER.LEGALNAME, CUSTOMER.PHONENO,
ADDRESS.STREET CUSTOMERSTREET, ADDRESS.ZIPCODE CUSTOMERZIP, ADDRESS.CITY CUSTOMERCITY,
ADDRESS.STREET2 CUSTOMERSTREET2, ADDRESS.STATE CUSTOMERSTATE, ADDRESS.COUNTY CUSTOMERCOUNTY,
MAILADRESS.STREET MAIL_STREET, MAILADRESS.ZIPCODE MAIL_ZIPCODE, MAILADRESS.CITY MAIL_CITY,
MAILADRESS.STATE MAIL_STATE, MAILADRESS.COUNTY MAIL_COUNTY, MAILADRESS.STREET2 MAIL_STREET2,
DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
PROCESSBU.DESCRIPTION BUDESCRIPTION,
PLANT.NAME PLANTNAME,
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
(SELECT DD.DESCRIPTION FROM DAY_DESC DD WHERE DD.DAY_ID = ROUTE.DRIVINGDAY_ID AND DD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) DRIVINGDAY_DESC,
ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION ROUTEDESCRIPTION, ROUTE.LOADINGDOCK,
ROUTE.CODEONLABEL,
LANGUAGES.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
, (select lan.code from languages lan where CUSTOMER.language_id = lan.language_id) LanguageCodeCustomer
, (select dud.usageday_id from departmentusageday dud where dud.department_id = department.department_id and dud.day_id = route.drivingday_id) usagedaynumber
, (select dd.description from departmentusageday dud, day_desc dd where dud.department_id = department.department_id and dud.usageday_id = dd.day_id and dud.day_id = route.drivingday_id and dd.language_id = languages.language_id) usagedaydesc
, CUSTOMER.labelcolor cu_labelcolor
, (select tad.description from transportarticle_desc tad where tad.transportarticle_id = ta.transportarticle_id and tad.language_id = languages.language_id) transportarticledescription
, ( select p.code from plant p where PROCESSBU.Plant_id=p.plant_id)plcode
FROM  CUSTOMER,
        ADDRESS, DEPARTMENT, DISTRIBUTIONPOINT, ADDRESS MAILADRESS,
        PLANT, ADDRESS PLANTADDRESS,
        BUSINESSUNIT PROCESSBU, DELIVERYPOINT,
        PACKINGNOTE
        LEFT OUTER JOIN ROUTE
        ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID,
        LANGUAGES,
        ADDRESS DELPOINT_ADDRESS,
        standarddelivery sdd,
        transportarticle ta
  WHERE PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
  AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
  AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND CUSTOMER.VISITADDRESS_ID = ADDRESS.ADDRESS_ID
  AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND CUSTOMER.MAILADDRESS_ID = MAILADRESS.ADDRESS_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = DELPOINT_ADDRESS.ADDRESS_ID
  and sdd.distributionpoint_id = packingnote.distributionpoint_id
  and sdd.sequencenumber = 1
  and sdd.transportarticle_id = ta.transportarticle_id

/
create or replace view V_CONTAINERSTICKER_STX
 (CORRECTEDNOTENUMBER, NOTENUMBER, 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, DRIVINGDAY_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, BATCHNUMBER)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER, PACKINGNOTE.NOTENUMBER,
PACKINGNOTE.SEQUENCENUMBER,
PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK,
PACKINGNOTE.STOPNUMBER,
PACKINGNOTE.PACKINGNOTE_ID,
PACKINGNOTE.ENDDATEFORUSE, PACKINGNOTE.ORIGIN,
PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME, CUSTOMER.PHONENO,
ADDRESS.STREET CUSTOMERSTREET, ADDRESS.ZIPCODE CUSTOMERZIP, ADDRESS.CITY CUSTOMERCITY,
ADDRESS.STREET2 CUSTOMERSTREET2, ADDRESS.STATE CUSTOMERSTATE, ADDRESS.COUNTY CUSTOMERCOUNTY,
MAILADRESS.STREET MAIL_STREET, MAILADRESS.ZIPCODE MAIL_ZIPCODE, MAILADRESS.CITY MAIL_CITY,
MAILADRESS.STATE MAIL_STATE, MAILADRESS.COUNTY MAIL_COUNTY, MAILADRESS.STREET2 MAIL_STREET2,
DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
PROCESSBU.DESCRIPTION BUDESCRIPTION,
PLANT.NAME PLANTNAME,
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
(SELECT DD.DESCRIPTION FROM DAY_DESC DD WHERE DD.DAY_ID = ROUTE.DRIVINGDAY_ID AND DD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) DRIVINGDAY_DESC,
ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION ROUTEDESCRIPTION, ROUTE.LOADINGDOCK,
LANGUAGES.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,
DEPOT.DESCRIPTION DEPOTDESCRIPTION
, DISTRIBUTIONPOINT.Remarkonpackingnote, DISTRIBUTIONPOINT.Remarkondeliverynote
, (select lan.code from languages lan where CUSTOMER.language_id = lan.language_id) LanguageCodeCustomer
, DISTRIBUTIONPOINT.Labelcolor cp_labelcolor, DISTRIBUTIONPOINT.Internalremarkfortransplabel
, DISTRIBUTIONPOINT.Transplabinternalremarkenddate, DISTRIBUTIONPOINT.Externalremarkfortransplabel
, DISTRIBUTIONPOINT.Transplabexternalremarkenddate, DISTRIBUTIONPOINT.Nooftransportlabels
, (select dud.usageday_id from departmentusageday dud where dud.department_id = department.department_id and dud.day_id = route.drivingday_id) usagedaynumber
, (select dd.description from departmentusageday dud, day_desc dd where dud.department_id = department.department_id and dud.usageday_id = dd.day_id and dud.day_id = route.drivingday_id and dd.language_id = languages.language_id) usagedaydesc
, CUSTOMER.labelcolor cu_labelcolor,
route.drivingday_id day_id
, (select max(ds.batchnumber) from deliveryscan ds where ds.packingnote_id = PACKINGNOTE.Packingnote_Id) BatchNumber
FROM  CUSTOMER,
        ADDRESS, DEPARTMENT, DISTRIBUTIONPOINT, ADDRESS MAILADRESS,
        PLANT, ADDRESS PLANTADDRESS,
        BUSINESSUNIT PROCESSBU, DELIVERYPOINT,
        PACKINGNOTE
        LEFT OUTER JOIN ROUTE
        LEFT OUTER JOIN DEPOT ON ROUTE.DEPOT_ID=DEPOT.DEPOT_ID    --TODO7736
        ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID,
        LANGUAGES,
        ADDRESS DELPOINT_ADDRESS
  WHERE PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
	AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
	AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND CUSTOMER.VISITADDRESS_ID = ADDRESS.ADDRESS_ID
	AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
	AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND CUSTOMER.MAILADDRESS_ID = MAILADRESS.ADDRESS_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = DELPOINT_ADDRESS.ADDRESS_ID

/
create or replace view V_CONTRACTDATES_LLG
 (BU_CODE, CUSTOMERNUMBER, CUSTOMERNAME, STARTDATE, NEXTNEGOCIATIONDATE, CONTRACTCODE, LASTNEGOCIATIONDATE)
as select (select bu.code from businessunit bu where bu.businessunit_id = c.defaultbusinessunit_id) bu_code,
c.customernumber,
c.name customername,
cpc.dateactive startdate,
cpc.dateinactive nextnegociationdate,
cpc.code contractcode,
(select max(cpc3.dateactive) from contractspercustomer cpc3 where cpc3.customer_id = cpc.customer_id and cpc3.code <> cpc.code) lastnegociationdate
from contractspercustomer cpc inner join customer c
on cpc.customer_id = c.customer_id
group by cpc.customer_id, c.customernumber, c.name, cpc.code, cpc.dateactive, cpc.dateinactive, c.defaultbusinessunit_id
having cpc.code = (select max(cpc2.code) from contractspercustomer cpc2 where cpc.customer_id = cpc2.customer_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_CORRRDNLINE_SMG
 (PACKINGNOTE_ID, PACKINGNOTELINE_ID, PACKINGNOTENUMBER, PRODUCTCODE, PRODUCTDESCRIPTION, PRODUCTCUSTOMCODE, SIZECODE, FINISHINGMETHODCODE, DELIVEREDAMOUNT, LANGUAGECODE, REGUNIT, OLD_QTY)
as SELECT PACKINGNOTE.PACKINGNOTE_ID,PACKINGNOTELINE.PACKINGNOTELINE_ID,
 PACKINGNOTE.NOTENUMBER PACKINGNOTENUMBER, PRODUCT.CODE PRODUCTCODE,
       (SELECT DESCRIPTION
         FROM   PRODUCT_DESC P
         WHERE  P.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
PRODUCTDESCRIPTION, PACKINGNOTELINE.CUSTOMCODE,  SIZEDEFINITION.CODE,
 (SELECT CODE FROM FINISHINGMETHOD F
         WHERE  F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID) FINISHINGMETHODCODE,
PACKINGNOTELINE.DELIVEREDAMOUNT,  LANGUAGES.CODE,
(SELECT RG.CODE
 FROM   REGISTRATIONUNIT RG
 WHERE  RG.REGISTRATIONUNIT_ID = PRODUCT.REGISTRATIONUNIT_ID) REGUNIT,
(CASE
  WHEN PACKINGNOTE.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 = PACKINGNOTELINE.PRODUCT_ID AND
           PAL.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND
           PAL.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID AND
           PA.NOTENUMBER = PACKINGNOTE.CORRECTEDNOTENUMBER)
END) OLD_QTY
FROM   PACKINGNOTELINE, PACKINGNOTE ,PRODUCT, SIZEDEFINITION, LANGUAGES
WHERE  PACKINGNOTELINE.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID AND
       PACKINGNOTELINE.PRODUCT_ID = PRODUCT.PRODUCT_ID AND
       PACKINGNOTELINE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
       and PACKINGNOTE.packingnote_id=PACKINGNOTELINE.packingnote_id
       and PACKINGNOTE.Origin =3
       and exists (select 1 from packingnote a where PACKINGNOTE.Correctionfornote_Id=a.packingnote_id and a.origin=13)

/
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, ADJUSTMENTPERMITED, 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.adjustmentpermited, 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_COSTCENTERINVOICELINE_BDE
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, TAXGROUPCODE, TAXTYPE, SUBJECTTOMINIMUM, INVOICELINESUBTYPE, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PRODUCTSHORTDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODCODE, FINISHINGMETHODDESCRIPTION, INVOICEQTYCOLUMN, INVENTORYQTY, DELIVEREDQTY
, ABUSEDQUANTITY, SOILQUANTITY, SOILCOUNTMETHOD, BILLINGMETHOD, WEARERNUMBER, WEARERNAME, WEARERADMINNR, WEARERBANK, WEARERLOCKER, SYSTEMUSER_ID, TIMESTAMP, INVOICELINE_ID, REMARK, LANGUAGECODE, INVOICEHEADER_ID, COSTCENTER_CODE, COSTCENTER_DESCRIPTION, COSTCENTERINVOICELINE_QUANTITY, COSTCENTERINVOICELINE_AMOUNT, COSTCENTER_LINK_ID, SEQUENCENUMBER, NEXTPERIODSTARTDATE, INVOICEFREQUENCYNUMBER, PARENTINVOICEHEADER_ID, INVOICECOMMENTS, NEXTPERIODSTARTWEEK
, NEXTPERIODENDWEEK, INVOICELAYOUTCODE, BILLTOCOUNTRYDESCRIPTION, INV_BU_CODE, INV_BU_DESC, FREQUENCY, MIN_WEEK, MIN_YEAR, MAX_WEEK, MAX_YEAR, CRI_WEEK, CRI_YEAR, CRI_QUANTITY)
as select f.invoicedate, f.invoicenumber, a.linenumber, 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.adjustmentpermited, 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,
cc.code costcenter_code, cc.description 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
, f.nextperiodstartdate, f.invoicefrequency_id invoicefrequencynumber, f.parentinvoiceheader_id
, f.invoicecomments, f.nextperiodstartweek, f.nextperiodendweek
, ihe.formlayoutcode INVOICELAYOUTCODE, ihe.billtocountrydescription
, ibu.code Inv_bu_code, ibu.description Inv_bu_desc
, (case
  when e.type = 1 and a.invoicelinesubtype = 0
  then FGET_BDE_FRECV(f.deltocustomer_link_id, b.product_link_id, b.sizedefinition_link_id, b.finishingmethod_id, f.invoicedate, b.deliveryschemecode)
  else -1
  end ) Frequency
, -1 Min_week
, -1 Min_year
, -1 Max_week
, -1 Max_year
, g.WEEK CRI_week
, g.YEAR CRI_year
, g.QUANTITY CRI_quantity
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)
LEFT OUTER JOIN costreportinfo g ON (a.invoiceline_id = g.invoiceline_id),
invoicelinetype e, invoiceheader f, LANGUAGES,
costcenterinvoiceline ccil, costcenter_link cc
, businessunit ibu, invoiceheaderextrainfo ihe
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 f.invoicebusinessunit_id = ibu.businessunit_id
and ihe.invoiceheader_id = f.invoiceheader_id
and f.nextperiodstartdate is null
union all
select f.invoicedate, f.invoicenumber, a.linenumber, 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.adjustmentpermited, 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,
cc.code costcenter_code, cc.description 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
, f.nextperiodstartdate, f.invoicefrequency_id invoicefrequencynumber, f.parentinvoiceheader_id
, f.invoicecomments, f.nextperiodstartweek, f.nextperiodendweek
, ihe.formlayoutcode INVOICELAYOUTCODE, ihe.billtocountrydescription
, ibu.code Inv_bu_code, ibu.description Inv_bu_desc
, (case
  when e.type = 1 and a.invoicelinesubtype = 0
  then FGET_BDE_FRECV(f.deltocustomer_link_id, b.product_link_id, b.sizedefinition_link_id, b.finishingmethod_id, f.invoicedate, b.deliveryschemecode)
  else -1
  end ) Frequency
, (select min(cr.week)
from costreportinfo cr
where cr.invoiceline_id = a.invoiceline_id and cr.year in (select min(cri.year) from costreportinfo cri where cri.invoiceline_id = a.invoiceline_id)) Min_week
, (select min(cri.year) from costreportinfo cri where cri.invoiceline_id = a.invoiceline_id) Min_year
, (select max(cr.week)
from costreportinfo cr
where cr.invoiceline_id = a.invoiceline_id and cr.year in (select max(cri.year) from costreportinfo cri where cri.invoiceline_id = a.invoiceline_id)) Max_week
, (select max(cri.year) from costreportinfo cri where cri.invoiceline_id = a.invoiceline_id) Max_year
, -1 CRI_week
, -1 CRI_year
, -1 CRI_quantity
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
, costcenterinvoiceline ccil, costcenter_link cc
, businessunit ibu, invoiceheaderextrainfo ihe
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 f.invoicebusinessunit_id = ibu.businessunit_id
and ihe.invoiceheader_id = f.invoiceheader_id
and f.nextperiodstartdate is not null

/
create or replace view V_COSTCENTERINVOICELINE_CIW
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, INVOICELINETYPEDESC_WASH, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, TAXGROUPCODE, TAXGROUPDESC, 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)
as select f.invoicedate, f.invoicenumber, a.linenumber,
       e.type invoicelinetype,
       (select description
         from   invoicelinetype_desc z
         where  z.invoicelinetype_id = a.invoicelinetype_id
         and    z.language_id = languages.language_id) invoicelinetypedesc,
       (select iltd.description from invoicelinetype_desc iltd
         where iltd.invoicelinetype_id = 2 and iltd.language_id = languages.language_id) invoicelinetypedesc_wash,
       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.adjustmentpermited, a.taxgroupcode,
       (select tg.description from taxgroup tg where tg.code = 'SSTD') taxgroupdesc,
       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
from   invoiceheader f, invoiceline a, invoicelinetype e, 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    a.invoicelinetype_id = e.invoicelinetype_id
and    f.documenttype = 1
and    ccil.invoiceline_id = a.invoiceline_id

/
create or replace view V_COSTCENTERINVOICELINE_HOW
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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, CORRECTED_INVOICEHEADER_ID, STARTDATE, ENDDATE, NOOFDAYS, INVPERIODPRICE, RENTPERIODPRICETYPE)
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.adjustmentpermited, 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 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, b.corrected_invoiceheader_id,
 b.startdate, b.enddate, getdatediff(b.enddate, b.startdate)+1 noofdays ,
(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,
(select max(ild.rentperiodpricetype) from invoicelinedetail ild where  a.invoiceheader_id=ild.invoiceheader_id
        and a.invoiceline_id=ild.invoiceline_id) rentperiodpricetype
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_COSTCENTERINVOICELINE_LTS
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, BILLTOCUSTOMERNUMBER, PREBILLAMOUNT, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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, INVLINESUBTYPEDESC, COSTCENTER_CODE, COSTCENTER_DESCRIPTION, COSTCENTERINVOICELINE_QUANTITY
, COSTCENTERINVOICELINE_AMOUNT, COSTCENTER_LINK_ID, REGISTRATIONUNITDESCRIPTION, SEQUENCENUMBER, TOTALAMOUNTEXCLVAT, PRICEFACTOR, SUPRESSPRINTING, ACTIVITYDESC, ACTIVITYCODE, TAXRATE, ACTIVITYREFERENCE)
as select f.invoicedate, f.invoicenumber, a.linenumber, f.billtocustomernumber, f.prebillamount,
       (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.adjustmentpermited, 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,
			 coalesce((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),
			          (select ils.factorydescription
			          from invoicelinesubtype ils
			          where ils.invoicelinetype_id = a.invoicelinetype_id
			          and ils.subtype = a.invoicelinesubtype)) invlinesubtypedesc,
       (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 rud.description
         from product pr, registrationunit_desc rud
        where b.product_link_id = pr.product_id
          and pr.registrationunit_id = rud.registrationunit_id
          and rud.language_id = languages.language_id) registrationunitdescription,
       (select pilt.sequencenumber
         from   plantinvoicelinetype pilt, businessunit bu
         where  f.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,
         b.pricefactor, e.supressprinting,
       case
         when e.type in (6, 12, 23, 28) then
          (select ad.description
             from activity_desc ad, activity ac
            where ac.code = '009'
              and ac.activity_id = ad.activity_id
              and ad.language_id = languages.language_id)
         when e.type in (7, 8, 9, 10, 11, 19, 20, 22, 24, 25) then
          (select ad.description
             from activity_desc ad, activity ac
            where ac.code = '008'
              and ac.activity_id = ad.activity_id
              and ad.language_id = languages.language_id)
         else
          (select ad.description
             from activity_desc ad, productgroup pg
            where b.productgroupcode = pg.code
              and ad.activity_id = pg.activity_id
              and ad.language_id = languages.language_id)
       end ActivityDesc,
       case
         when e.type in (6, 12, 23, 28) then
          '009'
         when e.type in (7, 8, 9, 10, 11, 19, 20, 22, 24, 25) then
          '008'
         else
          (select ac.code
             from activity ac, productgroup pg
            where b.productgroupcode = pg.code
              and ac.activity_id = pg.activity_id)
       end ActivityCode,/*
       (select tg.taxrate
          from productgrouptax pgt, taxgroup tg, product p
         where p.productgroup_id = pgt.productgroup_id
           and pgt.taxgroup_id = tg.taxgroup_id
           and b.product_link_id = p.product_id) taxrate,*/
        (select case when f.invoicedate < tg.startdatetaxrate then tg.oldtaxrate
               else tg.taxrate
               end taxrate
         from taxgroup tg, customer bill
         where a.taxgroupcode = tg.code
               and bill.customer_id = f.billtocustomer_link_id
               and tg.country_id = bill.country_id) taxrate,
        case
         when e.type in (6, 12, 23, 28) then
          (select max(ca.activityreference)
             from customeractivities ca, activity ac
            where ac.code = '009'
              and ac.activity_id = ca.activity_id
              and ca.customer_id = f.deltocustomer_link_id
              and ca.separateinvoice = 'Y')
         when e.type in (7, 8, 9, 10, 11, 19, 20, 22, 24, 25) then
          (select max(ca.activityreference)
             from customeractivities ca, activity ac
            where ac.code = '008'
              and ac.activity_id = ca.activity_id
              and ca.customer_id = f.deltocustomer_link_id
              and ca.separateinvoice = 'Y')
         else
          (select max(ca.activityreference)
             from customeractivities ca, productgroup pg
            where pg.activity_id = ca.activity_id
              and ca.customer_id = f.deltocustomer_link_id
              and ca.separateinvoice = 'Y'
              and b.productgroupcode = pg.code
              and ca.processbusinessunit_id = a.processingbusinessunit_id)
       end activityreference
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, invoicelinetype e
where  a.invoiceheader_id = f.invoiceheader_id
and    a.invoicelinetype_id = e.invoicelinetype_id
and    f.documenttype = 1
and    ccil.invoiceline_id = a.invoiceline_id

/
create or replace view V_COSTCENTERINVOICE_SMG
 (INVOICEDATE, INVOICENUMBER, CHAINCODE, INVOICEHEADER_ID, INVOICEAMOUNTDECIMALS, COSTCENTER_CODE, COSTCENTER_DESCRIPTION, COSTCENTERINVOICELINE_AMOUNT, TOTALAMOUNTEXCLVAT)
as select f.invoicedate,
       f.invoicenumber,
       (select ch.code from chain ch, customer cust where ch.chain_id = cust.chain_id and cust.customer_id = f.deltocustomer_link_id) chaincode,
       a.invoiceheader_id,
       (select curr.invoiceamountdecimals from currency curr where curr.currency_id = f.currency_id) invoiceamountdecimals,
       (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,
       sum(ccil.amount) costcenterinvoiceline_amount,
       (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
  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)
 where a.invoiceheader_id = f.invoiceheader_id
   and f.documenttype = 1
   and ccil.invoiceline_id = a.invoiceline_id
   and f.status_id = (select s.status_id from status s where s.statustype = 'IN' and s.code = '2')
 group by f.invoiceheader_id, a.invoiceheader_id, f.invoicedate, f.invoicenumber, f.deltocustomer_link_id, f.currency_id, ccil.costcenter_link_id

/
create or replace view V_COSTCINVLINECOSTSPEC_LTS
 (INVOICEDATE, INVOICENUMBER, BILLTOCUSTOMERNUMBER, PREBILLAMOUNT, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, TAXGROUPCODE, TAXTYPE, SUBJECTTOMINIMUM, TURNOVERGROUPCODE, TURNOVERGROUPDESCRIPTION, INVOICELINESUBTYPE, INVLINESUBTYPEDESC, 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, ACTIVITYDESC, ACTIVITYCODE, CCCODE, CCDESC, TAXRATE, ACTIVITYREFERENCE, PRICEFACTOR, SUPRESSPRINTING)
as select f.invoicedate,
       f.invoicenumber,
			 f.billtocustomernumber,
			 f.prebillamount,
       a.linenumber,
       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.adjustmentpermited,
       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,
			 coalesce((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),
			          (select ils.factorydescription
			          from invoicelinesubtype ils
			          where ils.invoicelinetype_id = a.invoicelinetype_id
			          and ils.subtype = a.invoicelinesubtype)) invlinesubtypedesc,
       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 rud.description
         from product pr, registrationunit_desc rud
        where b.product_link_id = pr.product_id
          and pr.registrationunit_id = rud.registrationunit_id
          and rud.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 ea.invoicelinetype_id
                  from invoicelinetype ea
                 where ea.type <> 18
                   and ab.invoicelinetype_id = ea.invoicelinetype_id
                   and ccilb.amount <> 0)
         group by a.invoiceheader_id, ccil.costcenter_link_id) totalamountexclvat,
       /*case
         when e.type in (6, 12, 23, 28) then
          '009'
         when e.type in (7, 8, 9, 10, 11, 19, 20, 22, 24, 25) then
          '008'
         else
       (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)),
                ''))
       end activitycode,
       case
         when e.type in (6, 12, 23, 28) then
          '009'
         when e.type in (7, 8, 9, 10, 11, 19, 20, 22, 24, 25) then
          '008'
         else
       (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)
       end activitydesc,*/
       case
         when e.type in (6, 12, 23, 28) then
          (select ad.description
             from activity_desc ad, activity ac
            where ac.code = '009'
              and ac.activity_id = ad.activity_id
              and ad.language_id = languages.language_id)
         when e.type in (7, 8, 9, 10, 11, 19, 20, 22, 24, 25) then
          (select ad.description
             from activity_desc ad, activity ac
            where ac.code = '008'
              and ac.activity_id = ad.activity_id
              and ad.language_id = languages.language_id)
         else
          (select ad.description
             from activity_desc ad, productgroup pg
            where b.productgroupcode = pg.code
              and ad.activity_id = pg.activity_id
              and ad.language_id = languages.language_id)
       end ActivityDesc,
       case
         when e.type in (6, 12, 23, 28) then
          '009'
         when e.type in (7, 8, 9, 10, 11, 19, 20, 22, 24, 25) then
          '008'
         else
          (select ac.code
             from activity ac, productgroup pg
            where b.productgroupcode = pg.code
              and ac.activity_id = pg.activity_id)
       end ActivityCode,
       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,
       /*(select tg.taxrate
          from productgrouptax pgt, taxgroup tg, product p
         where p.productgroup_id = pgt.productgroup_id
           and pgt.taxgroup_id = tg.taxgroup_id
           and b.product_link_id = p.product_id) taxrate,*/
        (select case when f.invoicedate < tg.startdatetaxrate then tg.oldtaxrate
               else tg.taxrate
               end taxrate
         from taxgroup tg, customer bill
         where a.taxgroupcode = tg.code
               and bill.customer_id = f.billtocustomer_link_id
               and tg.country_id = bill.country_id) taxrate,
        case
         when e.type in (6, 12, 23, 28) then
          (select max(ca.activityreference)
             from customeractivities ca, activity ac
            where ac.code = '009'
              and ac.activity_id = ca.activity_id
              and ca.customer_id = f.deltocustomer_link_id
              and ca.separateinvoice = 'Y')
         when e.type in (7, 8, 9, 10, 11, 19, 20, 22, 24, 25) then
          (select max(ca.activityreference)
             from customeractivities ca, activity ac
            where ac.code = '008'
              and ac.activity_id = ca.activity_id
              and ca.customer_id = f.deltocustomer_link_id
              and ca.separateinvoice = 'Y')
         else
          (select max(ca.activityreference)
             from customeractivities ca, productgroup pg
            where pg.activity_id = ca.activity_id
              and ca.customer_id = f.deltocustomer_link_id
              and ca.separateinvoice = 'Y'
              and b.productgroupcode = pg.code
              and ca.processbusinessunit_id = a.processingbusinessunit_id)
       end activityreference,
       b.pricefactor,
       e.supressprinting
from invoiceheader f, invoiceline a, invoicelinetype e,
     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
   and a.invoicelinetype_id = e.invoicelinetype_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_COSTREPORTINVOICELINE_SMG
 (INVOICEHEADER_ID, COSTCENTER_ID, DELTOCUSTOMER_LINK_ID, BILLTOCUSTOMER_LINK_ID, INVOICENUMBER, INVOICELINE_ID, COSTCENTER_CODE, COSTCENTER_DESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTNOLEGALNAME, DELTOCUSTOMERNAME, DELTOCUSTVATNR, COUNTY, STATE, ZIPCODE, STREET, STREET2, CITY, BILLTOCOUNTRYDESCRIPTION, PLANTCOUNTRYDESCRIPTION, ITEM, CODE, QTY, PRICE, AMOUNT, DISCOUNTPERCENTAGE, PRODUCTGR_CODE, SIZECODE, FINISHINGMETHODCODE
, YEAR, WEEK, QUANTITY, MAXILAWEEK, STARTWEEK, ENDWEEK, ENDWEEKDATE, STARTDATE, ENDDATE, WEEKSINYEAR, STARTMONTH, ENDMONTH, PRICEDECIMALS, INVOICEDECIMALS, CURRENCYCODE, INVOICELAYOUTCODE, INVOICELINETYPEDESC, DSFREQUENCY, INVOICEFREQUENCY_ID, BILLTOSENDINVOICETO, INVOICEDATE, PONUMBER, LANGUAGE_CODE, CUSTTYPE, PARENTINVOICEHEADER_ID, STARTYEAR, ENDYEAR, BILTOCUSTVATNR, LEGALENTITY_LEGALNAME, LEGALENTITY_ID, PLANT_STREET, PLANT_STREET2, PLANT_ZIPCODE, PLANT_CITY, PLANT_STATE
, PLANT_PHONENO, PLANT_FAXNO, PLANT_WEBSITE, PLANT_EMAIL)
as select h.invoiceheader_id, cc.costcenter_id, h.deltocustomer_link_id, h.billtocustomer_link_id
, coalesce((select ihp.invoicenumber from invoiceheader ihp where ihp.invoiceheader_id = h.parentinvoiceheader_id), h.invoicenumber) invoicenumber
, l.invoiceline_id, cc.code costcenter_code, cc.description costcenter_desc,
       h.billtocustomernumber,
       ( case when ((select c.sendinvoiceto from customer c  where c.customer_id=h.deltocustomer_link_id)=0) then  h.deltocustomername
       else  h.billtocustomername end) billtocustomername,
       h.extraname1, h.extraname2, h.deltocustomernumber,
       ( select c.customernumber|| ' ' ||c.legalname from customer c  where c.customer_id=h.deltocustomer_link_id) deltocustnolegalname,
       ( select c.name from customer c  where c.customer_id=h.deltocustomer_link_id) deltocustomername,
       ( select c.vatnumber from customer c  where c.customer_id=h.deltocustomer_link_id) deltocustvatnr,
       h.county, h.state, h.zipcode, h.street, h.street2, h.city,
(select ihextr.billtocountrydescription from invoiceheaderextrainfo ihextr where ihextr.invoiceheader_id = h.invoiceheader_id) billtocountrydescription,
(select co.description from businessunit bu, plant pl, country co
  where h.invoicebusinessunit_id = bu.businessunit_id and bu.plant_id = pl.plant_id and pl.country_id = co.country_id) PLANTCOUNTRYDESCRIPTION,
       l.description item, l.code,
       coalesce((select crei.quantity from costcenterinvoiceline crei where crei.invoiceline_id = l.invoiceline_id and crei.costcenter_link_id = cc.costcenter_id
               ), 0) qty,--sum(l.billedqty) qty,
       l.price, coalesce((select crei.amount from costcenterinvoiceline crei where crei.invoiceline_id = l.invoiceline_id and crei.costcenter_link_id = cc.costcenter_id
                ), 0) amount, l.discountpercentage,
       (select pg.code from product pr, productgroup pg where lp.product_link_id = pr.product_id and pr.productgroup_id=pg.productgroup_id)   productgr_code,
       (select  sd.code from sizedefinition sd where sd.sizedefinition_id=lp.sizedefinition_link_id) sizecode,
       (select fm.code from finishingmethod fm where lp.finishingmethod_id = fm.finishingmethod_id) finishingmethodcode,
       cri.year,cri.week,
       cri.standardquantity quantity,
        cast(( select to_char(max(ild.year*100+ild.week)) from costreportinfo ild, invoiceline il
          where ild.invoiceline_id=il.invoiceline_id
          and il.invoiceheader_id=h.invoiceheader_id
          and il.invoicelinetype_id = 1)as varchar2(6)) maxilaweek,
       h.startweek, h.endweek, to_number(getweeknumber(h.enddate)) endweekdate,h.startdate,h.enddate,
       (case  when h.startyear <> 0 then getweeksinyear(h.startyear)
          else getweeksinyear(to_number(getyearasvarchar(h.invoicedate))) end) weeksinyear,
       h.startmonth, h.endmonth,
(select c.decimals from currency c where h.currency_id=c.currency_id) pricedecimals,
(select c.invoiceamountdecimals from currency c where h.currency_id=c.currency_id) invoicedecimals,
(select c.code from currency c where h.currency_id=c.currency_id) currencycode,
(select ihextr.formlayoutcode from invoiceheaderextrainfo ihextr where ihextr.invoiceheader_id = h.invoiceheader_id) invoicelayoutcode
, (select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = l.invoicelinetype_id and iltd.language_id = lan.language_id) invoicelinetypedesc
, ( select ds.frequency from deliveryscheme ds where ds.code=lp.deliveryschemecode) dsfrequency
, h.invoicefrequency_id
, (select c.sendinvoiceto from customer c where h.deltocustomer_link_id = c.customer_id) billtosendinvoiceto
, h.invoicedate
, cc.ponumber
, lan.code Language_code
, F_GetCustType_smg(h.invoiceheader_id) custtype
, h.parentinvoiceheader_id
, h.startyear
, h.endyear
, (select deb.vatnumber from customer deb where deb.customer_id=h.billtocustomer_link_id) biltocustvatnr
, (select le.legalname from legalentity le where le.legalentity_id = e.legalentity_id) LegalEntity_LegalName
, (select le.legalentity_id from legalentity le where le.legalentity_id = e.legalentity_id) LegalEntity_ID
, pad.street plant_street, pad.street2 plant_street2, pad.zipcode plant_zipcode, pad.city plant_city
, pad.state plant_state, p.phoneno plant_phoneno, p.faxno plant_faxno, p.website plant_website, p.email plant_email
from invoiceheader h, invoicelineproduct lp, invoiceline l, costreportextrainfo cri, costcenter cc, languages lan, businessunit e, plant p, address pad
where  h.invoiceheader_id = l.invoiceheader_id
       and lp.invoiceline_id = l.invoiceline_id
       and l.invoiceline_id = cri.invoiceline_id
       and cc.costcenter_id = cri.costcenter_link_id
and l.invoicelinetype_id = 1 and l.invoicelinesubtype = 6  --all rent only underuse
and h.invoicebusinessunit_id = e.businessunit_id
and e.plant_id = p.plant_id
and pad.address_id = p.address_id
union all
select h.invoiceheader_id, cc.costcenter_id, h.deltocustomer_link_id, h.billtocustomer_link_id
, coalesce((select ihp.invoicenumber from invoiceheader ihp where ihp.invoiceheader_id = h.parentinvoiceheader_id), h.invoicenumber) invoicenumber
, l.invoiceline_id, cc.code costcenter_code, cc.description costcenter_desc,
       h.billtocustomernumber,
       ( case when ((select c.sendinvoiceto from customer c  where c.customer_id=h.deltocustomer_link_id)=0) then  h.deltocustomername
       else  h.billtocustomername end) billtocustomername,
        h.extraname1, h.extraname2, h.deltocustomernumber,
       ( select c.customernumber|| ' ' ||c.legalname from customer c  where c.customer_id=h.deltocustomer_link_id) deltocustnolegalname,
       ( select c.name from customer c  where c.customer_id=h.deltocustomer_link_id) deltocustomername,
       ( select c.vatnumber from customer c  where c.customer_id=h.deltocustomer_link_id) deltocustvatnr,
       h.county, h.state, h.zipcode, h.street, h.street2, h.city,
(select ihextr.billtocountrydescription from invoiceheaderextrainfo ihextr where ihextr.invoiceheader_id = h.invoiceheader_id) billtocountrydescription,
(select co.description from businessunit bu, plant pl, country co
  where h.invoicebusinessunit_id = bu.businessunit_id and bu.plant_id = pl.plant_id and pl.country_id = co.country_id) PLANTCOUNTRYDESCRIPTION,
       l.description item,l.code,coalesce((select crei.quantity from costcenterinvoiceline crei where crei.invoiceline_id = l.invoiceline_id and crei.costcenter_link_id = cc.costcenter_id
               ), 0) qty,--sum(l.billedqty) qty,
       l.price, coalesce((select crei.amount from costcenterinvoiceline crei where crei.invoiceline_id = l.invoiceline_id and crei.costcenter_link_id = cc.costcenter_id
                ), 0) amount, l.discountpercentage,
       (select pg.code from product pr, productgroup pg where lp.product_link_id = pr.product_id and pr.productgroup_id=pg.productgroup_id)   productgr_code,
       ( select  sd.code from sizedefinition sd where sd.sizedefinition_id=lp.sizedefinition_link_id) sizecode,
       (select fm.code from finishingmethod fm where lp.finishingmethod_id = fm.finishingmethod_id) finishingmethodcode,
       cri.year,cri.week,
      cri.quantity,
        cast(( select to_char(max(ild.year*100+ild.week)) from costreportinfo ild, invoiceline il
          where ild.invoiceline_id=il.invoiceline_id
          and il.invoiceheader_id=h.invoiceheader_id
          and il.invoicelinetype_id = 1)as varchar2(6)) maxilaweek,
      h.startweek, h.endweek, to_number(getweeknumber(h.enddate)) endweekdate,h.startdate,h.enddate,
      (case  when h.startyear <> 0 then getweeksinyear(h.startyear)
          else getweeksinyear(to_number(getyearasvarchar(h.invoicedate))) end) weeksinyear,
      h.startmonth, h.endmonth,
      (select c.decimals from currency c where h.currency_id=c.currency_id) pricedecimals,
      (select c.invoiceamountdecimals from currency c where h.currency_id=c.currency_id) invoicedecimals,
      (select c.code from currency c where h.currency_id=c.currency_id) currencycode,
(select ihextr.formlayoutcode from invoiceheaderextrainfo ihextr where ihextr.invoiceheader_id = h.invoiceheader_id) invoicelayoutcode
, (select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = l.invoicelinetype_id and iltd.language_id = lan.language_id) invoicelinetypedesc
, ( select ds.frequency from deliveryscheme ds where ds.code=lp.deliveryschemecode) dsfrequency
, h.invoicefrequency_id
, (select c.sendinvoiceto from customer c where h.deltocustomer_link_id = c.customer_id) billtosendinvoiceto
, h.invoicedate
, cc.ponumber
, lan.code Language_code
, F_GetCustType_smg(h.invoiceheader_id) custtype
, h.parentinvoiceheader_id
, h.startyear
, h.endyear
, (select deb.vatnumber from customer deb where deb.customer_id=h.billtocustomer_link_id) biltocustvatnr
, (select le.legalname from legalentity le where le.legalentity_id = e.legalentity_id) LegalEntity_LegalName
, (select le.legalentity_id from legalentity le where le.legalentity_id = e.legalentity_id) LegalEntity_ID
, pad.street plant_street, pad.street2 plant_street2, pad.zipcode plant_zipcode, pad.city plant_city
, pad.state plant_state, p.phoneno plant_phoneno, p.faxno plant_faxno, p.website plant_website, p.email plant_email
from invoiceheader h, invoicelineproduct lp, invoiceline l, costreportinfo cri, costcenter cc, languages lan, businessunit e, plant p, address pad
where  h.invoiceheader_id = l.invoiceheader_id
       and lp.invoiceline_id = l.invoiceline_id
       and l.invoiceline_id=cri.invoiceline_id
       and cc.costcenter_id = cri.costcenter_link_id
and l.invoicelinetype_id = 1 and l.invoicelinesubtype <> 6  --all rent EXCEPT underuse
and h.invoicebusinessunit_id = e.businessunit_id
and e.plant_id = p.plant_id
and pad.address_id = p.address_id
union all
select h.invoiceheader_id, cc.costcenter_id, h.deltocustomer_link_id, h.billtocustomer_link_id
, coalesce((select ihp.invoicenumber from invoiceheader ihp where ihp.invoiceheader_id = h.parentinvoiceheader_id), h.invoicenumber) invoicenumber
, l.invoiceline_id, cc.code costcenter_code, cc.description costcenter_desc,
       h.billtocustomernumber,
        ( case when ((select c.sendinvoiceto from customer c  where c.customer_id=h.deltocustomer_link_id)=0) then  h.deltocustomername
       else  h.billtocustomername end) billtocustomername, h.extraname1, h.extraname2, h.deltocustomernumber,
       ( select c.customernumber|| ' ' ||c.legalname from customer c  where c.customer_id=h.deltocustomer_link_id) deltocustnolegalname,
       ( select c.name from customer c  where c.customer_id=h.deltocustomer_link_id) deltocustomername,
       ( select c.vatnumber from customer c  where c.customer_id=h.deltocustomer_link_id) deltocustvatnr,
       h.county, h.state, h.zipcode, h.street, h.street2, h.city,
(select ihextr.billtocountrydescription from invoiceheaderextrainfo ihextr where ihextr.invoiceheader_id = h.invoiceheader_id) billtocountrydescription,
(select co.description from businessunit bu, plant pl, country co
  where h.invoicebusinessunit_id = bu.businessunit_id and bu.plant_id = pl.plant_id and pl.country_id = co.country_id) PLANTCOUNTRYDESCRIPTION,
       l.description item,l.code, coalesce((select crei.quantity from costcenterinvoiceline crei where crei.invoiceline_id = l.invoiceline_id and crei.costcenter_link_id = cc.costcenter_id
               ), 0) qty,--sum(l.billedqty) qty,
       l.price, coalesce((select crei.amount from costcenterinvoiceline crei where crei.invoiceline_id = l.invoiceline_id and crei.costcenter_link_id = cc.costcenter_id
                ), 0) amount, l.discountpercentage,
       (select pg.code from product pr, productgroup pg where lp.product_link_id = pr.product_id and pr.productgroup_id=pg.productgroup_id)   productgr_code,
       ( select  sd.code from sizedefinition sd where sd.sizedefinition_id=lp.sizedefinition_link_id) sizecode,
       (select fm.code from finishingmethod fm where lp.finishingmethod_id = fm.finishingmethod_id) finishingmethodcode,
       cri.year,cri.week,
      null quantity,
        cast(( select to_char(max(ild.year*100+ild.week)) from costreportinfo ild, invoiceline il
          where ild.invoiceline_id=il.invoiceline_id
          and il.invoiceheader_id=h.invoiceheader_id
          and il.invoicelinetype_id = 1)as varchar2(6)) maxilaweek,
      h.startweek, h.endweek, to_number(getweeknumber(h.enddate)) endweekdate,h.startdate,h.enddate,
      (case  when h.startyear <> 0 then getweeksinyear(h.startyear)
          else getweeksinyear(to_number(getyearasvarchar(h.invoicedate))) end) weeksinyear,
      h.startmonth, h.endmonth,
      (select c.decimals from currency c where h.currency_id=c.currency_id) pricedecimals,
      (select c.invoiceamountdecimals from currency c where h.currency_id=c.currency_id) invoicedecimals,
      (select c.code from currency c where h.currency_id=c.currency_id) currencycode,
(select ihextr.formlayoutcode from invoiceheaderextrainfo ihextr where ihextr.invoiceheader_id = h.invoiceheader_id) invoicelayoutcode
, (select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = l.invoicelinetype_id and iltd.language_id = lan.language_id) invoicelinetypedesc
, null dsfrequency, h.invoicefrequency_id
, (select c.sendinvoiceto from customer c where h.deltocustomer_link_id = c.customer_id) billtosendinvoiceto
, h.invoicedate
, cc.ponumber
, lan.code Language_code
, F_GetCustType_smg(h.invoiceheader_id) custtype
, h.parentinvoiceheader_id
, h.startyear
, h.endyear
, (select deb.vatnumber from customer deb where deb.customer_id=h.billtocustomer_link_id) biltocustvatnr
, (select le.legalname from legalentity le where le.legalentity_id = e.legalentity_id) LegalEntity_LegalName
, (select le.legalentity_id from legalentity le where le.legalentity_id = e.legalentity_id) LegalEntity_ID
, pad.street plant_street, pad.street2 plant_street2, pad.zipcode plant_zipcode, pad.city plant_city
, pad.state plant_state, p.phoneno plant_phoneno, p.faxno plant_faxno, p.website plant_website, p.email plant_email
from invoiceheader h, invoiceline l left outer join invoicelineproduct lp on lp.invoiceline_id = l.invoiceline_id
, costreportinfo cri, costcenter cc, languages lan, businessunit e, plant p, address pad
where  h.invoiceheader_id = l.invoiceheader_id
       and l.invoiceline_id=cri.invoiceline_id
       and cc.costcenter_id = cri.costcenter_link_id
       and l.invoicelinetype_id not in (1,18)
      and h.invoicebusinessunit_id = e.businessunit_id
      and e.plant_id = p.plant_id
      and pad.address_id = p.address_id

/
create or replace view V_COSTREPORT_INVLINE_BDM
 (CODE, COSTCENTER_LINK_ID, PRODUCT_LINK_ID, DELTOCUSTOMER_LINK_ID, INVOICEAMOUNTDECIMALS, DECIMALS, BILLEDQTY, AMOUNT, SIZECODE, PRICE, INVOICEHEADER_ID, INVOICELINETYPE_ID, INVOICELINESUBTYPE, DESCRIPTION, TYPEOFMERCHM, CC_YEAR, INVOICELINE_ID, INVOICEDATE, INVOICEWEEK, PRODUCTGROUPCODE, CC_WEEK, FIRSTDAYOFWEEK, CC_QUANTITY, TOTALAMOUNT, INCR, DECR, CIRCINV, SUPRESSPRINTING, FINISHINGMETHODCODE)
as SELECT il.code,csc.costcenter_id costcenter_link_id, ilp.product_link_id, ih.deltocustomer_link_id, b.invoiceamountdecimals, b.decimals, il.billedqty, il.amount, ilp.sizecode, il.price, il.invoiceheader_id, il.invoicelinetype_id, il.invoicelinesubtype,
il.description, (select p.typeofmerchandise from product p where p.code=il.code) typeofmerchm,
cc.year CC_YEAR, CC.INVOICELINE_ID, trunc(ih.invoicedate) invoicedate, ih.invoiceweek, ilp.productgroupcode
, cc.week CC_WEEK,  trunc(getfirstdayofweek(getdateforweekyear(1, cc.week, cc.year))) firstdayofweek
, cc.quantity CC_QUANTITY, (select sum(nvl(b.amount,a.amount)) from invoiceline a left outer join costcenterinvoiceline b on a.invoiceline_id=b.invoiceline_id where a.invoiceheader_id=il.invoiceheader_id and a.invoicelinetype_id=2 and b.costcenter_link_id=ccil.costcenter_link_id) totalamount,
 nvl((select sum(q.quantity)
              from   rentalqtyadjustment q, productlistperdistribpoint plpd, distributionpoint dp,
                     department t
              where  q.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
              and    plpd.distributionpoint_id = dp.distributionpoint_id
              and    dp.department_id = t.department_id
              and    t.customer_id =ih.deltocustomer_link_id
              and    ilp.product_link_id = plpd.product_id
              and   (ilp.sizedefinition_link_id = plpd.sizedefinition_id)
              and    ilp.finishingmethod_id = plpd.finishingmethod_id
              --and    q.adjustmentdate >= ih.startdate and    q.adjustmentdate <= ih.enddate
              and getisoweek(q.adjustmentdate)=cc.week
                and year(q.adjustmentdate)=cc.year
              and dp.costcenter_id=csc.costcenter_id
              and    q.quantity > 0), 0) incr,
                nvl((select sum(q.quantity)
              from   rentalqtyadjustment q, productlistperdistribpoint plpd, distributionpoint dp,
                     department t
              where  q.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
              and    plpd.distributionpoint_id = dp.distributionpoint_id
              and    dp.department_id = t.department_id
              and    t.customer_id = ih.deltocustomer_link_id
              and    ilp.product_link_id = plpd.product_id
              and    ilp.sizedefinition_link_id = plpd.sizedefinition_id
              and    ilp.finishingmethod_id = plpd.finishingmethod_id
              --and    q.adjustmentdate >= ih.startdate and    q.adjustmentdate <= ih.enddate
              and getisoweek(q.adjustmentdate) = cc.week
              and year(q.adjustmentdate)=cc.year
              and dp.costcenter_id = csc.costcenter_id
              and    q.quantity < 0), 0) decr,
              coalesce((select sum(q.quantity)
              from   rentalqtyadjustment q, productlistperdistribpoint plpd, distributionpoint dp, department t
              where  q.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
              and    plpd.distributionpoint_id = dp.distributionpoint_id
              and    dp.department_id = t.department_id
              and    t.customer_id = ih.deltocustomer_link_id
              and    ilp.product_link_id = plpd.product_id
              and    ilp.sizedefinition_link_id = plpd.sizedefinition_id
              and    ilp.finishingmethod_id = plpd.finishingmethod_id--and getyearofweek(q.adjustmentdate)*100+getisoweek(q.adjustmentdate) < cc.year*100+cc.week
              and    dp.costcenter_id = csc.costcenter_id
              and    q.adjustmentdate < ih.invoicedate
            ), 0) circinv,
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 e.supressprinting
end supressprinting, ilp.finishingmethodcode
from costreportinfo cc join invoiceline il on cc.invoiceline_id=il.invoiceline_id
join invoiceheader ih on il.invoiceheader_id=ih.invoiceheader_id
inner join invoicelinetype e on e.invoicelinetype_id=il.invoicelinetype_id
left outer join invoicelineproduct ilp on il.invoiceline_id=ilp.invoiceline_id
inner join currency b on ih.currency_id=b.currency_id
left outer join costcenterinvoiceline ccil inner join costcenter csc on ccil.costcenter_link_id=csc.costcenter_id  on (ccil.invoiceline_id=il.invoiceline_id and csc.costcenter_id=cc.costcenter_link_id)
where il.invoicelinetype_id=2

/
create or replace view V_COSTREPORT_INVLINE_DFD
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, GENERATED, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, TAXGROUPCODE, TAXTYPE, SUBJECTTOMINIMUM, TURNOVERGROUPCODE, TURNOVERGROUPDESCRIPTION, INVOICELINESUBTYPE, INVOICELINESUBTYPEDESC, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PRODUCTSHORTDESCRIPTION, SHORTDESCRIPTION, SIZECODE, SIZEDESCRIPTION
, FINISHINGMETHODCODE, FINISHINGMETHODDESCRIPTION, 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, DELIVERYSCHEMECODE, CHANGESWEEKFREQUENCY, YEAR, WEEK, QUANTITYPERWEEK, AMOUNTPERWEEK)
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 rpad(trim(DESCRIPTION), 63) 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.adjustmentpermited, 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,
(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, 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,
case (SELECT pilt.suppressprinting
         from plantinvoicelinetype pilt, businessunit bu
         where f.invoicebusinessunit_id = bu.businessunit_id
               and bu.plant_id = pilt.plant_id
               and pilt.invoicelinetype_id = a.invoicelinetype_id)
  when 0 then 0
  when 1 then 1
  when 2 then 2
  else e.supressprinting
end supressprinting, --502161
b.adjustmentdeliveredqty, b.pricefactor, b.deliveryschemecode
, (case
  when a.invoicelinetype_id = 1 and a.invoicelinesubtype in (0, 7, 8)--e.type = 1 and a.invoicelinesubtype = 0
  then FGET_BDE_FRECV(f.deltocustomer_link_id, b.product_link_id, b.sizedefinition_link_id, b.finishingmethod_id, f.invoicedate, b.deliveryschemecode)
  else -1
  end ) changesweekFrequency,
cri.year,
cri.week,
cri.quantity quantityperweek,
cri.amount amountperweek
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)
left outer join costreportinfo cri on a.invoiceline_id = cri.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) -- 501528

/
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_COSTSSPECSPERWEARER_INVL_BDM
 (INVOICEHEADER_ID, INVLINEPRICE, PRODUCT_LINK_ID, FINISHINGMETHOD_ID, INVOICEQTYCOLUMN, INVOICELINETYPE_DESC)
as select l.invoiceheader_id,
       max(l.price) invLinePRICE,
       ilp.product_link_id, ilp.finishingmethod_id, ilp.invoiceqtycolumn,
       (select iltd.description from invoicelinetype_desc iltd, invoiceheader ih, customer bil where iltd.invoicelinetype_id = ilt.invoicelinetype_id and
       iltd.language_id = bil.language_id and l.invoiceheader_id = ih.invoiceheader_id and bil.customer_id = ih.billtocustomer_link_id) invoicelinetype_desc
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
, ilt.invoicelinetype_id

/
create or replace view V_COSTSSPECSPERWEARER_INVL_CBD
 (INVOICEHEADER_ID, INVLINEPRICE, PRODUCT_LINK_ID, FINISHINGMETHOD_ID, LANGUAGE_CODE, INVLINETYPE_DESC)
as select l.invoiceheader_id,
       max(l.price * (100 - l.discountpercentage)/100) invLinePRICE,
       ilp.product_link_id, ilp.finishingmethod_id, lan.code language_code,
       (select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = ilt.invoicelinetype_id and iltd.language_id = lan.language_id) invlinetype_desc
from invoiceline l, invoicelinetype ilt, invoicelineproduct ilp, languages lan
where l.invoicelinetype_id = ilt.invoicelinetype_id
      and ilt.type in (1, 2) --ONLY RENT and WASH LINES
      and l.invoiceline_id = ilp.invoiceline_id --MUST EXISTS
      and ilp.billingmethod in (1, 3) --ONLY billing Method 1 and 3 for CBD
group by l.invoiceheader_id, ilp.product_link_id, ilp.finishingmethod_id, ilt.invoicelinetype_id, lan.language_id, lan.code --only one price should show per invHeader, product and finMeth

/
create or replace view V_COSTSSPECSPERWEARER_INV_CBD
 (INVOICEHEADER_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, BUCODE, BUDESCRIPTION, PLANT_ID, PLANTCODE, PLANTNAME, PLANTPHONENO, PLANTFAX, PLANTSTREET, PLANTSTREET2, PLANTCITY, PLANTSTATE, PLANTZIPCODE
, DECIMALSPRICES, DECIMALSAMOUNT, CURRENCYCODE, CURRENCYDESC, COSTCENTER_ID, COSTCENTER_CODE, COSTCENTER_DESC, SALESAREA)
as select distinct h.invoiceheader_id, h.invoicebusinessunit_id, h.endweek, h.endyear,
       h.invoicedate, h.invoicenumber, h.purchaseorder, h.startdate, h.enddate,
       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, cc.code costcenter_code, cc.description costcenter_desc,
       c.salesarea_id Salesarea
from invoiceheader h, businessunit bu, plant p, address pa, currency cy--, invoicefrequency ifr
     , costcenter cc, costcenterinvoiceline ccil, invoiceline il, customer c
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
      and H.Deltocustomernumber = C.Customernumber

/
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, locker.locker, locker.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 statusquoheader sh,
     sqsetincirculation si,
     customer c,
     department d,
     Costcenter cc, distributionpoint dp, product p,
     sizedefinition s,
     finishingmethod f, weareremployment we left outer join locker on locker.locker_id = we.locker_id,
     wearer w,
     LANGUAGES L
where sh.statusquoheader_id = si.statusquoheader_id
      and si.finishingmethod_id = f.finishingmethod_id
      and si.weareremployment_link_id = we.weareremployment_id --this must be NOT NULL
      and we.wearer_id = w.wearer_id
      and sh.statusquotype = 2 --ONLY SETS
      and si.numberemploymentscharge > 0
      and c.customer_id = si.customer_link_id
      and d.costcenter_id = cc.costcenter_id
      and si.department_link_id = d.department_id
      and si.distributionpoint_link_id = dp.distributionpoint_id
      and si.product_link_id = p.product_id
      and si.sizedefinition_link_id = s.sizedefinition_id

/
create or replace view V_COSTS_SPECS_PER_WEARER_BDM
 (BRANCHTYPE, INVLINETYPE_DESC, INVOICEHEADER_ID, CHANGESPERWEEK, INVLINEPRICE, CUSTOMER_ID, CUSTOMERNUMBER, WEARERNUMBER, WEARERNAME, PRODUCT_ID, PRODUCTCODE, PRODUCTDESC, SIZECODE, LANGUAGECODE, COSTCENTER_ID, COSTCENTERCODE, COSTCENTERDESC, INVOICELINETYPE_ID, DEPARTMENT_ID, DEPARTMENTNUMBER, DEPARTMENTDESC)
as select /*+parallel*/ x.branchtype, 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.sizecode,x.languageCode, x.costcenter_id, x.CostcenterCode, x.CostcenterDesc, x.invoicelinetype_id, x.department_id, x.departmentnumber, x.departmentDesc
from
(
       select 1 branchtype, ih.invoiceheader_id, 'Abonnement' invlinetype_desc,
       --(select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = 1 and iltd.language_id = l.language_id) invlinetype_desc,
       sum(si.changesperweek)changesperweek, dep.department_id, dep.departmentnumber, dep.description departmentDesc,
       PACK_PRICE.Rent_Price(c.customer_id, p.product_id, si.sizedefinition_link_id, si.finishingmethod_id, ih.invoicedate)-- max(il.price * (100 - il.discountpercentage)/100)
       invLinePRICE,
       c.customer_id, c.customernumber,
       we.wearernumber,  we.wearername wearerName,
       p.product_id, p.code productCode, s.code sizecode,
       (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, cc.costcenter_id, cc.code CostcenterCode, cc.description CostcenterDesc,
       il.invoicelinetype_id --rent line
      from statusquoheader sh, sqsetincirculation si, customer c, Costcenter cc, distributionpoint dp, department dep, product p,
           sizedefinition s, weareremployment_link we, invoiceheader ih, invoiceline il, invoicelineproduct ilp, LANGUAGES L
      where sh.statusquoheader_id = si.statusquoheader_id
            and si.weareremployment_link_id = we.weareremployment_link_id --this must be NOT NULL
            and sh.statusquotype = 2 --ONLY SETS      and si.numberemploymentscharge > 0 -- commented for CBD
            and c.customer_id = si.customer_link_id
            and si.distributionpoint_link_id = dp.distributionpoint_id
            and dep.costcenter_id = cc.costcenter_id
            and si.product_link_id = p.product_id
            and si.product_link_id = ilp.product_link_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='*'))
            and si.finishingmethod_id = ilp.finishingmethod_id
            and ilp.invoiceline_id = il.invoiceline_id
            and ilp.weareremployment_link_id = we.WEAREREMPLOYMENT_LINK_ID
            and il.invoicelinetype_id = 1--RENT
            and il.invoiceheader_id = ih.invoiceheader_id
            and ilp.billingmethod = 1
            and ih.startdate <= sh.statusquodate
            and ih.enddate >= sh.statusquodate
            and ih.deltocustomer_link_id = c.customer_id
            and dp.department_id = dep.department_id
            and si.sizedefinition_link_id = s.sizedefinition_id
            and coalesce(ih.splitupcode, cc.code) = cc.code
            group by ih.invoiceheader_id, si.sizedefinition_link_id, si.finishingmethod_id, ih.invoicedate,il.invoicelinetype_id, c.customer_id,c.customernumber,we.wearernumber,we.wearername,p.product_id,cc.costcenter_id, cc.code,cc.description, p.code, s.code,l.language_id,l.code, dep.department_id, dep.departmentnumber, dep.description
      union all
       select 2 branchtype, ih.invoiceheader_id, 'Abonnement' invlinetype_desc,
       --(select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = 1 and iltd.language_id = l.language_id) invlinetype_desc,
       sum(si.changesperweek)changesperweek, dep.department_id, dep.departmentnumber, dep.description departmentDesc,
       PACK_PRICE.Rent_Price(c.customer_id, p.product_id, si.sizedefinition_link_id, si.finishingmethod_id, ih.invoicedate)-- max(il.price * (100 - il.discountpercentage)/100)
       invLinePRICE,
       c.customer_id, c.customernumber,
       we.wearernumber,  we.wearername wearerName,
       p.product_id, p.code productCode, s.code sizecode,
       (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, cc.costcenter_id, cc.code CostcenterCode, cc.description CostcenterDesc,
       il.invoicelinetype_id --rent line
      from statusquoheader sh, sqsetincirculation si, customer c, Costcenter cc, distributionpoint dp, department dep, product p,
           sizedefinition s, weareremployment_link we, invoiceheader ih, invoiceline il, invoicelineproduct ilp, LANGUAGES L
      where sh.statusquoheader_id = si.statusquoheader_id
            and si.weareremployment_link_id = we.weareremployment_link_id --this must be NOT NULL
            and sh.statusquotype = 2 --ONLY SETS      and si.numberemploymentscharge > 0 -- commented for CBD
            and c.customer_id = si.customer_link_id
            and si.distributionpoint_link_id = dp.distributionpoint_id
            and dep.costcenter_id = cc.costcenter_id
            and si.product_link_id = p.product_id
            and si.product_link_id = ilp.product_link_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='*'))
            and si.finishingmethod_id = ilp.finishingmethod_id
            and ilp.invoiceline_id = il.invoiceline_id
            and ilp.WEAREREMPLOYMENT_LINK_ID is null
            and il.invoicelinetype_id = 1--rent
            and il.invoiceheader_id = ih.invoiceheader_id
            and ilp.billingmethod = 1
            and ih.startdate <= sh.statusquodate
            and ih.enddate >= sh.statusquodate
            and ih.deltocustomer_link_id = c.customer_id
            and dp.department_id = dep.department_id
            and si.sizedefinition_link_id = s.sizedefinition_id
            and coalesce(ih.splitupcode, cc.code) = cc.code
            group by ih.invoiceheader_id, si.sizedefinition_link_id, si.finishingmethod_id, ih.invoicedate,il.invoicelinetype_id, c.customer_id,c.customernumber,we.wearernumber,we.wearername,p.product_id,cc.costcenter_id, cc.code,cc.description, p.code, s.code,l.language_id,l.code, dep.department_id, dep.departmentnumber, dep.description
       union all
        select 3 branchtype, ih.invoiceheader_id, 'Forfait' invlinetype_desc,
        --(select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = 1 and iltd.language_id = l.language_id) invlinetype_desc,
        sum(si.QtyRentedPerPiece + si.beyondlifetimecirc) changesperweek, dep.department_id, dep.departmentnumber, dep.description departmentDesc,/*else si.QtyRentedPerPiece end*/
        PACK_PRICE.Rent_Price(c.customer_id, p.product_id, si.sizedefinition_link_id, si.finishingmethod_id, ih.invoicedate)-- max(il.price * (100 - il.discountpercentage)/100)
        invLinePRICE,
        c.customer_id, c.customernumber,
        we.wearernumber, we.wearername wearerName,
        p.product_id, p.code productCode, s.code sizecode,
        (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, cc.costcenter_id, cc.code CostcenterCode, cc.description CostcenterDesc,
        1 invoicelinetype_id
       from statusquoheader sh, sqitemincirculation si, customer c, Costcenter cc, distributionpoint dp, department dep, product p, sizedefinition s,
            weareremployment_link we, invoiceheader ih, invoiceline il, invoicelineproduct ilp, LANGUAGES L
       where sh.statusquoheader_id = si.statusquoheader_id
             and si.weareremployment_link_id = we.weareremployment_link_id --this must be NOT NULL
             and sh.statusquotype = 1 --Items In Circ      and si.numberemploymentscharge > 0 -- commented for CBD
             and c.customer_id = si.customer_link_id
             and si.distributionpoint_link_id = dp.distributionpoint_id
             and dep.costcenter_id=cc.costcenter_id
             and si.product_link_id = p.product_id
             and si.product_link_id = ilp.product_link_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='*'))
             and si.finishingmethod_id = ilp.finishingmethod_id
             and ilp.invoiceline_id = il.invoiceline_id
             and ilp.weareremployment_link_id = we.WEAREREMPLOYMENT_LINK_ID
             and il.invoicelinetype_id = 1--rent
             and il.invoiceheader_id = ih.invoiceheader_id
             and ilp.billingmethod = 3
             and ih.startdate <= sh.statusquodate
             and ih.enddate >= sh.statusquodate
             and ih.deltocustomer_link_id = c.customer_id
             and dp.department_id = dep.department_id
             and si.sizedefinition_link_id = s.sizedefinition_id
             and coalesce(ih.splitupcode, cc.code) = cc.code
             group by ih.invoiceheader_id, si.sizedefinition_link_id, si.finishingmethod_id, ih.invoicedate,il.invoicelinetype_id, c.customer_id,c.customernumber,we.wearernumber,we.wearername,p.product_id,cc.costcenter_id, cc.code,cc.description, p.code, s.code,l.language_id,l.code, dep.department_id, dep.departmentnumber, dep.description
      union all
       select 4 branchtype, ih.invoiceheader_id, 'Forfait' invlinetype_desc,
       --(select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = 1 and iltd.language_id = l.language_id) invlinetype_desc,
       sum(si.QtyRentedPerPiece + si.beyondlifetimecirc) changesperweek, dep.department_id, dep.departmentnumber, dep.description departmentDesc,/*else si.QtyRentedPerPiece end*/
       PACK_PRICE.Rent_Price(c.customer_id, p.product_id, si.sizedefinition_link_id, si.finishingmethod_id, ih.invoicedate)-- max(il.price * (100 - il.discountpercentage)/100)
       invLinePRICE,
       c.customer_id, c.customernumber,
       we.wearernumber, we.wearername wearerName,
       p.product_id, p.code productCode, s.code sizecode,
       (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, cc.costcenter_id, cc.code CostcenterCode, cc.description CostcenterDesc,
       1 invoicelinetype_id
      from statusquoheader sh, sqitemincirculation si, customer c, Costcenter cc, distributionpoint dp, department dep, product p,
           sizedefinition s, weareremployment_link we, invoiceheader ih, invoiceline il, invoicelineproduct ilp, LANGUAGES L
      where sh.statusquoheader_id = si.statusquoheader_id
            and si.weareremployment_link_id = we.weareremployment_link_id --this must be NOT NULL
            and sh.statusquotype = 1 --Items In Circ      and si.numberemploymentscharge > 0 -- commented for CBD
            and c.customer_id = si.customer_link_id
            and si.distributionpoint_link_id = dp.distributionpoint_id
            and dep.costcenter_id=cc.costcenter_id
            and si.product_link_id = p.product_id
            and si.product_link_id = ilp.product_link_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='*'))
            and si.finishingmethod_id = ilp.finishingmethod_id
            and ilp.invoiceline_id = il.invoiceline_id
            and ilp.WEAREREMPLOYMENT_LINK_ID is null
            and il.invoicelinetype_id = 1--rent
            and il.invoiceheader_id = ih.invoiceheader_id
            and ilp.billingmethod = 3
            and ih.startdate <= sh.statusquodate
            and ih.enddate >= sh.statusquodate
            and ih.deltocustomer_link_id = c.customer_id
            and dp.department_id = dep.department_id
            and si.sizedefinition_link_id = s.sizedefinition_id
            and coalesce(ih.splitupcode, cc.code) = cc.code
            group by ih.invoiceheader_id,ih.invoicedate,il.invoicelinetype_id,c.customer_id,c.customernumber,we.wearernumber,we.wearername,p.product_id,cc.costcenter_id, cc.code,cc.description, p.code, si.sizedefinition_link_id, si.finishingmethod_id, s.code,l.language_id, l.code, dep.department_id, dep.departmentnumber, dep.description
       union all
        select 5 branchtype, 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, dep.department_id, dep.departmentnumber, dep.description departmentDesc,--max
        (il.price * (100 - il.discountpercentage)/100) invLinePRICE,
        c.customer_id, c.customernumber,
        we.wearernumber, we.wearername wearerName,
        p.product_id, p.code productCode, s.code sizecode,
        (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, cc.costcenter_id, cc.code CostcenterCode, cc.description CostcenterDesc,
        2 invoicelinetype_id
       from deliveryscan ds, customer c, weareremployment_link we, packingnote pn, distributionpoint dp, department dep, Costcenter cc,
            packingnoteline pnl, product p, sizedefinition s, invoiceline il, invoiceheader ih, invoicelineproduct ilp, LANGUAGES L
       where ds.customer_link_id = c.customer_id
             and ds.chargewashing = 'Y'
             and ds.outscannodelivery in (0,2)
             and ds.weareremployment_link_id = we.weareremployment_link_id
             and pn.packingnote_id = ds.packingnote_id
             and pn.distributionpoint_id = dp.distributionpoint_id
             and cc.costcenter_id = dep.costcenter_id
             and pn.packingnote_id = pnl.packingnote_id
             and ds.product_link_id = pnl.product_id
             and pnl.invoiceheader_id = ih.invoiceheader_id
             and pnl.product_id = p.product_id
             and il.invoiceheader_id = ih.invoiceheader_id
             and ih.deltocustomer_link_id = c.customer_id
             and ilp.invoiceline_id = il.invoiceline_id
             and ilp.weareremployment_link_id = we.WEAREREMPLOYMENT_LINK_ID
             and il.invoicelinetype_id = 2
             and ilp.product_link_id = ds.product_link_id
             and ds.sizedefinition_link_id = pnl.sizedefinition_id
             and (ds.sizedefinition_link_id = ilp.sizedefinition_link_id or ilp.sizedefinition_link_id = (select sd.sizedefinition_id from sizedefinition sd where sd.code='*'))
             and ds.finishingmethod_id=ilp.finishingmethod_id
             and dp.department_id = dep.department_id
             and ds.sizedefinition_link_id = s.sizedefinition_id
             group by ih.invoiceheader_id,il.invoicelinetype_id,c.customer_id,c.customernumber,we.wearernumber,we.wearername,p.product_id,cc.costcenter_id,cc.code,cc.description, p.code, s.code,l.language_id,l.code, dep.department_id, dep.departmentnumber, dep.description
                      , il.price, il.discountpercentage
        union all
         select 6 branchtype, 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, dep.department_id, dep.departmentnumber, dep.description departmentDesc, --max
         (il.price * (100 - il.discountpercentage)/100) invLinePRICE,
         c.customer_id, c.customernumber,
         we.wearernumber, we.wearername wearerName,
         p.product_id, p.code productCode, s.code sizecode,
         (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, cc.costcenter_id, cc.code CostcenterCode, cc.description CostcenterDesc,
         2 invoicelinetype_id
        from deliveryscan ds, customer c, weareremployment_link we, packingnote pn, distributionpoint dp, department dep, Costcenter cc,
             packingnoteline pnl, product p, sizedefinition s, invoiceline il, invoiceheader ih, invoicelineproduct ilp, LANGUAGES L
        where ds.customer_link_id = c.customer_id
              and ds.chargewashing = 'Y'
              and ds.outscannodelivery in (0,2)
              and ds.weareremployment_link_id = we.weareremployment_link_id
              and pn.packingnote_id = ds.packingnote_id
              and pn.distributionpoint_id = dp.distributionpoint_id
              and cc.costcenter_id = dep.costcenter_id
              and pn.packingnote_id = pnl.packingnote_id
              and ds.product_link_id = pnl.product_id
              and pnl.invoiceheader_id = ih.invoiceheader_id
              and pnl.product_id = p.product_id
              and il.invoiceheader_id = ih.invoiceheader_id
              and ih.deltocustomer_link_id = c.customer_id
              and ilp.invoiceline_id = il.invoiceline_id
              and ilp.WEAREREMPLOYMENT_LINK_ID is null
              and il.invoicelinetype_id = 2
              and ilp.product_link_id = ds.product_link_id
              and ds.sizedefinition_link_id = pnl.sizedefinition_id
              and (ds.sizedefinition_link_id = ilp.sizedefinition_link_id or ilp.sizedefinition_link_id = (select sd.sizedefinition_id from sizedefinition sd where sd.code='*'))
              and ds.finishingmethod_id = ilp.finishingmethod_id
              and dp.department_id = dep.department_id
              and ds.sizedefinition_link_id = s.sizedefinition_id
              group by ih.invoiceheader_id,il.invoicelinetype_id,c.customer_id,c.customernumber,we.wearernumber,we.wearername,p.product_id,cc.costcenter_id,cc.code,cc.description, p.code, s.code,l.language_id,l.code, dep.department_id, dep.departmentnumber, dep.description
                       , il.price, il.discountpercentage
        union all
         select 7 branchtype, a.invoiceheader_id,
         (select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = 10 and iltd.language_id = languages.language_id) invlinetype_desc,
         a.quantity changesperweek, e.department_id, e.departmentnumber, e.description departmentDesc, a.amount invLinePRICE,
         cu.customer_id, cu.customernumber, w.wearernumber, w.wearername wearerName, p.product_id, p.code productCode,
         (select sz.code from sizedefinition sz where sz.sizedefinition_id = a.sizedefinition_link_id) sizecode,
         (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,
         languages.code languageCode, cc.costcenter_id, cc.code CostcenterCode, cc.description CostcenterDesc,
         10 invoicelinetype_id
        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, Costcenter cc, distributionpoint_link d, department e, customer cu, product_link p, languages
        where a.reasoncode_id = b.reasoncode_id
              and a.distributionpoint_link_id = d.distributionpoint_link_id and e.costcenter_id=cc.costcenter_id
              and d.department_link_id = e.department_id and e.customer_id = cu.customer_id
              and a.product_link_id = p.product_link_id AND a.chargetype = 1--Res Value
              AND a.status = 0 and a.amount <> 0
        union all
         select 8 branchtype, a.invoiceheader_id,
         (select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = 23 and iltd.language_id = languages.language_id) invlinetype_desc,
         a.quantity changesperweek, e.department_id, e.departmentnumber, e.description departmentDesc, a.amount invLinePRICE,
         cu.customer_id, cu.customernumber, w.wearernumber, w.wearername wearerName, p.product_id, p.code productCode,
         (select sz.code from sizedefinition sz where sz.sizedefinition_id = a.sizedefinition_link_id) sizecode,
         (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,
         languages.code languageCode, cc.costcenter_id, cc.code CostcenterCode, cc.description CostcenterDesc,
         10 invoicelinetype_id
        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, Costcenter cc, distributionpoint_link d, department e, customer cu, product_link p, languages
        where a.reasoncode_id = b.reasoncode_id
              and a.distributionpoint_link_id = d.distributionpoint_link_id and e.costcenter_id=cc.costcenter_id
              and d.department_link_id = e.department_id and e.customer_id = cu.customer_id
              and a.product_link_id = p.product_link_id AND a.chargetype = 2--Restock Fee
              AND a.status = 0and a.amount <> 0
        union all
         select 9 branchtype, a.invoiceheader_id,
         (select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = 12 and iltd.language_id = languages.language_id) invlinetype_desc,
         a.quantity changesperweek, e.department_id, e.departmentnumber, e.description departmentDesc, coalesce(a.prepcharge, 0) invLinePRICE,
         cu.customer_id, cu.customernumber, w.wearernumber, w.wearername wearerName, p.product_id, p.code productCode, s.code sizecode,
         (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,
         languages.code languageCode, cc.costcenter_id, cc.code CostcenterCode, cc.description CostcenterDesc,
         12 invoicelinetype_id
        from issuehistory a
             left outer join weareremployment_link w on (a.weareremployment_link_id = w.weareremployment_link_id),
             Costcenter cc, distributionpoint_link d, department e, customer cu, product_link p, languages, sizedefinition_link s
        where a.distributionpoint_link_id = d.distributionpoint_link_id and e.costcenter_id = cc.costcenter_id
              and d.department_link_id = e.department_id and e.customer_id = cu.customer_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)--Prep charge
        union all
         select 10 branchtype, pr.invoiceheader_id, 'Étiquettes' invlinetype_desc,
         pr.quantity changesperweek, dep.department_id, dep.departmentnumber, dep.description departmentDesc, pr.amount invLinePRICE,
         cu.customer_id, cu.customernumber, wel.wearernumber, wel.wearername wearerName, prdl.product_id, prdl.code productCode,
         (select sz.code from sizedefinition sz where sz.sizedefinition_id = pr.sizedefinition_link_id) sizecode,
         (select z.description from product_link_desc z where z.product_link_id = pr.product_link_id and z.language_id = lan.language_id) productdesc,
         lan.code languageCode, cc.costcenter_id, cc.code CostcenterCode, cc.description CostcenterDesc,
         99 invoicelinetype_id
        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 dep, customer cu, Costcenter cc, labellayout ll, languages lan
        where 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_id
              and dep.costcenter_id = cc.costcenter_id and dep.customer_id = cu.customer_id
              and pr.status = 0 and pr.amount <> 0--Labels
        union all
         select 11 branchtype, a.invoiceheader_id,
         (select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = 6 and iltd.language_id = languages.language_id) invlinetype_desc,
         a.minutes changesperweek, e.department_id, e.departmentnumber, e.description departmentDesc, a.amount invLinePRICE,
         cu.customer_id, cu.customernumber, w.wearernumber, w.wearername wearerName, plk.product_id, plk.code productCode,
         null sizecode,
         (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,
         languages.code languageCode, cc.costcenter_id, cc.code CostcenterCode, cc.description CostcenterDesc,
         6 invoicelinetype_id
        from repairhistory a
             left outer join product_link plk on (a.product_link_id = plk.product_link_id)
             left outer join weareremployment_link w on (a.weareremployment_link_id = w.weareremployment_link_id)
             left outer join distributionpoint_link d on (a.distributionpoint_link_id = d.distributionpoint_link_id),
             department e, customer cu, Costcenter cc, languages--, repairtype p
        where d.department_link_id = e.department_id
              and e.costcenter_id = cc.costcenter_id and e.customer_id = cu.customer_id--and a.repairtype_id = p.repairtype_id
              and a.status = 0 and a.amount <> 0--Repairs
        union all
         select 12 branchtype, a.invoiceheader_id,
         (select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = 19 and iltd.language_id = languages.language_id) invlinetype_desc,
         a.quantity changesperweek, e.department_id, e.departmentnumber, e.description departmentDesc, a.amount invLinePRICE,
         f.customer_id, f.customernumber, w.wearernumber, w.wearername wearerName, p.product_id, p.code productCode,
         (select sd.code from emblemtemplateline emb, sizedefinition sd where a.emblemtemplateline_id = emb.emblemtemplateline_id and emb.sizedefinition_id = sd.sizedefinition_id) sizecode,
         (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,
         languages.code languageCode, cc.costcenter_id, cc.code CostcenterCode, cc.description CostcenterDesc,
         19 invoicelinetype_id
        from emblemhistory a, weareremployment_link w, product p, distributionpoint_link d, department e, Costcenter cc, 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_id and e.costcenter_id = cc.costcenter_id
              and e.customer_id = f.customer_link_id and p.product_id = coalesce(a.emblemproduct_id, a.product_link_id)
              and a.weareremployment_link_id = w.weareremployment_link_id and a.amount <> 0 --Emblem invoice
        union all
         select 13 branchtype, (select i.parentinvoiceheader_id from invoiceheader i where i.invoiceheader_id = a.invoiceheader_id) invoiceheader_id,
         (select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = 19 and iltd.language_id = languages.language_id) invlinetype_desc,
         a.quantity changesperweek, e.department_id, e.departmentnumber, e.description departmentDesc, a.amount invLinePRICE,
         f.customer_id, f.customernumber, w.wearernumber, w.wearername wearerName, p.product_id, p.code productCode,
         (select sd.code from emblemtemplateline emb, sizedefinition sd where a.emblemtemplateline_id = emb.emblemtemplateline_id and emb.sizedefinition_id = sd.sizedefinition_id) sizecode,
         (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,
         languages.code languageCode, cc.costcenter_id, cc.code CostcenterCode, cc.description CostcenterDesc,
         19 invoicelinetype_id
        from emblemhistory a, weareremployment_link w, product p, distributionpoint_link d, department e, Costcenter cc, 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_id and e.costcenter_id = cc.costcenter_id
              and e.customer_id = f.customer_link_id and p.product_id = coalesce(a.emblemproduct_id, a.product_link_id)
              and a.weareremployment_link_id = w.weareremployment_link_id and a.amount <> 0--Emblem PARENT invoice
        union all
         select 14 branchtype, a.invoiceheader_id,
         (select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = 5 and iltd.language_id = languages.language_id) invlinetype_desc,
         a.quantity changesperweek, e.department_id, e.departmentnumber, e.description departmentDesc, a.amount invLinePRICE,
         f.customer_id, f.customernumber, w.wearernumber, w.wearername wearerName, p.product_id, p.code productCode,
         r.code  sizecode,
         (select z.description from product_link_desc z where z.product_link_id = p.product_link_id and z.language_id = languages.language_id) productdesc,
         languages.code languageCode, cc.costcenter_id, cc.code CostcenterCode, cc.description CostcenterDesc,
         5 invoicelinetype_id
        from garmentsaleshistory a
             left outer join weareremployment_link w on (a.weareremployment_link_id = w.weareremployment_link_id),
             distributionpoint_link d, department e, Costcenter cc, customer_link f, product_link p,  sizedefinition_link r, languages
        where a.distributionpoint_link_id = d.distributionpoint_link_id and d.department_link_id = e.department_id
              and e.costcenter_id = cc.costcenter_id and e.customer_id = f.customer_link_id
              and a.product_link_id = p.product_link_id and a.sizedefinition_link_id = r.sizedefinition_link_id
              and a.status = 0 and a.amount <> 0--SALES
) x

/
create or replace view V_COSTS_SPECS_PER_WEARER_CBD
 (INVLINETYPE_DESC, INVOICEHEADER_ID, CHANGESPERWEEK, INVLINEPRICE, CUSTOMER_ID, CUSTOMERNUMBER, WEARERNUMBER, WEARERNAME, PRODUCT_ID, PRODUCTCODE, PRODUCTDESC, LANGUAGECODE, COSTCENTERCODE, COSTCENTERDESC, INVOICELINETYPE_ID)
as select /*+parallel*/ 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.CostcenterCode, x.CostcenterDesc, x.invoicelinetype_id
from
(select 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.changesperweek)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,cc.code CostcenterCode, cc.description CostcenterDesc,
       il.invoicelinetype_id --rent line
          from statusquoheader sh,
               sqsetincirculation si,
               customer c,
               Costcenter cc, distributionpoint dp, product p,
               weareremployment_link we,
               invoiceheader ih, invoiceline il, invoicelineproduct ilp,
               LANGUAGES L
          where sh.statusquoheader_id = si.statusquoheader_id
                and si.weareremployment_link_id = we.weareremployment_link_id --this must be NOT NULL
                and sh.statusquotype = 2 --ONLY SETS      and si.numberemploymentscharge > 0 -- commented for CBD
                and c.customer_id = si.customer_link_id
                and si.distributionpoint_link_id = dp.distributionpoint_id
                and dp.costcenter_id=cc.costcenter_id
                and si.product_link_id = p.product_id
                and si.product_link_id=ilp.product_link_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='*'))
                and si.finishingmethod_id=ilp.finishingmethod_id
                and ilp.invoiceline_id=il.invoiceline_id
                and ilp.weareremployment_link_id = we.WEAREREMPLOYMENT_LINK_ID
                and il.invoicelinetype_id=1--rent
                and il.invoiceheader_id=ih.invoiceheader_id
                and ilp.billingmethod in (1, 3)
                and ih.startdate<=sh.statusquodate
                and ih.enddate>=sh.statusquodate
                and ih.deltocustomer_link_id=c.customer_id
                and coalesce(ih.splitupcode, cc.code) = cc.code
            group by ih.invoiceheader_id,il.invoicelinetype_id, c.customer_id,c.customernumber,we.wearernumber,we.wearername,p.product_id,cc.code,cc.description, p.code,l.language_id,l.code
union all
select 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.changesperweek)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,cc.code CostcenterCode, cc.description CostcenterDesc,
       il.invoicelinetype_id --rent line
          from statusquoheader sh,
               sqsetincirculation si,
               customer c,
               Costcenter cc, distributionpoint dp, product p,
               weareremployment_link we,
               invoiceheader ih, invoiceline il, invoicelineproduct ilp,
               LANGUAGES L
          where sh.statusquoheader_id = si.statusquoheader_id
                and si.weareremployment_link_id = we.weareremployment_link_id --this must be NOT NULL
                and sh.statusquotype = 2 --ONLY SETS      and si.numberemploymentscharge > 0 -- commented for CBD
                and c.customer_id = si.customer_link_id
                and si.distributionpoint_link_id = dp.distributionpoint_id
                and dp.costcenter_id=cc.costcenter_id
                and si.product_link_id = p.product_id
                and si.product_link_id=ilp.product_link_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='*'))
                and si.finishingmethod_id=ilp.finishingmethod_id
                and ilp.invoiceline_id=il.invoiceline_id
                and  ilp.WEAREREMPLOYMENT_LINK_ID is null
                and il.invoicelinetype_id=1--rent
                and il.invoiceheader_id=ih.invoiceheader_id
                and ilp.billingmethod in (1, 3)
                and ih.startdate<=sh.statusquodate
                  and ih.enddate>=sh.statusquodate
                and ih.deltocustomer_link_id=c.customer_id
                and coalesce(ih.splitupcode, cc.code) = cc.code
            group by ih.invoiceheader_id,il.invoicelinetype_id, c.customer_id,c.customernumber,we.wearernumber,we.wearername,p.product_id,cc.code,cc.description, p.code,l.language_id,l.code
union all
select 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.QtyRentedPerPiece + si.beyondlifetimecirc) changesperweek,/*else si.QtyRentedPerPiece end*/
        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,cc.code CostcenterCode, cc.description CostcenterDesc,
       1 invoicelinetype_id
            from statusquoheader sh,
                 sqitemincirculation si,
                 customer c,
                 Costcenter cc, distributionpoint dp, product p,
                 weareremployment_link we,
                 invoiceheader ih, invoiceline il, invoicelineproduct ilp,
                 LANGUAGES L
            where sh.statusquoheader_id = si.statusquoheader_id
                  and si.weareremployment_link_id = we.weareremployment_link_id --this must be NOT NULL
                  and sh.statusquotype = 1 --Items In Circ      and si.numberemploymentscharge > 0 -- commented for CBD
                  and c.customer_id = si.customer_link_id
                  and si.distributionpoint_link_id = dp.distributionpoint_id
                  and dp.costcenter_id=cc.costcenter_id
                  and si.product_link_id = p.product_id
                  and si.product_link_id=ilp.product_link_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='*'))
                  and si.finishingmethod_id=ilp.finishingmethod_id
                  and ilp.invoiceline_id=il.invoiceline_id
                  and ilp.weareremployment_link_id = we.WEAREREMPLOYMENT_LINK_ID
                  and il.invoicelinetype_id=1--rent
                  and il.invoiceheader_id=ih.invoiceheader_id
                  and ilp.billingmethod in (1, 3)
                  and ih.startdate<=sh.statusquodate
                  and ih.enddate>=sh.statusquodate
                  and ih.deltocustomer_link_id=c.customer_id
                  and coalesce(ih.splitupcode, cc.code) = cc.code
     group by ih.invoiceheader_id,il.invoicelinetype_id, c.customer_id,c.customernumber,we.wearernumber,we.wearername,p.product_id,cc.code,cc.description, p.code,l.language_id,l.code
 union all
select 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.QtyRentedPerPiece + si.beyondlifetimecirc) changesperweek,/*else si.QtyRentedPerPiece end*/
        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,cc.code CostcenterCode, cc.description CostcenterDesc,
       1 invoicelinetype_id
            from statusquoheader sh,
                 sqitemincirculation si,
                 customer c,
                 Costcenter cc, distributionpoint dp, product p,
                 weareremployment_link we,
                 invoiceheader ih, invoiceline il, invoicelineproduct ilp,
                 LANGUAGES L
            where sh.statusquoheader_id = si.statusquoheader_id
                  and si.weareremployment_link_id = we.weareremployment_link_id --this must be NOT NULL
                  and sh.statusquotype = 1 --Items In Circ      and si.numberemploymentscharge > 0 -- commented for CBD
                  and c.customer_id = si.customer_link_id
                  and si.distributionpoint_link_id = dp.distributionpoint_id
                  and dp.costcenter_id=cc.costcenter_id
                  and si.product_link_id = p.product_id
                  and si.product_link_id=ilp.product_link_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='*'))
                  and si.finishingmethod_id=ilp.finishingmethod_id
                  and ilp.invoiceline_id=il.invoiceline_id
                  and ilp.WEAREREMPLOYMENT_LINK_ID is null
                  and il.invoicelinetype_id=1--rent
                  and il.invoiceheader_id=ih.invoiceheader_id
                  and ilp.billingmethod in (1, 3)
                  and ih.startdate<=sh.statusquodate
                  and ih.enddate>=sh.statusquodate
                  and ih.deltocustomer_link_id=c.customer_id
                 and coalesce(ih.splitupcode, cc.code) = cc.code
     group by ih.invoiceheader_id,il.invoicelinetype_id, c.customer_id,c.customernumber,we.wearernumber,we.wearername,p.product_id,cc.code,cc.description, p.code,l.language_id,l.code
 union all
select 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,
        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,cc.code CostcenterCode, cc.description CostcenterDesc,
        invoicelinetype_id
                from deliveryscan ds,customer c,weareremployment_link we,packingnote pn,
                distributionpoint dp,Costcenter cc,packingnoteline pnl,product p,
                invoiceline il,invoiceheader ih,invoicelineproduct ilp,LANGUAGES L
                where ds.customer_link_id=c.customer_id
                and ds.chargewashing='Y'
                and ds.outscannodelivery in (0,2)
                and ds.weareremployment_link_id=we.weareremployment_link_id
                and pn.packingnote_id=ds.packingnote_id
                and pn.distributionpoint_id=dp.distributionpoint_id
                and cc.costcenter_id=dp.costcenter_id
                and pn.packingnote_id=pnl.packingnote_id
                and ds.product_link_id=pnl.product_id
                and pnl.invoiceheader_id=ih.invoiceheader_id
                and pnl.product_id=p.product_id
                and il.invoiceheader_id=ih.invoiceheader_id
                and ih.deltocustomer_link_id=c.customer_id
                and ilp.invoiceline_id=il.invoiceline_id
                and ilp.weareremployment_link_id = we.WEAREREMPLOYMENT_LINK_ID
                and il.invoicelinetype_id=2
                and ilp.product_link_id=ds.product_link_id
                and ds.sizedefinition_link_id=pnl.sizedefinition_id
                and (ds.sizedefinition_link_id=ilp.sizedefinition_link_id or ilp.sizedefinition_link_id=(select sd.sizedefinition_id from sizedefinition sd where sd.code='*'))
                and ds.finishingmethod_id=ilp.finishingmethod_id
                group by ih.invoiceheader_id,il.invoicelinetype_id, c.customer_id,c.customernumber,we.wearernumber,we.wearername,p.product_id,cc.code,cc.description, p.code,l.language_id,l.code
                union all
select 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,
        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,cc.code CostcenterCode, cc.description CostcenterDesc,
        invoicelinetype_id
                from deliveryscan ds,customer c,weareremployment_link we,packingnote pn,
                distributionpoint dp,Costcenter cc,packingnoteline pnl,product p,
                invoiceline il,invoiceheader ih,invoicelineproduct ilp,LANGUAGES L
                where ds.customer_link_id=c.customer_id
                and ds.chargewashing='Y'
                and ds.outscannodelivery in (0,2)
                and ds.weareremployment_link_id=we.weareremployment_link_id
                and pn.packingnote_id=ds.packingnote_id
                and pn.distributionpoint_id=dp.distributionpoint_id
                and cc.costcenter_id=dp.costcenter_id
                and pn.packingnote_id=pnl.packingnote_id
                and ds.product_link_id=pnl.product_id
                and pnl.invoiceheader_id=ih.invoiceheader_id
                and pnl.product_id=p.product_id
                and il.invoiceheader_id=ih.invoiceheader_id
                and ih.deltocustomer_link_id=c.customer_id
                and ilp.invoiceline_id=il.invoiceline_id
                and ilp.WEAREREMPLOYMENT_LINK_ID is null
                and il.invoicelinetype_id=2
                and ilp.product_link_id=ds.product_link_id
                and ds.sizedefinition_link_id=pnl.sizedefinition_id
                and (ds.sizedefinition_link_id=ilp.sizedefinition_link_id or ilp.sizedefinition_link_id=(select sd.sizedefinition_id from sizedefinition sd where sd.code='*'))
                and ds.finishingmethod_id=ilp.finishingmethod_id
                group by ih.invoiceheader_id,il.invoicelinetype_id, c.customer_id,c.customernumber,we.wearernumber,we.wearername,p.product_id,cc.code,cc.description, p.code,l.language_id,l.code) x

/
create or replace view V_COSTS_SPECS_PER_WEARER_INV
 (INVOICEHEADER_ID, INVOICEBUSINESSUNIT_ID, ENDWEEK, ENDYEAR, INVOICEDATE, INVOICENUMBER, PURCHASEORDER, 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.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_CPLMANUALADJUSTMENTS_LLG
 (BUCODE, STARTDATERENT, CUSTOMERNUMBER, CUSTOMERNAME, PRODUCTCODE, PRODUCTDESC, SIZECODE, ADJUSTMENTRC, ADJUSTMENTRC_DESC, QUANTITY, REMARK, SYSTEMUSERNAME, TIMESTAMP, RENTPRICE, LOANPRICE, LANGUAGECODE)
as select
 (select bu.code from businessunit bu where bu.businessunit_id = c.defaultbusinessunit_id) bucode,
 rqa.adjustmentdate startdaterent,
 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 rc.code from reasoncode rc where rc.reasoncode_id = rqa.reasoncode_id) adjustmentrc,
(select rcd.description from reasoncode rc, reasoncode_desc rcd where rc.reasoncode_id = rcd.reasoncode_id and rcd.language_id = l.language_id
 and rc.reasoncode_id = rqa.reasoncode_id) adjustmentrc_desc,
 rqa.quantity,
 rqa.remark,
 (select su.username from systemuser su where su.systemuser_id = rqa.systemuser_id) systemusername,
 rqa.timestamp,
 pack_price.Rent_Price(c.customer_id,p.product_id,sd.sizedefinition_id,fm.finishingmethod_id,rqa.adjustmentdate) rentprice,
 pack_price.Loan_Price(c.customer_id,p.product_id,sd.sizedefinition_id,fm.finishingmethod_id,rqa.adjustmentdate) loanprice,
 l.code languagecode
from rentalqtyadjustment rqa
inner join productlistperdistribpoint plpd on rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
inner join distributionpoint dp on plpd.distributionpoint_id = dp.distributionpoint_id
inner join product p on plpd.product_id = p.product_id
inner join sizedefinition sd on plpd.sizedefinition_id = sd.sizedefinition_id
inner join finishingmethod fm on plpd.finishingmethod_id = fm.finishingmethod_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
where rqa.deliveryvariations_id is null

/
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_CREDITCARDRECEIPT_AMM
 (CUSTOMERNUMBER, CUSTOMERNAME, COUNTRYCODE, STREET, ZIPCODE, STATE, CITY, FAXNO, CREDITCARDTRANSACTION_ID, INVOICEAMOUNTDECIMALS, CURRENCYCODE, REFERENCENUMBER, REMITIDENTIFICATION, ARTRANSACTIONDATE, REMARK, AMOUNT, CLOSINGAMOUNT, ORIGIN, RESPDATETIME, AUTHORIZATIONCODE, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTCITY, PLANTSTATE, PLANTZIPCODE, PLANTPHONENO, PLANTEMAIL, PLANTFAX, CUSTOMEREMAIL, CARDBRAND, USAGE)
as select
  cu.customernumber, cu.name customerName,  c.code countrycode
, coalesce(address.street, debtorAddress.Street) street
, coalesce(address.zipcode, debtorAddress.zipcode) zipcode
, coalesce(address.state, debtorAddress.State) state
, coalesce(address.city, debtorAddress.city) city
, cu.faxno
, cct.creditcardtransaction_id
, 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
, (select a.amount from artransaction a where cct.artransaction_id = a.artransaction_id) amount
, ca.amount Closingamount
, cct.origin
, cct.respdatetime
, cct.authorizationcode
, p.code plantcode
, p.name plantname
, plantaddress.street plantstreet
, plantaddress.city plantcity
, plantaddress.state plantstate
, plantaddress.zipcode plantzipcode
, p.phoneno plantphoneno, p.email plantemail, p.faxno plantfax
, coalesce((select cp.email from contactperson cp where cp.customer_id = cu.customer_id and cp.invoicecontactperson = 'Y'),cu.email) customeremail
, cct.cardbrand
, artt.usage
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
, businessunit bu
, plant p
, address plantaddress
, artransactiontype artt
, country c
, plantcompany pc
where
 art.currency_id = currencyCU.Currency_Id
and art.billtocustomer_link_id = cu.customer_id
and cu.debtor_id = debtor.customer_id
and art.artransaction_id = ca.debitartransaction_id
and bu.businessunit_id = cu.defaultbusinessunit_id
and bu.plant_id = p.plant_id
and pc.plant_id=p.plant_id
and pc.address_id = plantaddress.address_id
and c.country_id=p.country_id
and (ca.creditartransaction_id = cct.artransaction_id
or ca.debitartransaction_id = cct.artransaction_id)
and artt.artransactiontype_id = art.artransactiontype_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--change WBO
, 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
, (select pra1.ranking from productranking pra1 where pra1.productranking_id = pr.productranking_id) prodranking
, (select pra2.priority from productranking pra2 where pra2.productranking_id = pr.productranking_id) 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'--rework line 150 WBO added
  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--, curr.username, curr.systemuser_id
, 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, product pr, salesarea sa, businessunit bu, customer cu
left outer join customer ma1 on cu.masteraccount_id = ma1.customer_id --change WBO
left outer join customer comm1 on cu.commoncustomer_id = comm1.customer_id --change WBO
, productlistperdistribpoint plpd
, distributionpoint dp, department de, standarddeliveryline sdl
, customer deb
, customerbillinginfo cbi1 left outer join customer payby1 on cbi1.paybycustomer_link_id = payby1.customer_id--change WBO
, languages lan--, systemuser curr
where plpc.product_id = pr.product_id and plpc.customer_id = cu.customer_id
      and plpc.billingmethod in (1, 3)
      and plpc.dateactive <= trunc(sysdate) and plpc.dateinactive >= trunc(sysdate)
      and plpc.product_id = plpd.product_id and plpd.distributionpoint_id = dp.distributionpoint_id
      and dp.department_id = de.department_id and de.customer_id = cu.customer_id
      and (plpd.sizedefinition_id = plpc.sizedefinition_id
          --OR plpc.sizedefinition_id in (select sd1.sizedefinition_id from sizedefinition sd1 where sd1.code = '*')
          )--rework line 140
      and plpd.finishingmethod_id = plpc.finishingmethod_id
      and sdl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_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
                             -- (getdateforweekyear(1, TDS.TemporaryStopStartWeek, TDS.TemporaryStopStartYear) <= trunc(sysdate)) and
                             -- (getdateforweekyear(7, TDS.TemporaryStopStartWeek, TDS.TemporaryStopStartYear) > trunc(sysdate)) and
                           TDS.TemporaryStopStartWeek <= to_number(to_char(sysdate,'IW')) and TDS.TemporaryStopStartYear <= to_number(to_char(sysdate,'YYYY')) and --wb0
                           TDS.Temporarystopendweek  > to_number(to_char(sysdate,'IW')) and TDS.Temporarystopendyear >to_number(to_char(sysdate,'YYYY')) and --wbo
                            (TDS.TempStopRentForYearWeek = 'Y')) or
                            ((TDS.TempStopStartWeekForYear <> 0) and
                         -- (getdateforweekyear(1, TDS.TempStopStartWeekForYear, Year(sysdate)) <= trunc(sysdate)) and
                         -- (getdateforweekyear(7, TDS.TempStopEndWeekForYear, Year(sysdate)) > trunc(sysdate)) and
                          TDS.TempStopStartWeekForYear<= to_number(to_char(sysdate,'IW')) and  TDS.TempStopEndWeekForYear> to_number(to_char(sysdate,'IW')) and --wbo
                            (TDS.TempStopRentForWeek = 'Y'))))
      and cu.debtor_id = deb.customer_id
      --AND EXISTS (SELECT 1 FROM businessunitsperusergroup bug WHERE bug.usergroup_id = curr.usergroup_id AND bug.businessunit_id = cu.defaultbusinessunit_id)
      and pr.typeofmerchandise = 1
      and deb.customer_id = cbi1.customer_id --added WBO
      and cu.salesarea_id = sa.salesarea_id and bu.businessunit_id = cu.defaultbusinessunit_id
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--change WBO
, 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
, (select pra1.ranking from productranking pra1 where pra1.productranking_id = pr.productranking_id) prodranking
, (select pra2.priority from productranking pra2 where pra2.productranking_id = pr.productranking_id) prodpriority
, plpc.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 = plpc.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
, plpc.changesperweek plpc_changesperweek, lan.Code Language_Code--, curr.username, curr.systemuser_id
, 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 product pr, salesarea sa, businessunit bu, customer cu
left outer join customer ma1 on cu.masteraccount_id = ma1.customer_id --change wbo
left outer join customer comm1 on cu.commoncustomer_id = comm1.customer_id --change WBO
, wearer wr, weareremployment we, wearerinventory wi
     left outer 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.sizedefinition_id not in (select plpc2.sizedefinition_id from productlistpercustomer plpc2
                where (plpc2.customer_id = plpc.customer_id and plpc2.product_id = plpc.product_id
                and plpc2.sizedefinition_id = wi.sizedefinition_id
                and plpc2.billingmethod in (1, 3)
                and plpc2.finishingmethod_id = plpc.finishingmethod_id
                and plpc2.dateactive <= trunc(sysdate) and plpc2.dateinactive >= trunc(sysdate)))))
            and plpc.billingmethod in (1, 3)
            and wi.finishingmethod_id = plpc.finishingmethod_id
            and plpc.dateactive <= trunc(sysdate) and plpc.dateinactive >= trunc(sysdate))
     , customer deb
     , customerbillinginfo cbi1 left outer join customer payby1 on cbi1.paybycustomer_link_id = payby1.customer_id---change WBO
     , distributionpoint dp, department de, languages lan--, systemuser curr
where wi.product_id = pr.product_id and cu.customer_id = coalesce(plpc.customer_id, wr.customer_id)
      and wr.customer_id = cu.customer_id and we.wearer_id = wr.wearer_id
      and wi.weareremployment_id = we.weareremployment_id
      and wi.dateactive <= trunc(sysdate) and wi.dateinactive >= trunc(sysdate)
      and Not Exists (select 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')) --added wbo
                      --getdateforweekyear(1, TGRS.StartWeek, TGRS.StartYear) <= trunc(sysdate)
                     and (TGRS.EndWeek = 0 OR TGRS.EndYear=0 or (TGRS.EndWeek <> 0 and TGRS.EndYear <> 0 and --wbo
                     --getdateforweekyear(7, TGRS.EndWeek, TGRS.EndYear) > trunc(sysdate)
                     TGRS.EndWeek > to_number(to_char(sysdate,'IW')) and TGRS.EndYear>to_number(to_char(sysdate,'YYYY'))
                     )))
      and cu.debtor_id = deb.customer_id
      and we.distributionpoint_id = dp.distributionpoint_id and dp.department_id = de.department_id
      --AND EXISTS (SELECT 1 FROM businessunitsperusergroup bug WHERE bug.usergroup_id = curr.usergroup_id AND bug.businessunit_id = cu.defaultbusinessunit_id)
      and pr.typeofmerchandise = 2
      and deb.customer_id = cbi1.customer_id --added WBO
      and cu.salesarea_id = sa.salesarea_id and bu.businessunit_id = cu.defaultbusinessunit_id
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--change WBO
, 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
, /*pack_price.SpecialCharge_Price(cu.customer_id, sc.specialcharge_id, sysdate)*/ 0 Price
, ' ' plpc_changesperweek, lan.Code Language_Code--, curr.username, curr.systemuser_id
, /*case when sc.startdate <= trunc(sysdate) then sc.oldamount else sc.newamount end*/
  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, specialcharge sc, salesarea sa, businessunit bu, customer cu
left outer join customer ma1 on cu.masteraccount_id = ma1.customer_id --change WBO
left outer join customer comm1 on cu.commoncustomer_id = comm1.customer_id --change WBO
, customer deb
, customerbillinginfo cbi1 left outer join customer payby1 on cbi1.paybycustomer_link_id = payby1.customer_id ---change WBO
, languages lan--, systemuser curr
where csc.specialcharge_id = sc.specialcharge_id and csc.customer_id = cu.customer_id
      and sc.fixedamount = 'Y' and sc.frequency <= 4
      and cu.debtor_id = deb.customer_id
      and deb.customer_id = cbi1.customer_id --added WBO
      and cu.salesarea_id = sa.salesarea_id and bu.businessunit_id = cu.defaultbusinessunit_id

/
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(getcurrentdate(), 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(getcurrentdate(), 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(getcurrentdate(), 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(getcurrentdate(), 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, ZIPCODE, CITY, COUNTY, STATE, MAILSTREET, 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)
as SELECT
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.ZIPCODE,VISITADDRESS.CITY, VISITADDRESS.COUNTY, VISITADDRESS.STATE,
MAILADDRESS.STREET mailstreet, 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,
--CONSIGNMENTLAYOUT.CODE ,
CUSTOMER.CONSIGNMENTNOTELEVEL, --CUSTOMER.PRINTCONSIGNMENTNOTE,
 CUSTOMER.INTERNETORDERING,
CUSTOMER.IMPORTOCCUPANCYHHT,
CUSTOMER.RETURNLINEN, CUSTOMER.RETURNGARMENTS, CUSTOMER.CODEGARMENTSUNIQUELY,
CUSTOMER.LOCKERMANAGEMENT, CUSTOMER.USESGARMENTDISPENSER, --CUSTOMER.USEDISPENSEROBLIGATED,
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,
--STATES.CODE, STATES.NAME,
--CITYCOUNTY2.NAME, CITYCOUNTY.NAME,
CUSTOMER.CUSTOMERMARKINGGARMENT, CUSTOMER.INVOICEFREQUENCY_ID,
CUSTOMER.SYSTEMUSER_ID, CUSTOMER.TIMESTAMP, LANGUAGES.CODE languagecode
FROM
ADDRESS VISITADDRESS, ADDRESS MAILADDRESS,COUNTRY, CURRENCY,
BUSINESSUNIT,
CUSTOMER DEBTOR, CUSTOMER MASTERACCOUNT,  COMMUNICATIONMETHOD,
MARKETSEGMENT, SALESAREA,
FORMLAYOUT DELIVERYLAYOUT,
FORMLAYOUT FORMLAYOUT_I,
--STATES, --CITYCOUNTY CITYCOUNTY2,CITYCOUNTY,
CUSTOMER
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),
LANGUAGES CUSTOMERLANGUAGES,LANGUAGES
WHERE CUSTOMER.VISITADDRESS_ID =VISITADDRESS.ADDRESS_ID
and CUSTOMER.MAILADDRESS_ID = MAILADDRESS.ADDRESS_ID
and CUSTOMER.DEBTOR_ID = DEBTOR.CUSTOMER_ID
and CUSTOMER.MASTERACCOUNT_ID = MASTERACCOUNT.CUSTOMER_ID
and CUSTOMER.COUNTRY_ID = COUNTRY.COUNTRY_ID
and CUSTOMER.CURRENCY_ID = CURRENCY.CURRENCY_ID
and CUSTOMER.LANGUAGE_ID = CUSTOMERLANGUAGES.LANGUAGE_ID
and CUSTOMER.DEFAULTBUSINESSUNIT_ID = BUSINESSUNIT.BUSINESSUNIT_ID
and CUSTOMER.MARKETSEGMENT_ID = MARKETSEGMENT.MARKETSEGMENT_ID
and CUSTOMER.SALESAREA_ID = SALESAREA.SALESAREA_ID
and CUSTOMER.COMMUNICATIONMETHOD_ID = COMMUNICATIONMETHOD.COMMUNICATIONMETHOD_ID
AND (CUSTOMER.DELIVERYNOTELAYOUT_ID = DELIVERYLAYOUT.FORMLAYOUT_ID
AND DELIVERYLAYOUT.FORMTYPE = 'DN')
AND (CUSTOMER.INVOICELAYOUT_ID = FORMLAYOUT_I.FORMLAYOUT_ID
AND FORMLAYOUT_I.FORMTYPE = 'IN')

/
create or replace view V_CUSTOMERACTIVECONTRACT
 (CUSTOMER_ID, DATEACTIVE, CONTRACTSPERCUSTOMER_ID)
as SELECT cpc.customer_id, cpc.dateactive, cpc.contractspercustomer_id
FROM contractspercustomer cpc
ORDER BY cpc.dateactive DESC
/
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, CITY, CURRENCYCODE)
as select
  cu.customer_id ,address.city, currency.code currencyCode
from
  customer cu, address, currency
where
    cu.visitaddress_id = address.address_id
and cu.currency_id = currency.currency_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, address cua, businessunit bu, plant p, address pa,REPORTPARAM rp
where cua.address_id = cu.visitaddress_id
AND cu.defaultbusinessunit_id = bu.businessunit_id
AND bu.plant_id = p.plant_id
AND p.address_id = pa.address_id
AND rp.number_value IS NULL
AND cu.customernumber >= rp.number_value1
AND cu.customernumber <= 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 customer cu, deliverypoint dp, address dpa, businessunit bu, plant p, address pa, REPORTPARAM rp
where dp.customer_id = cu.customer_id
and dpa.address_id = dp.deliveryaddress_id
AND cu.defaultbusinessunit_id = bu.businessunit_id
AND bu.plant_id = p.plant_id
AND p.address_id = pa.address_id
AND dp.deliverypoint_id = rp.number_value
AND cu.customernumber >= rp.number_value1
AND cu.customernumber <= 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_CUSTOMERCONTRACTS_LST
 (CUSTOMER_ID, CONTACTPERSON_ID, CONTRACTSPERCUSTOMER_ID, CODE, DATEACTIVE, DATEINACTIVE, ACCOUNTMANAGER, PURCHASEORDER, ANNIVERSARYPRICEADJ, SERVICEEMPL)
as select cpc.customer_id, cpc.contactperson_id, cpc.contractspercustomer_id
, cpc.code, cpc.dateactive, cpc.dateinactive
, (select e.name from employee e where cpc.accountmanager_id=e.employee_id) AccountManager
, cpc.purchaseorder, cpc.anniversarypriceadj
--add WBO
, (select e2.name from customer cu, employee e2 where cu.customer_id=cpc.customer_id and cu.serviceemployee_id=e2.employee_id) serviceempl
from contractspercustomer cpc

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

/
create or replace view V_CUSTOMERDETAILRECAP_LST
 (BUSINESSUNITCODE, BUSINESSUNITDESCRIPTION, CUSTOMERID, CUSTOMERNUMBER, CUSTOMERNAME, STREET1, STREET2, CITY, ZIPCODE, STATE, LEGALNAME, EXTRANAME1, NATACCOUNT, SEARCHNAME, MAILSTREET, MAILSTREET2, MAILCITY, MAILZIP, MAILSTATE, PHONENO, FAXNO, DELIVERYDAYS_US, CUST_DELIVERYDAYS_US, COUNTRYCODE, COUNTRYDESC, MARKET_SEGMENT, BILLCUSTOMERNUMBER, BILLNAME, BILLSTREET1, BILLSTREET2, BILLCITY, BILLZIPCODE, BILLSTATE, BILLCOUNTRYCODE, DELIVERYSCHEMECODE, ROUTENUMBER, PAYMENTMETHOD, PAYMENTTYPE, TAXABLE
, VATNUMBER, BANKACCOUNT, PAYMENTTERMS, INVOICEFREQUENCY_DESC, CUSTOMERCLUSTER_DESC, MINIMUMINVOICEAMOUNT, CURRENCYCODE, CURRENCYINVOICEAMOUNTDECIMALS, GARMENTRENTSPECIFICATION, REMARK, CUSTOMERDELIVERYDAYNUMBER, CUSTOMERDELIVERYDAYDESC, MARKETSEGMENTCODE, ACTIVE, DATEACTIVE, DATEINACTIVE, SALESAREACODE, SALESAREA_DESC, COM_METHOD, CHAIN_DESC, LANGUAGECODE, LANGUAGEDESC)
as select
  bu.code BusinessunitCode, bu.description BusinessunitDescription , cu.customer_id customerid
, cu.customernumber, cu.name CustomerName, a.street Street1, a.street2, a.city, a.zipcode, a.state
-- add WBO
, bill.legalname, cu.extraname1, (select nacc.name from nationalaccount nacc where nacc.nationalaccount_id=cu.nationalaccount_id) nataccount
, cu.searchname, m.street MailStreet, m.street2 MailStreet2
, m.city MailCity, m.zipcode MailZip, m.state MailState
, cu.phoneno, cu.faxno, s.value DELIVERYDAYS_US
, F_DELIVERYDAYS_US(s.value, cu.customer_id, languages.language_id) Cust_DELIVERYDAYS_US
, (select co.code from country co, plant pl where bu.plant_id=pl.plant_id and pl.country_id=co.country_id) CountryCode
, (select co.description from country co, plant pl where bu.plant_id=pl.plant_id and pl.country_id=co.country_id) CountryDesc
, (select msd.description from  marketsegment_desc msd where cu.marketsegment_id=msd.marketsegment_id and msd.language_id=languages.language_id) Market_segment
, bill.customernumber Billcustomernumber, bill.name BillName, ba.street BillStreet1
, ba.street2 BillStreet2, ba.city BillCity, ba.zipcode BillZipcode, ba.state BillState
, (select co.code from country co, plant pl, businessunit bt where bill.defaultbusinessunit_id=bt.businessunit_id and bt.plant_id=pl.plant_id and pl.country_id=co.country_id) BillCountryCode
, (select deliveryscheme.code from deliveryscheme
    where deliveryscheme.deliveryscheme_id = F_DELIVERYSCHEMEPERCUSTOMER(cu.customer_id)) deliveryschemeCode
, (select route.routenumber from route, routestop r
  where route.route_id = r.route_id and route.active = 'Y'
  and r.routestop_id = F_FIRSTROUTESTOP(cu.customer_id,F_DELIVERYSCHEMEPERCUSTOMER(cu.customer_id))) routenumber
, cu.paymentmethod, cu.paymenttype, cu.taxable, cu.vatnumber, cbi.bankaccount
, (select ptd.description from paymentterms_desc ptd where ptd.paymentterms_id=cbi.paymentterms_id and ptd.language_id=languages.language_id) PaymentTerms
, (select ifd.description from invoicefrequency_desc ifd where ifd.invoicefrequency_id=cu.invoicefrequency_id and ifd.language_id=languages.language_id) invoicefrequency_desc
--, (select cc.description from customercluster cc where cu.cluster_id=cc.cluster_id ) customercluster_desc
,F_CUSTOMERSPERCLUSTER(cu.customer_id) customercluster_desc
, cu.minimuminvoiceamount, currency.code currencyCode, currency.invoiceamountdecimals currencyInvoiceamountdecimals
, cu.garmentrentspecification
, cu.remark , customerdeliveryscheme.day_id customerdeliverydayNumber
, (select description from day_desc  where customerdeliveryscheme.day_id = day_desc.day_id
 and day_desc.language_id = languages.language_id ) customerdeliverydayDesc
, marketsegment.code marketsegmentCode, cu.active, cu.dateactive, cu.dateinactive
, salesarea.code salesareaCode
, (select sad.description from salesarea_desc sad where sad.salesarea_id=salesarea.salesarea_id and sad.language_id=languages.language_id) Salesarea_desc
, (select cmd.description from communicationmethod_desc cmd where cu.communicationmethod_id=cmd.communicationmethod_id and cmd.language_id=languages.language_id) Com_method
, (select cha.name from chain cha where cha.chain_id=cu.chain_id) Chain_desc
, languages.code languagecode, languages.description Languagedesc
from customer cu
  left outer join ( customer Bill join address b on b.address_id = bill.visitaddress_id) on bill.customer_id = cu.debtor_id
 -- Change WBO
 -- left outer join ( customerbillinginfo cbi join paymentterms pt on cbi.paymentterms_id=pt.paymentterms_id ) on cu.customer_id=cbi.customer_id
left outer join ( customerbillinginfo cbi join paymentterms pt on cbi.paymentterms_id=pt.paymentterms_id ) on cu.debtor_id=cbi.customer_id
, address a, address m, customerdeliveryscheme
, businessunit bu
  left outer join systemsetting s on bu.plant_id=s.plant_id
, currency,  marketsegment
, salesarea,  languages, address ba
where cu.visitaddress_id = a.address_id
and cu.mailaddress_id=m.address_id
and cu.defaultbusinessunit_id = bu.businessunit_id
and cu.currency_id = currency.currency_id
and cu.marketsegment_id = marketsegment.marketsegment_id
and cu.salesarea_id = salesarea.salesarea_id
and cu.customer_id = customerdeliveryscheme.customer_id
and bill.invoiceaddress_id=ba.address_id
and customerdeliveryscheme.deliveryscheme_id = F_DELIVERYSCHEMEPERCUSTOMER(cu.customer_id)
and s.name='DELIVERYDAYS_US'

/
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_CUSTOMERFLEXFIELDS_SMG
 (CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, COCNUMBER, PNNUMBER, VATNUMBER, VAT_REGNO, TIN)
as select cu.customer_id, cu.customernumber, cu.name customername, cu.cocnumber, cu.pnnumber, cu.vatnumber,
(select dff.stringvalue from CharacteristicsTempLine chtl, characteristic ch, DialogFlexFields dff where 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 ch.code = 'VAT_REGNO') VAT_REGNO,
(select dff.stringvalue from CharacteristicsTempLine chtl, characteristic ch, DialogFlexFields dff where 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 ch.code = 'TIN') TIN
from dialogs dia, CharacteristicsTemplate cht, customer cu
where cht.dialog_id = dia.dialog_id and dia.code = 'Customer' and cht.code = 'STEUERDATEN'

/
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 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
union all
select rp.reportparam_id, c.customer_id, -1 bufiltered
from customer c, 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_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_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_CUSTOMERSTICKER_CBD
 (CLIENTDELIVERYNOTE_ID, CUSTOMERCLIENTS, CUSTOMERNAME, DELIVERYPOINT_DESC, DISTRIBUTIONPOINT_DESC, STREET, STREET2, ZIPCODE, CITY, CLIENTDELIVERYNOTENUMBER, DELIVERYDATE, CUSTOMERNUMBER, EMPLOYEE_NAME, EMPLOYEE_PHONE, EMPLOYEE_EMAIL, BATCHNUMBER, BOXNUMBER, CLIENT_NAME, CLIENT_FIRSTNAME, DEPARTMENTNUMBER, DEPARTMENT_DESC, CLIENTNUMBER, CLIENTNAME, ROOMNUMBER, PRODUCT_CODE, PRODUCT_DESC, QTYSCANNEDOUT, QTYCOUNTEDOUT, ROUTENUMBER, STOPNUMBER, DESCRIPTION)
as select cd.clientdeliverynote_id, crs.customerclients,
  cu.name customername,
  CASE WHEN coalesce(crs.customerclients, 1) = 0
      THEN del1.description
      else del2.description
  end  DeliveryPoint_Desc,
  CASE WHEN coalesce(crs.customerclients, 1) = 0
      THEN dip1.description
      else dip2.description
  end  DistributionPoint_Desc,
  CASE WHEN coalesce(crs.customerclients, 1) = 0
      THEN ad1.street
      else ad2.street
  end  street,
  CASE WHEN coalesce(crs.customerclients, 1) = 0
      THEN ad1.street2
      else ad2.street2
  end  street2,
  CASE WHEN coalesce(crs.customerclients, 1) = 0
      THEN ad1.zipcode
      else ad2.zipcode
  end  zipcode,
  CASE WHEN coalesce(crs.customerclients, 1) = 0
      THEN ad1.city
      else ad2.city
  end  city,
  cd.clientdeliverynotenumber, cd.deliverydate, cu.customernumber,
  emp.name employee_name, emp.phoneno employee_phone, emp.email employee_email,
  ba.batchnumber, cd.boxnumber, cl.name client_name, cl.firstname client_firstname,
  CASE WHEN coalesce(crs.customerclients, 1) = 0
      THEN d1.departmentnumber
      else d2.departmentnumber
  end departmentnumber,
  CASE WHEN coalesce(crs.customerclients, 1) = 0
      THEN coalesce(cl.legacycode, d1.description)
      else coalesce(cl.legacycode, d2.description)
  end department_desc,
  cl.clientnumber, cl.name clientname, coalesce(cd.roomnumber, dr.roomnumber) roomnumber,
  (select pr.code from product_link pr where cdl.product_link_id = pr.product_link_id) product_code,
  (select prd.description from product_link_desc prd where cdl.product_link_id = prd.product_link_id and prd.language_id = cu.language_id) product_desc,
  cdl.qtyscannedout, cdl.qtycountedout, rt.routenumber, cd.stopnumber, rt.description
from clientdeliverynote cd, clientdeliverynoteline cdl, finishingmethod fm, batch ba, route rt, client cl
    left outer join clientresident cr
         inner join departmentroom dr
               inner join department d1 on dr.department_id = d1.department_id
               inner join distributionpoint dip1
                     inner join deliverypoint del1
                           inner join address ad1 on del1.deliveryaddress_id = ad1.address_id
                     on dip1.deliverypoint_id = del1.deliverypoint_id
               on dr.distributionpoint_id = dip1.distributionpoint_id
         on cr.departmentroom_id = dr.departmentroom_id
    on cl.client_id = cr.client_id
    left outer join clientprivateperson cp
               inner join distributionpoint dip2
                     inner join department d2 on dip2.department_id = d2.department_id
                     inner join deliverypoint del2
                           inner join address ad2 on del2.deliveryaddress_id = ad2.address_id
                     on dip2.deliverypoint_id = del2.deliverypoint_id
               on cp.distributionpoint_id = dip2.distributionpoint_id
    on cl.client_id = cp.client_id
    , customer cu
    left outer join customerresidentialsettings crs on crs.customer_id = cu.customer_id
    left outer join employee emp on emp.employee_id = cu.serviceemployee_id
where cd.client_link_id = cl.client_id
  and cd.customer_link_id = cu.customer_id
  and cdl.clientdeliverinote_id = cd.clientdeliverynote_id
  and cdl.finishingmethod_id = fm.finishingmethod_id
  and fm.printstickeratoutscan = 'Y'
  and cd.batch_id = ba.batch_id
  and cd.route_id = rt.route_id

/
create or replace view V_CUSTOMERSURVEYSCHEDULE
 (DEFAULTBUSINESSUNIT_ID, SURVEY_CODE, SURVEY_DESCRIPTION, SURVEY_FREQUENCY, NEXTSURVEYDATE, CUSTOMERNUMBER, CUSTOMERNAME, SURVEYINTERVAL, EMPLOYEENUMBER, EMPLOYEENAME, LASTSURVEYDATE, REPORTPARAM_ID)
as select c.defaultbusinessunit_id,
svt.code survey_code,
svt.description survey_description,
svt.frequency survey_frequency,
csvt.nextsurveydate,
c.customernumber,
c.name customername,
csvt.surveyinterval,
e.employeenumber,
e.name employeename,
csvt.lastsurveydate,
rp.reportparam_id
from surveytype svt
, customersurveytype csvt
  left outer join employee e on csvt.employee_id = e.employee_id
, customer c
, reportparam rp
where svt.surveytype_id = csvt.surveytype_id
and csvt.customer_id = c.customer_id
and (svt.code >= rp.string_value1 and svt.code <= rp.string_value2) --survey type code
and (c.customernumber >= rp.number_value1 and c.customernumber <= rp.number_value2) --customer code
and ((csvt.lastsurveydate >= rp.date_value1 and csvt.lastsurveydate <= rp.date_value2) or csvt.lastsurveydate is null) --last survey date
and (csvt.nextsurveydate >= rp.date_value3 and csvt.nextsurveydate <= rp.date_value4) --next survey date
and (c.defaultbusinessunit_id = rp.number_value9 or exists
    (select 1 from customeractivities ca where ca.customer_id = c.customer_id and ca.processbusinessunit_id = rp.number_value9))

/
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, CONSPOINTNUMBER, CONSPOINTDESC, PRODUCTGROUPCODE, PRODUCTGROUPDESC, PRODUCT_ID, PRODUCTCODE, PRODUCTDESC, SIZECODE, SIZEDESC, COLUMN1, COLUMN2, COLUMN3, COLUMN4, COLUMN5, COLUMN6, COLUMN7, COLUMN8, COLUMN9, TOTAL_DAYS_AT_CUSTOMER, TOTAL_STOCK, QTY_USED, LANGUAGECODE)
as select q.reportparam_id,
      q.customer_id,
      cu.customernumber,
      cu.name customername,
      q.department_id,
      d.departmentnumber,
      d.description departmentdesc,
      dp.distributionpointnumber conspointnumber,
      dp.description conspointdesc,
      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,
      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 = languages.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 = languages.language_id) sizedesc,
      q.column1,
      q.column2,
      q.column3,
      q.column4,
      q.column5,
      q.column6,
      q.column7,
      q.column8,
      q.column9,
      q.total_days_at_customer,
      q.total_stock,
      q.qty_used,
      languages.code languagecode
 from (select y.reportparam_id,
        y.customer_id,
        y.department_id,
        y.distributionpoint_id,
        y.product_id,
        y.sizedefinition_id,
        sum(y.column1) column1,
        sum(y.column2) column2,
        sum(y.column3) column3,
        sum(y.column4) column4,
        sum(y.column5) column5,
        sum(y.column6) column6,
        sum(y.column7) column7,
        sum(y.column8) column8,
        sum(y.column9) column9,
        sum(y.total_days_at_customer) total_days_at_customer,
        sum(y.number_of_items) total_stock,
        sum(y.qty_used) qty_used
         from (
               --- first part of union : select unique pool items
               select x.reportparam_id,
                      x.customer_id,
                      x.department_id,
                      x.distributionpoint_id,
                      x.product_id,
                      x.sizedefinition_id,
                      sum(case when x.columnnr=1 then 1 else 0 end) column1,
                      sum(case when x.columnnr=2 then 1 else 0 end) column2,
                      sum(case when x.columnnr=3 then 1 else 0 end) column3,
                      sum(case when x.columnnr=4 then 1 else 0 end) column4,
                      sum(case when x.columnnr=5 then 1 else 0 end) column5,
                      sum(case when x.columnnr=6 then 1 else 0 end) column6,
                      sum(case when x.columnnr=7 then 1 else 0 end) column7,
                      sum(case when x.columnnr=8 then 1 else 0 end) column8,
                      sum(case when x.columnnr=9 then 1 else 0 end) column9,
                      count(*) number_of_items,
                      sum(x.days_at_customer) total_days_at_customer,
                      0 qty_used
                 from (select /*+index(uq XIF12UNIQUEITEM)*/
                              rp.reportparam_id,
                              dp.customer_id,
                              dp.department_id,
                              cp.distributionpoint_id,
                              uq.product_id,
                              uq.sizedefinition_id,
                              uq.uniqueitem_id,
                              trunc(uq.lastoutscandate),
                              trunc(sysdate) - trunc(uq.lastoutscandate) days_at_customer,
                              case
                                when floor((trunc(sysdate) - trunc(uq.lastoutscandate)) / rp.number_value3) + 1 > 9
                                  then 9
                                  else floor((trunc(sysdate) - trunc(uq.lastoutscandate)) / rp.number_value3) + 1
                              end columnnr
                         from department        dp,
                              distributionpoint cp,
                              uniqueitem        uq,
                              product           prd,
                              productgroup      pg,
                              reportparam       rp
                        where dp.department_id = cp.department_id
                          and cp.distributionpoint_id = uq.distributionpoint_id
                          and uq.customerowned = 'N'
                          and uq.poolitem = 1
                          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 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 dp.customer_id = rp.number_value
                          and (trunc(sysdate) - trunc(uq.lastoutscandate)) <= rp.number_value4
                          ) x
                group by x.reportparam_id,
                         x.customer_id,
                         x.department_id,
                         x.distributionpoint_id,
                         x.product_id,
                         x.sizedefinition_id
               UNION -- second part of union: select delivery history for average daily usage
               select rp.reportparam_id,
                      dh.customer_link_id customer_id,
                      dh.department_link_id department_id,
                      dh.distributionpoint_link_id distributionpoint_id,
                      dh.product_link_id product_id,
                      dh.sizedefinition_link_id sizedefinition_id,
                      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
                 from deliveryhistory dh,
                      department_link dl,
                      product p,
                      productgroup pg,
                      reportparam rp
                where p.product_id = dh.product_link_id
                  and p.uniquepoolitem = 'Y'
                  and pg.productgroup_id = p.productgroup_id
                  and dl.department_link_id = dh.department_link_id
                  and dh.deliverydate >= rp.date_value1
                  and dh.deliverydate <= rp.date_value2
                  and dh.customer_link_id = rp.number_value
             group by rp.reportparam_id,
                      dh.customer_link_id,
                      dh.department_link_id,
                      dh.distributionpoint_link_id,
                      dh.product_link_id,
                      dh.sizedefinition_link_id) y
       group by y.reportparam_id,
                y.customer_id,
                y.department_id,
                y.distributionpoint_id,
                y.product_id,
                y.sizedefinition_id) q,
      customer cu,
      department d,
      distributionpoint dp,
      sizedefinition s,
      product p, productgroup pg,
      languages
where cu.customer_id = q.customer_id
  and d.department_id = q.department_id
  and dp.distributionpoint_id = q.distributionpoint_id
  and p.product_id = q.product_id
  and pg.productgroup_id = p.productgroup_id
  and s.sizedefinition_id = q.sizedefinition_id

/
create or replace view V_DAILYDEPOSIT
 (REMITBATCH_ID, REMITIDENTIFICATION, ARTRANSACTION_ID, PAYMENTTYPE, TYPENUMBER, ARTRANSACTIONTYPE_ID, BILLTOCUSTOMER_LINK_ID, BUSINESSUNITCODE, BUSINESSUNITDESC, TRANSACTIONREMITDATE, REMITDATE, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, CHECKREF, PAYMENTREF, DELINQUENTMARKAFTER, INVOICEAMOUNTDECIMALS, BATCHNUMBER, ROUTENUMBER)
as select COALESCE(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,
       (select culb.customernumber billtocustomernumber
          from customer_link culb
         where ar.billtocustomer_link_id = culb.customer_link_id) billtocustomernumber,
       (select culb.name billtocustomername
          from customer_link culb
         where ar.billtocustomer_link_id = culb.customer_link_id) billtocustomername,
       ar.remitidentification checkref,
       ar.amount paymentref,
       (select cb.delinquentmarkafter
          from customerbillinginfo cb
         where ar.billtocustomer_link_id = cb.customer_id) delinquentmarkafter,
       (select cr.invoiceamountdecimals
          from currency cr
         where ar.currency_id = cr.currency_id) invoiceamountdecimals
, (SELECT rb.batchnumber FROM remitbatch rb WHERE rb.remitbatch_id = ar.remitbatch_id) batchnumber
, (SELECT ro.routenumber FROM route ro WHERE ro.route_id = ar.route_id) routenumber
from artransaction ar, businessunit bu, artransactiontype art, remitbatch rb
where ar.businessunit_id = bu.businessunit_id and ar.debitcredit = 'C'
      and ar.artransactiontype_id = art.artransactiontype_id
      and rb.remitbatch_id = ar.remitbatch_id

/
create or replace view V_DAILYDEPOSIT_DET
 (REMITBATCH_ID, CLOSINGTRANSACTION_ID, ARTRANSACTION_ID, REMITIDENTIFICATION, BILLTOCUSTOMER_LINK_ID, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEDATE, INVOICENUMBER, INVOICEAMOUNT, APPLIEDAMOUNT, DISCOUNTAMOUNT)
as select COALESCE(ar.remitbatch_id, -1) remitbatch_id,--ar.remitbatch_id,
       ca.creditartransaction_id closingtransaction_id,
       ar.artransaction_id,
       COALESCE(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,
      -- (select sum(ca2.amount) from cashapplication ca2 where ar.artransaction_id = ca2.debitartransaction_id and ca2.unapplied_yn = 'N' ) appliedamount,
       (select sum(ca1.amount)
          from artransaction ar1, artransactiontype art1, cashapplication ca1
         where ar1.invoicenumber = ar.invoicenumber and
               ar1.businessunit_id = ar.businessunit_id and
               ar1.billtocustomer_link_id = ar.billtocustomer_link_id and
               ar1.artransactiontype_id = art1.artransactiontype_id and
               art1.typenumber = 4 and
               ar1.artransaction_id = ca1.creditartransaction_id and ca1.unapplied_yn = 'N') discountamount
  from artransaction ar, cashapplication ca
 where ar.debitcredit = 'D' and --ar.closingtransaction_id is not null
       ar.artransaction_id = ca.debitartransaction_id and ca.unapplied_yn = 'N'
--group by COALESCE(ar.remitbatch_id, -1), ca.creditartransaction_id, ar.artransaction_id, COALESCE(ar.remitidentification, ''), ar.billtocustomer_link_id,
      --ar.deltocustomer_link_id, ar.artransactiondate, ar.invoicenumber, ar.businessunit_id, ar.amount

/
create or replace view V_DAILYUSAGEDECREASES_LLG
 (CUSTOMERNUMBER, CUSTOMERNAME, BUCODE, BUDESCRIPTION, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, PRODUCT_ID, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDEFINITION_ID, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHOD_ID, FINISHINGMETHODCODE, FINISHINGMETHODDESCRIPTION, PACKINGNOTENUMBER, PROCESSBUSINESSUNIT_ID, DELIVERYDATE, ORIGIN, AMOUNT, FIXEDAMOUNT, REFERENCE, PROCESSED, CAUSENOTENUMBER, CAUSENOTEDELIVERYDATE, SYSTEMUSER_ID
, TIMESTAMP, LANGUAGECODE, SOILCOUNTSUBTYPE, REASONCODE_ID, RC_CODE, RC_DESCRIPTION, ADJ_RC_CODE, ADJ_RC_DESCRIPTION)
as SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME,
  (select bu.code from businessunit bu where bu.businessunit_id = CUSTOMER.DEFAULTBUSINESSUNIT_ID) bucode,
  (select bu.description from businessunit bu where bu.businessunit_id = CUSTOMER.DEFAULTBUSINESSUNIT_ID) budescription,
  DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
  DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
  PRODUCT.PRODUCT_ID,
  PRODUCT.CODE PRODUCTCODE,
  (SELECT DESCRIPTION FROM PRODUCT_DESC P WHERE P.PRODUCT_ID = DELIVERYVARIATIONS.PRODUCT_ID
     AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  PRODUCTDESCRIPTION,
  DELIVERYVARIATIONS.SIZEDEFINITION_ID,
  (select SIZEDEFINITION.CODE from sizedefinition where sizedefinition.sizedefinition_id = deliveryvariations.sizedefinition_id) sizecode,
  (SELECT DESCRIPTION FROM SIZEDEFINITION_DESC S WHERE S.SIZEDEFINITION_ID = DELIVERYVARIATIONS.SIZEDEFINITION_ID
     AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  SIZEDESCRIPTION,
  FINISHINGMETHOD.FINISHINGMETHOD_ID,
  FINISHINGMETHOD.CODE FINISHINGMETHODCODE,
  (SELECT DESCRIPTION FROM FINISHINGMETHOD_DESC F WHERE F.FINISHINGMETHOD_ID = DELIVERYVARIATIONS.FINISHINGMETHOD_ID
     AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  FINISHINGMETHODDESCRIPTION,
  PACKINGNOTE.NOTENUMBER PACKINGNOTENUMBER, PACKINGNOTE.PROCESSBUSINESSUNIT_ID,
  DELIVERYVARIATIONS.DELIVERYDATE, DELIVERYVARIATIONS.ORIGIN,
  DELIVERYVARIATIONS.AMOUNT,
  DELIVERYVARIATIONS.FIXEDAMOUNT, DELIVERYVARIATIONS.REFERENCE, DELIVERYVARIATIONS.PROCESSED,
  CAUSENOTE.NOTENUMBER CAUSENOTENUMBER, CAUSENOTE.DELIVERYDATE CAUSENOTEDELIVERYDATE,
  DELIVERYVARIATIONS.SYSTEMUSER_ID, GETDATEONLY(DELIVERYVARIATIONS.TIMESTAMP) TIMESTAMP, LANGUAGES.CODE LANGUAGECODE,
  DELIVERYVARIATIONS.SOILCOUNTSUBTYPE,
  DELIVERYVARIATIONS.REASONCODE_ID,
  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 = LANGUAGES.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 = LANGUAGES.LANGUAGE_ID) ADJ_RC_DESCRIPTION
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT,
  PRODUCT, FINISHINGMETHOD, LANGUAGES,
  DELIVERYVARIATIONS
    LEFT OUTER JOIN PACKINGNOTE ON (DELIVERYVARIATIONS.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID)
    LEFT OUTER JOIN PACKINGNOTE CAUSENOTE ON (DELIVERYVARIATIONS.CAUSENOTE_ID = CAUSENOTE.PACKINGNOTE_ID)
    LEFT OUTER JOIN REASONCODE RC ON (DELIVERYVARIATIONS.REASONCODE_ID = RC.REASONCODE_ID)
    LEFT OUTER JOIN REASONCODE ADJ_RC ON (DELIVERYVARIATIONS.ADJUSTMENTREASON_ID = ADJ_RC.REASONCODE_ID)
WHERE DELIVERYVARIATIONS.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
  AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
  AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND DELIVERYVARIATIONS.PRODUCT_ID = PRODUCT.PRODUCT_ID
  AND DELIVERYVARIATIONS.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
  AND DEPARTMENT.ACTIVE = 'Y'
  AND DELIVERYVARIATIONS.ORIGIN = 3
  AND DELIVERYVARIATIONS.AMOUNT < 0

/
create or replace view V_DAILYUSAGEINCREASES_LLG
 (CUSTOMERNUMBER, CUSTOMERNAME, BUCODE, BUDESCRIPTION, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, PRODUCT_ID, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDEFINITION_ID, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHOD_ID, FINISHINGMETHODCODE, FINISHINGMETHODDESCRIPTION, PACKINGNOTENUMBER, PROCESSBUSINESSUNIT_ID, DELIVERYDATE, ORIGIN, AMOUNT, FIXEDAMOUNT, REFERENCE, PROCESSED, CAUSENOTENUMBER, CAUSENOTEDELIVERYDATE, SYSTEMUSER_ID
, TIMESTAMP, LANGUAGECODE, SOILCOUNTSUBTYPE, REASONCODE_ID, RC_CODE, RC_DESCRIPTION, ADJ_RC_CODE, ADJ_RC_DESCRIPTION)
as SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME,
  (select bu.code from businessunit bu where bu.businessunit_id = CUSTOMER.DEFAULTBUSINESSUNIT_ID) bucode,
  (select bu.description from businessunit bu where bu.businessunit_id = CUSTOMER.DEFAULTBUSINESSUNIT_ID) budescription,
  DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
  DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
  PRODUCT.PRODUCT_ID,
  PRODUCT.CODE PRODUCTCODE,
  (SELECT DESCRIPTION FROM PRODUCT_DESC P WHERE P.PRODUCT_ID = DELIVERYVARIATIONS.PRODUCT_ID
     AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  PRODUCTDESCRIPTION,
  DELIVERYVARIATIONS.SIZEDEFINITION_ID,
  (select SIZEDEFINITION.CODE from sizedefinition where sizedefinition.sizedefinition_id = deliveryvariations.sizedefinition_id) sizecode,
  (SELECT DESCRIPTION FROM SIZEDEFINITION_DESC S WHERE S.SIZEDEFINITION_ID = DELIVERYVARIATIONS.SIZEDEFINITION_ID
     AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  SIZEDESCRIPTION,
  FINISHINGMETHOD.FINISHINGMETHOD_ID,
  FINISHINGMETHOD.CODE FINISHINGMETHODCODE,
  (SELECT DESCRIPTION FROM FINISHINGMETHOD_DESC F WHERE F.FINISHINGMETHOD_ID = DELIVERYVARIATIONS.FINISHINGMETHOD_ID
     AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  FINISHINGMETHODDESCRIPTION,
  PACKINGNOTE.NOTENUMBER PACKINGNOTENUMBER, PACKINGNOTE.PROCESSBUSINESSUNIT_ID,
  DELIVERYVARIATIONS.DELIVERYDATE, DELIVERYVARIATIONS.ORIGIN,
  DELIVERYVARIATIONS.AMOUNT,
  DELIVERYVARIATIONS.FIXEDAMOUNT, DELIVERYVARIATIONS.REFERENCE, DELIVERYVARIATIONS.PROCESSED,
  CAUSENOTE.NOTENUMBER CAUSENOTENUMBER, CAUSENOTE.DELIVERYDATE CAUSENOTEDELIVERYDATE,
  DELIVERYVARIATIONS.SYSTEMUSER_ID, GETDATEONLY(DELIVERYVARIATIONS.TIMESTAMP) TIMESTAMP, LANGUAGES.CODE LANGUAGECODE,
  DELIVERYVARIATIONS.SOILCOUNTSUBTYPE,
  DELIVERYVARIATIONS.REASONCODE_ID,
  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 = LANGUAGES.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 = LANGUAGES.LANGUAGE_ID) ADJ_RC_DESCRIPTION
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT,
  PRODUCT, FINISHINGMETHOD, LANGUAGES,
  DELIVERYVARIATIONS
    LEFT OUTER JOIN PACKINGNOTE ON (DELIVERYVARIATIONS.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID)
    LEFT OUTER JOIN PACKINGNOTE CAUSENOTE ON (DELIVERYVARIATIONS.CAUSENOTE_ID = CAUSENOTE.PACKINGNOTE_ID)
    LEFT OUTER JOIN REASONCODE RC ON (DELIVERYVARIATIONS.REASONCODE_ID = RC.REASONCODE_ID)
    LEFT OUTER JOIN REASONCODE ADJ_RC ON (DELIVERYVARIATIONS.ADJUSTMENTREASON_ID = ADJ_RC.REASONCODE_ID)
WHERE DELIVERYVARIATIONS.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
  AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
  AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND DELIVERYVARIATIONS.PRODUCT_ID = PRODUCT.PRODUCT_ID
  AND DELIVERYVARIATIONS.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
  AND DEPARTMENT.ACTIVE = 'Y'
  AND DELIVERYVARIATIONS.ORIGIN = 3
  AND DELIVERYVARIATIONS.AMOUNT > 0

/
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_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
, GETCURRENTDATE() 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_DELIVEREDCONTAINERS_CIW
 (LINETYPE, CUSTOMERNUMBER, NAME, DEPARTMENTNUMBER, DEP_NAME, DISTRIBUTIONPOINTNUMBER, DISTRIBPOINT_DESC, DEFAULTBU_ID, PROCBU_ID, CONTAINERTYPE_CODE, CONTAINERTYPE_ACTIVE, CONTAINERTYPE_DESC, CONTAINERTYPE_DESC_TY, CONTAINER_ID, CONT_IN, CONT_OUT, AT_CUSTOMER, DELIVERYDATE, LANGUAGE_CODE, DEPOTCODE, DEPOTDESCRIPTION)
as select 1 linetype --outscan on deliverynote
, c.customernumber, c.name, dep.departmentnumber, dep.description Dep_name
, dp.distributionpointnumber, dp.description DistribPoint_desc
, bu.businessunit_id DefaultBU_id, proc_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
, (select ctd.description from containertype_desc ctd where ctd.language_id = lan.language_id and ctd.containertype_id = (select ct.containertype_id from containertype ct where ct.code = 'TY')) ContainerType_desc_TY
, co.container_id
, 0 cont_in, 1 cont_out, 0 at_customer
, pn.deliverydate deliverydate
, lan.code Language_code
, (select d.code
   from depot d
   where d.depot_id = (select r.depot_id from route r where r.route_id = pn.route_id)) depotcode
, (select d.description
   from depot d
   where d.depot_id = (select r.depot_id from route r where r.route_id = pn.route_id)) depotdescription
from customer c, department dep, distributionpoint dp, container co
, containertype ct
, businessunit bu, businessunit proc_bu
, languages lan
, packingnotecontainer pnc
, packingnote pn
where dp.department_id=dep.department_id
and dep.customer_id=c.customer_id
and co.containertype_id = ct.containertype_id
and (c.defaultbusinessunit_id = bu.businessunit_id or
    exists (select 1 from customeractivities ca where
        ca.processbusinessunit_id = proc_bu.businessunit_id
        and ca.customer_id = c.customer_id))
and co.businessunit_id = bu.businessunit_id
and pnc.container_id = co.container_id
and pnc.packingnote_id = pn.packingnote_id
and pn.distributionpoint_id = dp.distributionpoint_id
and pn.status_id = (select s.status_id from status s where s.statustype = 'PN' and s.code = 30)
union all
select 2 linetype --outscan on weighing ticket
, c.customernumber, c.name, dep.departmentnumber, dep.description Dep_name
, dp.distributionpointnumber, dp.description DistribPoint_desc
, bu.businessunit_id DefaultBU_id, proc_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
, (select ctd.description from containertype_desc ctd where ctd.language_id = lan.language_id and ctd.containertype_id = (select ct.containertype_id from containertype ct where ct.code = 'TY')) ContainerType_desc_TY
, co.container_id
, 0 cont_in, 1 cont_out, 0 at_customer
, wt.deliverydate deliverydate
, lan.code Language_code
, (select d.code
   from depot d
   where d.depot_id = (select max(nvl(r.depot_id, 0))
                     from routestop rs, route r
                     where r.route_id = rs.route_id
                     and rs.customer_id = c.customer_id
                     and ((rs.deliverypoint_id is null) or (rs.deliverypoint_id = dp.deliverypoint_id))
                     )) depotcode
, (select d.description
   from depot d
   where d.depot_id = (select max(nvl(r.depot_id, 0))
                     from routestop rs, route r
                     where r.route_id = rs.route_id
                     and rs.customer_id = c.customer_id
                     and ((rs.deliverypoint_id is null) or (rs.deliverypoint_id = dp.deliverypoint_id))
                     )) depotdescription
from customer c, department dep, distributionpoint dp, container co
, containertype ct
, businessunit bu, businessunit proc_bu
, languages lan
, weighingticket wt
, weighingticketline wtl
where dp.department_id=dep.department_id
and dep.customer_id=c.customer_id
and co.containertype_id = ct.containertype_id
and (c.defaultbusinessunit_id = bu.businessunit_id or
    exists (select 1 from customeractivities ca where
        ca.processbusinessunit_id = proc_bu.businessunit_id
        and ca.customer_id = c.customer_id))
and co.businessunit_id = bu.businessunit_id
and wtl.container_id = co.container_id
and wtl.weighingticket_id = wt.weighingticket_id
and wt.customer_id = c.customer_id

/
create or replace view V_DELIVEREDLOANS_LLG
 (CUSTOMERNUMBER, SEARCHNAME, NAME, NOTENUMBER, DISTRIBUTIONPOINT_ID, PN_DELIVERYDATE, DV_DELIVERYDATE, DELIVERYVARIATIONS_ID, ORIGIN, PRODUCTCODE, PRODUCTDESCRIPTION, SIZECODE, SOILQTY, DV_LOANAMOUNT, PNL_DELIVEREDAMOUNT, LOANQTY, LANGUAGECODE, CODE, BU_DESCRIPTION)
as select c.customernumber,
       c.searchname,
       c.name,
       pn.notenumber,
       dp.distributionpoint_id,
       pn.deliverydate pn_deliverydate,
       dv.deliverydate dv_deliverydate,
       dv.deliveryvariations_id,
       dv.origin,
       (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) productdescription,
       (select sd.code from sizedefinition sd where sd.sizedefinition_id = dv.sizedefinition_id) sizecode,
       0 soilqty,
       dv.amount dv_loanamount,
       /*nvl((select pnl.deliveredamount
               from packingnoteline pnl where pnl.packingnote_id = pn.packingnote_id
               and pnl.product_id = dv.product_id
               and pnl.sizedefinition_id = dv.sizedefinition_id
               and pnl.finishingmethod_id = dv.finishingmethod_id), 0)*/0 pnl_deliveredamount,
        nvl((select sum(rqa.quantity) from rentalqtyadjustment rqa, productlistperdistribpoint plpd
                    where rqa.origin = 2 and rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
                    and plpd.product_id = dv.product_id
                    and plpd.sizedefinition_id = dv.sizedefinition_id
                    and plpd.finishingmethod_id = dv.finishingmethod_id
                    and plpd.distributionpoint_id = dp.distributionpoint_id
                    and rqa.adjustmentdate <= sysdate),0) loanqty,
        l.code languagecode,
        bu.code,
        bu.description bu_description
  from deliveryvariations dv,
       packingnote        pn,
       customer c,
       department d,
       distributionpoint dp,
       languages l,
       businessunit bu,
       status s
 where dv.packingnote_id = pn.packingnote_id
   and bu.businessunit_id = pn.processbusinessunit_id
   and pn.distributionpoint_id = dp.distributionpoint_id
   and dp.department_id = d.department_id
   and d.customer_id = c.customer_id
   and dv.updaterentqty = 'Y'
   and dv.enddate is not null
   and dv.adjustmentreason_id is not null
   and dv.origin = 3
/*   and pn.status_id = s.status_id
   and s.statustype = 'PN' and s.code = 30*/
union
select c.customernumber,
       c.searchname,
       c.name,
       pn.notenumber,
       dp.distributionpoint_id,
       pn.deliverydate pn_deliverydate,
       dv.deliverydate dv_deliverydate,
       dv.deliveryvariations_id,
       dv.origin,
       (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) productdescription,
       (select sd.code from sizedefinition sd where sd.sizedefinition_id = dv.sizedefinition_id) sizecode,
       dv.amount soilqty,
       0 dv_loanamount,
       nvl((select pnl.deliveredamount
               from packingnoteline pnl where pnl.packingnote_id = pn.packingnote_id
               and pnl.product_id = dv.product_id
               and pnl.sizedefinition_id = dv.sizedefinition_id
               and pnl.finishingmethod_id = dv.finishingmethod_id), 0) pnl_deliveredamount,
        0 loanqty,
        l.code languagecode,
        bu.code,
        bu.description bu_description
  from deliveryvariations dv,
       packingnote        pn,
       customer c,
       department d,
       distributionpoint dp,
       languages l,
       businessunit bu
 where dv.packingnote_id = pn.packingnote_id
   and bu.businessunit_id = pn.processbusinessunit_id
   and pn.distributionpoint_id = dp.distributionpoint_id
   and dp.department_id = d.department_id
   and d.customer_id = c.customer_id
   and dv.origin = 1

/
create or replace view V_DELIVEREDPRODUCTS
 (REPORTPARAM_ID, PROCESSBU_ID, CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PRODUCTCODE, PRODUCTDESCRIPTION, PARENTPRODUCTCODE, PARENTPRODUCTDESCRIPTION, PACKINDICATION, PACKCODE, PACKDESCRIPTION, ACTIVITYCODE, THEORETICALWEIGHT, TYPEOFMERCHANDISE, MODEL, PRODSIZE_THEORETICALWEIGHT, THEORETICALWEIGHT_PLPC, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODCODE
, FINISHINGMETHODDESCRIPTION, 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, PRICE, VATRATE, DECIMALS, INVOICEAMOUNTDECIMALS, TAXABLE, DEFAULTBUSINESSUNIT_ID, CUSTOMERLANGUAGECODE, LANGUAGECODE, PRICEWITHDISCOUNT, DISCOUNTPERCENTAGE
, Q, W, E, R, T, Y, U, PLANT_CODE, PLANT_NAME, WIDTH_S, LENGTH_S)
as SELECT RP.REPORTPARAM_ID, PROCESSBU.BUSINESSUNIT_ID PROCESSBU_ID,
       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,
       PRODUCT_LINK.CODE productcode,
       (SELECT B.DESCRIPTION FROM PRODUCT_DESC B WHERE B.PRODUCT_ID = DELIVERYHISTORY.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 = DELIVERYHISTORY.PARENTPRODUCT_LINK_ID AND E.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) parentproductdescription,
       DELIVERYHISTORY.PACKINDICATION,
       pack.CODE packcode,
       (SELECT F.DESCRIPTION FROM PRODUCT_LINK_DESC F WHERE F.PRODUCT_LINK_ID = DELIVERYHISTORY.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,
       PRODUCT.THEORETICALWEIGHT, PRODUCT.typeofmerchandise, PRODUCT.MODEL,
       PRODUCTSIZE.THEORETICALWEIGHT PRODSIZE_THEORETICALWEIGHT,
       (select plpc.soilweight from productlistpercustomer plpc where PLPC.CUSTOMER_ID=CUSTOMER_LINK.CUSTOMER_LINK_ID AND plpc.product_id=product_link.product_link_id
       and plpc.sizedefinition_id=SIZEDEFINITION_LINK.Sizedefinition_Id and plpc.finishingmethod_id=FINISHINGMETHOD.Finishingmethod_Id
       AND PLPC.DATEINACTIVE >=SYSDATE
       ) theoreticalweight_plpc,
       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,
       FINISHINGMETHOD.CODE finishingmethodcode,
       (SELECT D.DESCRIPTION FROM FINISHINGMETHOD_DESC D WHERE D.FINISHINGMETHOD_ID = DELIVERYHISTORY.FINISHINGMETHOD_ID AND D.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODdescription,
       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.PARENTPACKPRODUCT_LINK_ID, DELIVERYHISTORY.PARENTPRODUCT_LINK_ID,
       PROCESSBU.CODE processbucode, PROCESSBU.DESCRIPTION processbudescription, INVOICEBU.CODE invoicebucode,
       INVOICEBU.DESCRIPTION invoicebudescription, DELIVERYHISTORY.SYSTEMUSER_ID, DELIVERYHISTORY.TIMESTAMP,
       F_GETDELPRODPRICE(rp.number_value, cu.customer_id, product.product_id, SIZEDEFINITION_LINK.SIZEDEFINITION_ID,
         FINISHINGMETHOD.FINISHINGMETHOD_ID, rp.date_value1/*deliveryhistory.deliverydate*/,product.typeofmerchandise) price,
       F_GETVAT(rp.number_value, (CASE WHEN cu.taxable = 'Y' then cu.customer_id ELSE null END)
       , product.product_id, /*rp.number_value1*/ (CASE WHEN rp.number_value1 = -1 then cu.country_id ELSE rp.number_value1  END), cu.country_id, rp.date_value1/*deliveryhistory.deliverydate*/) vatrate,
       cur.decimals, cur.invoiceamountdecimals,
       cu.taxable, bu.businessunit_id defaultbusinessunit_id,
       CUSTOMER_LINK.LANGUAGECODE CUSTOMERLANGUAGECODE, LANGUAGES.CODE LANGUAGECODE,
       F_GETDELPRODPRICEWITHDISC(cu.customer_id, product.product_id, SIZEDEFINITION_LINK.SIZEDEFINITION_ID,
         FINISHINGMETHOD.FINISHINGMETHOD_ID, deliveryhistory.deliverydate, product.typeofmerchandise) PRICEWITHDISCOUNT,
       pack_price.Wash_Discount(cu.customer_id, product.product_id, SIZEDEFINITION_LINK.SIZEDEFINITION_ID,
         FINISHINGMETHOD.FINISHINGMETHOD_ID,deliveryhistory.deliverydate) DISCOUNTPERCENTAGE
         , rp.number_value q , cu.customer_id  w, product.product_id e, SIZEDEFINITION_LINK.SIZEDEFINITION_ID r,
         FINISHINGMETHOD.FINISHINGMETHOD_ID t, deliveryhistory.deliverydate y ,product.typeofmerchandise u
, pl.code Plant_Code, pl.name Plant_Name,
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),
      PRODUCTSIZE,
      CUSTOMER_LINK
        left outer join customer cu          --left join country ctr on cu.country_id = ctr.country_id)
        on cu.customer_id = CUSTOMER_LINK.CUSTOMER_ID,
      DEPARTMENT_LINK, DISTRIBUTIONPOINT_LINK,
      SIZEDEFINITION_LINK,
      BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU, FINISHINGMETHOD, LANGUAGES,
      PRODUCT_LINK parentproduct, PRODUCT_LINK pack,
      PRODUCT_LINK
        LEFT OUTER JOIN PRODUCTGROUP ON (PRODUCT_LINK.PRODUCTGROUPCODE = PRODUCTGROUP.CODE),
      REPORTPARAM RP, currency cur, Businessunit BU, plant pl
 WHERE 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_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.PARENTPACKPRODUCT_LINK_ID = pack.PRODUCT_LINK_ID
  AND DELIVERYHISTORY.SIZEDEFINITION_LINK_ID = SIZEDEFINITION_LINK.SIZEDEFINITION_LINK_ID
  AND DELIVERYHISTORY.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND DELIVERYHISTORY.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  AND FINISHINGMETHOD.FINISHINGMETHOD_ID = DELIVERYHISTORY.FINISHINGMETHOD_ID
  AND PRODUCT.PRODUCT_ID = PRODUCTSIZE.PRODUCT_ID
  AND SIZEDEFINITION.SIZEDEFINITION_ID = PRODUCTSIZE.SIZEDEFINITION_ID
  and DELIVERYHISTORY.Currency_Id = cur.currency_id
  and (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 bu.plant_id = pl.plant_id

/
create or replace view V_DELIVEREDPRODUCTSPERCC_SMG
 (LINETYPE, COSTCENTER_CODE, COSTCENTER_DESC, NOTENUMBER, DELIVERYDATE, PRODUCTCODE, CUSTOMERNUMBER, DELIVEREDAMOUNT, PRODUCTGROUPCODE, PRODUCTDESC, CHAINCODE, REGUNIT, WEIGHTCATEGCODE, WEIGHTCATEGDESC, SPECIALQUANTITY, SPECIALLENGTH, SPECIALWIDTH, WEIGHT)
as select 1 linetype, cc.code costcenter_code, cc.description costcenter_desc,
       pn.notenumber,
       pn.deliverydate,
       p.code productcode,
       c.customernumber,
       pnl.deliveredamount,
       (select pg.code from productgroup pg where pg.productgroup_id = p.productgroup_id) productgroupcode,
       (select pdesc.description from product_desc pdesc where pdesc.product_id = p.product_id and pdesc.language_id = c.language_id) productdesc,
       (select ch.code from chain ch where ch.chain_id = c.chain_id) chaincode,
       (select ru.code from registrationunit ru where ru.registrationunit_id = p.registrationunit_id) regunit,
       null weightcategcode,
       null weightcategdesc,
       0 specialquantity, 0 speciallength, 0 specialwidth,
       0 weight
from packingnote pn
     left outer join (packingnoteline pnl join product p on pnl.product_id = p.product_id )
          on pn.packingnote_id = pnl.packingnote_id
     /*left outer join (packingnotecontainer pnc join weighingcategory w on pnc.weighingcategory_id = w.weighingcategory_id)
          on pn.packingnote_id = pnc.packingnote_id*/
     join distributionpoint dp on pn.distributionpoint_id = dp.distributionpoint_id
     join costcenter cc on cc.costcenter_id = dp.costcenter_id
     join customer c on c.customer_id = cc.customer_id
where pn.status_id = (select s.status_id from status s where s.statustype = 'PN' and s.code = '30')
union all
select 2 linetype, cc.code costcenter_code, cc.description costcenter_desc,
       pn.notenumber,
       pn.deliverydate,
       null productcode,
       c.customernumber,
       0 deliveredamount,
       null productgroupcode,
       null productdesc,
       (select ch.code from chain ch where ch.chain_id = c.chain_id) chaincode,
       (select ru.code from registrationunit ru where ru.registrationunit_id = w.registrationunit_id) regunit,
       w.code weightcategcode,
       (select wd.description from weighingcategory_desc wd where pnc.weighingcategory_id = wd.weighingcategory_id and wd.language_id = c.language_id) weightcategdesc,
       pnc.specialquantity, pnc.speciallength, pnc.specialwidth,
       (pnc.grossweight - pnc.soilportion) weight
from packingnote pn
     /*left outer join (packingnoteline pnl join product p on pnl.product_id = p.product_id )
          on pn.packingnote_id = pnl.packingnote_id*/
     left outer join (packingnotecontainer pnc join weighingcategory w on pnc.weighingcategory_id = w.weighingcategory_id)
          on pn.packingnote_id = pnc.packingnote_id
     join distributionpoint dp on pn.distributionpoint_id = dp.distributionpoint_id
     join costcenter cc on cc.costcenter_id = dp.costcenter_id
     join customer c on c.customer_id = cc.customer_id
where pn.status_id = (select s.status_id from status s where s.statustype = 'PN' and s.code = '30')
union all
select 3 linetype, cc.code costcenter_code, cc.description costcenter_desc,
       wo.workordernumber notenumber,
       wo.completiondate deliverydate,
       p.code productcode,
       c.customernumber,
       wol.quantityordered deliveredamount,
       (select pg.code from productgroup pg where pg.productgroup_id = p.productgroup_id) productgroupcode,
       (select pdesc.description from product_desc pdesc where pdesc.product_id = p.product_id and pdesc.language_id = c.language_id) productdesc,
       (select ch.code from chain ch where ch.chain_id = c.chain_id) chaincode,
       (select ru.code from registrationunit ru where ru.registrationunit_id = p.registrationunit_id) regunit,
       null weightcategcode,
       null weightcategdesc,
       0 specialquantity, 0 speciallength, 0 specialwidth,
       0 weight
from workorder wo
     join (workorderline wol join product p on wol.product_link_id = p.product_id )
          on wo.workorder_id = wol.workorder_id
     join distributionpoint dp on wo.distributionpoint_link_id = dp.distributionpoint_id
     join costcenter cc on cc.costcenter_id = dp.costcenter_id
     join customer c on c.customer_id = cc.customer_id
where wo.status_id = (select s.status_id from status s where s.statustype='WO' and s.code='30')
      and wo.origin = 6

/
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_DELIVEREDPRODUCTS_BCH
 (REPORTPARAM_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, INTERNALPRICE, DISCOUNT, STANDARDORDER, PARENTPACKPRODUCT_LINK_ID, PARENTPRODUCT_LINK_ID, PROCESSBUCODE, PROCESSBUDESCRIPTION, INVOICEBUCODE, INVOICEBUDESCRIPTION, SYSTEMUSER_ID, TIMESTAMP, PRICE, VATRATE, DECIMALS, INVOICEAMOUNTDECIMALS, TAXABLE, DEFAULTBUSINESSUNIT_ID, CUSTOMERLANGUAGECODE, LANGUAGECODE, PRICEWITHDISCOUNT, DISCOUNTPERCENTAGE
, Q, W, E, R, T, Y, U, PLANT_CODE, PLANT_NAME)
as SELECT RP.REPORTPARAM_ID,
       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,
       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,
       parentproduct.CODE parentproductcode,
       (SELECT E.DESCRIPTION FROM PRODUCT_LINK_DESC E WHERE E.PRODUCT_LINK_ID = DELIVERYHISTORY.PARENTPRODUCT_LINK_ID AND E.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) parentproductdescription,
       DELIVERYHISTORY.PACKINDICATION,
       pack.CODE packcode,
       (SELECT F.DESCRIPTION FROM PRODUCT_LINK_DESC F WHERE F.PRODUCT_LINK_ID = DELIVERYHISTORY.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,
       PRODUCT.THEORETICALWEIGHT, PRODUCT.typeofmerchandise, PRODUCT.MODEL,
       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,
       FINISHINGMETHOD.CODE finishingmethodcode,
       (SELECT D.DESCRIPTION FROM FINISHINGMETHOD_DESC D WHERE D.FINISHINGMETHOD_ID = DELIVERYHISTORY.FINISHINGMETHOD_ID AND D.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODdescription,
       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,
       (select sum(sda.amount)
        from standarddeliveryline sdl, productlistperdistribpoint plpd,standarddeliveryamount sda, day d
        where sdl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
              and sda.standarddeliveryline_id = sdl.standarddeliveryline_id
              and plpd.product_id = DELIVERYHISTORY.parentpackproduct_link_id
              and plpd.sizedefinition_id = DELIVERYHISTORY.Sizedefinition_Link_Id
              and plpd.finishingmethod_id = DELIVERYHISTORY.Finishingmethod_Id
              and plpd.distributionpoint_id = DELIVERYHISTORY.Distributionpoint_Link_Id
              and DELIVERYHISTORY.Deliverydate between sdl.dateactive and sdl.dateinactive
              and sda.day_id = d.day_id
              and d.daynumber = DELIVERYHISTORY.DAYNUMBER
         group by DELIVERYHISTORY.Distributionpoint_Link_Id) standardorder,
       --deliveryhistory.amountstandard standardorder,
       DELIVERYHISTORY.PARENTPACKPRODUCT_LINK_ID, DELIVERYHISTORY.PARENTPRODUCT_LINK_ID,
       PROCESSBU.CODE processbucode, PROCESSBU.DESCRIPTION processbudescription, INVOICEBU.CODE invoicebucode,
       INVOICEBU.DESCRIPTION invoicebudescription, DELIVERYHISTORY.SYSTEMUSER_ID, DELIVERYHISTORY.TIMESTAMP,
       F_GETDELPRODPRICE(rp.number_value, cu.customer_id, product.product_id, SIZEDEFINITION_LINK.SIZEDEFINITION_ID,
         FINISHINGMETHOD.FINISHINGMETHOD_ID, rp.date_value1/*deliveryhistory.deliverydate*/,product.typeofmerchandise) price,
       F_GETVAT(rp.number_value, (CASE WHEN cu.taxable = 'Y' then cu.customer_id ELSE null END)
       , product.product_id, /*rp.number_value1*/ (CASE WHEN rp.number_value1 = -1 then cu.country_id ELSE rp.number_value1  END), cu.country_id, rp.date_value1/*deliveryhistory.deliverydate*/) vatrate,
       cur.decimals, cur.invoiceamountdecimals,
       cu.taxable, bu.businessunit_id defaultbusinessunit_id,
       CUSTOMER_LINK.LANGUAGECODE CUSTOMERLANGUAGECODE, LANGUAGES.CODE LANGUAGECODE,
       F_GETDELPRODPRICEWITHDISC(cu.customer_id, product.product_id, SIZEDEFINITION_LINK.SIZEDEFINITION_ID,
         FINISHINGMETHOD.FINISHINGMETHOD_ID, deliveryhistory.deliverydate, product.typeofmerchandise) PRICEWITHDISCOUNT,
       F_DiscountWash(cu.customer_id, product.product_id, SIZEDEFINITION_LINK.SIZEDEFINITION_ID,
         FINISHINGMETHOD.FINISHINGMETHOD_ID,deliveryhistory.deliverydate) DISCOUNTPERCENTAGE
         , rp.number_value q , cu.customer_id  w, product.product_id e, SIZEDEFINITION_LINK.SIZEDEFINITION_ID r,
         FINISHINGMETHOD.FINISHINGMETHOD_ID t, deliveryhistory.deliverydate y ,product.typeofmerchandise u
, pl.code Plant_Code, pl.name Plant_Name
 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,
      CUSTOMER_LINK
        left outer join customer cu          --left join country ctr on cu.country_id = ctr.country_id)
        on cu.customer_id = CUSTOMER_LINK.CUSTOMER_ID,
      DEPARTMENT_LINK, DISTRIBUTIONPOINT_LINK,
      SIZEDEFINITION_LINK,
      BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU, FINISHINGMETHOD, LANGUAGES,
      PRODUCT_LINK parentproduct, PRODUCT_LINK pack,
      PRODUCT_LINK
        LEFT OUTER JOIN PRODUCTGROUP ON (PRODUCT_LINK.PRODUCTGROUPCODE = PRODUCTGROUP.CODE),
      REPORTPARAM RP, currency cur, Businessunit BU, plant pl
 WHERE 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_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.PARENTPACKPRODUCT_LINK_ID = pack.PRODUCT_LINK_ID
  AND DELIVERYHISTORY.SIZEDEFINITION_LINK_ID = SIZEDEFINITION_LINK.SIZEDEFINITION_LINK_ID
  AND DELIVERYHISTORY.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
	AND DELIVERYHISTORY.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  AND FINISHINGMETHOD.FINISHINGMETHOD_ID = DELIVERYHISTORY.FINISHINGMETHOD_ID
  AND PRODUCT.PRODUCT_ID = PRODUCTSIZE.PRODUCT_ID
  AND SIZEDEFINITION.SIZEDEFINITION_ID = PRODUCTSIZE.SIZEDEFINITION_ID
  and DELIVERYHISTORY.Currency_Id = cur.currency_id
  and (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 bu.plant_id = pl.plant_id

/
create or replace view V_DELIVEREDPRODUCTS_ECL
 (LINETYPE, REPORTPARAM_ID, CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT_ID, 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, INTERNALPRICE, DISCOUNT, PARENTPACKPRODUCT_LINK_ID, PARENTPRODUCT_LINK_ID, PROCESSBUCODE, PROCESSBUDESCRIPTION, INVOICEBUCODE, INVOICEBUDESCRIPTION, SYSTEMUSER_ID, TIMESTAMP, PRICE, VATRATE, DECIMALS, INVOICEAMOUNTDECIMALS, TAXABLE, DEFAULTBUSINESSUNIT_ID, CUSTOMERLANGUAGECODE, LANGUAGECODE, PRICEWITHDISCOUNT, DISCOUNTPERCENTAGE
, Q, W, E, R, T, Y, U, PLANT_CODE, PLANT_NAME, QTYREJECT, QTYSHORTAGE)
as select /*+index(DELIVERYHISTORY XIE10DELIVERYHISTORY)*/
 1 linetype, rp.reportparam_id, customer_link.customernumber, customer_link.name customername,
 department_link.departmentnumber, department_link.description departmentdescription,
 distributionpoint_link.distributionpointnumber, distributionpoint_link.distributionpoint_id distributionpoint_id,
 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, product.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,
 parentproduct.code parentproductcode,
 (select e.description
   from   product_link_desc e
   where  e.product_link_id = deliveryhistory.parentproduct_link_id
   and    e.language_id = languages.language_id) parentproductdescription,
 deliveryhistory.packindication, pack.code packcode,
 (select f.description
   from   product_link_desc f
   where  f.product_link_id = deliveryhistory.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,
 product.theoreticalweight, product.typeofmerchandise, product.model,
 (select productsize.theoreticalweight
   from   productsize
   where  productsize.product_id = deliveryhistory.product_link_id
   and    productsize.sizedefinition_id = deliveryhistory.sizedefinition_link_id) 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,
 finishingmethod.code finishingmethodcode,
 (select d.description
   from   finishingmethod_desc d
   where  d.finishingmethod_id = deliveryhistory.finishingmethod_id
   and    d.language_id = languages.language_id) finishingmethoddescription,
 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.internalprice, deliveryhistory.discount, deliveryhistory.parentpackproduct_link_id,
 deliveryhistory.parentproduct_link_id, processbu.code processbucode,
 processbu.description processbudescription, invoicebu.code invoicebucode,
 invoicebu.description invoicebudescription, deliveryhistory.systemuser_id,
 deliveryhistory.timestamp,
 f_getdelprodprice(rp.number_value, cu.customer_id, product.product_id,
                    sizedefinition_link.sizedefinition_id, finishingmethod.finishingmethod_id,
                    deliveryhistory.deliverydate, product.typeofmerchandise) price,
 f_getvat(rp.number_value,
          (case
             when cu.taxable = 'Y' then
              cu.customer_id
             else
              null
           end), product.product_id, rp.number_value1, cu.country_id, deliveryhistory.deliverydate) vatrate,
 cur.decimals, cur.invoiceamountdecimals, cu.taxable, deliveryhistory.processbusinessunit_id defaultbusinessunit_id,
 customer_link.languagecode customerlanguagecode, languages.code languagecode,
 f_getdelprodpricewithdisc(cu.customer_id, product.product_id, sizedefinition_link.sizedefinition_id,
                            finishingmethod.finishingmethod_id, deliveryhistory.deliverydate,
                            product.typeofmerchandise) pricewithdiscount,
 pack_price.wash_discount(cu.customer_id, product.product_id, sizedefinition_link.sizedefinition_id,
                           finishingmethod.finishingmethod_id, deliveryhistory.deliverydate) discountpercentage,
 rp.number_value q, cu.customer_id w, product.product_id e, sizedefinition_link.sizedefinition_id r,
 finishingmethod.finishingmethod_id t, deliveryhistory.deliverydate y, product.typeofmerchandise u,
 pl.code plant_code, pl.name plant_name, 0 qtyreject, 0 qtyshortage
from   deliveryhistory
join   product
on     (deliveryhistory.product_link_id = product.product_id)
join   productgroup
on     (productgroup.productgroup_id = product.productgroup_id)
join   sizedefinition
on     (deliveryhistory.sizedefinition_link_id = sizedefinition.sizedefinition_id), customer_link
left   outer join customer cu
on     cu.customer_id = customer_link.customer_id, department_link, distributionpoint_link,
 sizedefinition_link, businessunit processbu, businessunit invoicebu, finishingmethod,
 languages, product_link parentproduct, product_link pack, reportparam rp, currency cur,
 businessunit bu, plant pl
where  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_link.customer_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.processbusinessunit_id = processbu.businessunit_id
and    deliveryhistory.invoicebusinessunit_id = invoicebu.businessunit_id
and    finishingmethod.finishingmethod_id = deliveryhistory.finishingmethod_id
and    deliveryhistory.currency_id = cur.currency_id
and    bu.businessunit_id = deliveryhistory.processbusinessunit_id
and    bu.plant_id = pl.plant_id
union all
select /*+index(pn XIE10PACKINGNOTE)*/
 2 linetype, rp.reportparam_id, cu.customernumber, cu.name customername, depl.departmentnumber,
 depl.description departmentdescription, distl.distributionpointnumber, distl.distributionpoint_id distributionpoint_id,
 distl.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, product.code productcode,
 (select b.description
   from   product_link_desc b
   where  b.product_link_id = pnl.product_id
   and    b.language_id = languages.language_id) productdescription, '' parentproductcode,
 '' parentproductdescription, 1 packindication, '' packcode,
 (select f.description
   from   product_link_desc f
   where  f.product_link_id = pnl.product_id
   and    f.language_id = languages.language_id) packdescription,
 (select f.code from activity f where f.activity_id = productgroup.activity_id) activitycode,
 product.theoreticalweight, product.typeofmerchandise, product.model,
 (select productsize.theoreticalweight
   from   productsize
   where  productsize.product_id = pnl.product_id
   and    productsize.sizedefinition_id = pnl.sizedefinition_id) prodsize_theoreticalweight,
 sizedefinition.code sizecode,
 (select c.description
   from   sizedefinition_link_desc c
   where  c.sizedefinition_link_id = pnl.sizedefinition_id
   and    c.language_id = languages.language_id) sizedescription,
 finishingmethod.code finishingmethodcode,
 (select d.description
   from   finishingmethod_desc d
   where  d.finishingmethod_id = pnl.finishingmethod_id
   and    d.language_id = languages.language_id) finishingmethoddescription, pn.deliverydate,
 pn.year * 100 + pn.week yearweek, pn.week, pn.year, month(pn.deliverydate) realmonth,
 year(pn.deliverydate) realyear, pn.daynumber, 0 amountordered, 0 amountdelivered, 0 amountshortage,
 pnl.price internalprice, pnl.discount, 0 parentpackproduct_link_id, 0 parentproduct_link_id,
 processbu.code processbucode, processbu.description processbudescription,
 invoicebu.code invoicebucode, invoicebu.description invoicebudescription, pn.systemuser_id,
 pn.timestamp,
 f_getdelprodprice(rp.number_value, cu.customer_id, product.product_id,
                    sizedefinition.sizedefinition_id, finishingmethod.finishingmethod_id,
                    pn.deliverydate, product.typeofmerchandise) price,
 f_getvat(rp.number_value,
           (case
              when cu.taxable = 'Y' then
               cu.customer_id
              else
               null
            end), product.product_id, rp.number_value1, cu.country_id, pn.deliverydate)  vatrate,
 cur.decimals, cur.invoiceamountdecimals, cu.taxable,  cu.defaultbusinessunit_id defaultbusinessunit_id,
 (select ls.code from languages ls where ls.language_id = cu.language_id) customerlanguagecode,
 languages.code languagecode,
 f_getdelprodpricewithdisc(cu.customer_id, product.product_id, sizedefinition.sizedefinition_id,
                            finishingmethod.finishingmethod_id, pn.deliverydate,
                            product.typeofmerchandise)  pricewithdiscount,
 pack_price.wash_discount(cu.customer_id, product.product_id, sizedefinition.sizedefinition_id,
                           finishingmethod.finishingmethod_id, pn.deliverydate)  discountpercentage,
 rp.number_value q, cu.customer_id w, product.product_id e, sizedefinition.sizedefinition_id r,
 finishingmethod.finishingmethod_id t, pn.deliverydate y, product.typeofmerchandise u,
 pl.code plant_code, pl.name plant_name,
 coalesce((select /*+index (dvs XSPEEDDELIVERYVARIATIONS)*/ sum(dvs.amount)
           from   deliveryvariations dvs
           where  dvs.processed = 'Y'
           and    dvs.packingnote_id = pnl.packingnote_id
           and    dvs.distributionpoint_id = pn.distributionpoint_id
           and    dvs.product_id = pnl.product_id
           and    dvs.sizedefinition_id = pnl.sizedefinition_id
           and    dvs.finishingmethod_id = pnl.finishingmethod_id
           and    dvs.origin = 1
           and    dvs.soilcountsubtype = 3), 0)  qtyreject,
 coalesce((select /*+index (dvs1 XSPEEDDELIVERYVARIATIONS)*/ sum(dvs1.amount)
           from   deliveryvariations dvs1
           where  dvs1.processed = 'Y'
           and    dvs1.packingnote_id = pnl.packingnote_id
           and    dvs1.distributionpoint_id = pn.distributionpoint_id
           and    dvs1.product_id = pnl.product_id
           and    dvs1.sizedefinition_id = pnl.sizedefinition_id
           and    dvs1.finishingmethod_id = pnl.finishingmethod_id
           and    dvs1.origin = 1
           and    dvs1.soilcountsubtype = 2), 0)  qtyshortage
from   packingnote pn
join   packingnoteline pnl
on     pnl.packingnote_id = pn.packingnote_id
join   distributionpoint distl
on     pn.distributionpoint_id = distl.distributionpoint_id
join   department depl
on     distl.department_id = depl.department_id
join   customer cu
on     depl.customer_id = cu.customer_id
join   currency cur
on     cur.currency_id = cu.currency_id
join   businessunit processbu
on     pn.processbusinessunit_id = processbu.businessunit_id
join   plant pl
on     pl.plant_id = processbu.plant_id
join   businessunit invoicebu
on     pn.invoicebusinessunit_id = invoicebu.businessunit_id
join   product
on     pnl.product_id = product.product_id
join   sizedefinition
on     pnl.sizedefinition_id = sizedefinition.sizedefinition_id
join   finishingmethod
on     finishingmethod.finishingmethod_id = pnl.finishingmethod_id
join   productgroup
on     product.productgroup_id = productgroup.productgroup_id
, languages, reportparam rp
where  pn.status_id = (select s.status_id
                       from   status s
                       where  s.statustype = 'PN'
                       and    s.code = '30')

/
create or replace view V_DELIVEREDPRODUCTS_FIS
 (LINETYPE, REPORTPARAM_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, INTERNALPRICE, DISCOUNT, PARENTPACKPRODUCT_LINK_ID, PARENTPRODUCT_LINK_ID, PROCESSBUCODE, PROCESSBUDESCRIPTION, INVOICEBUCODE, INVOICEBUDESCRIPTION, SYSTEMUSER_ID, TIMESTAMP, PRICE, VATRATE, DECIMALS, INVOICEAMOUNTDECIMALS, TAXABLE, DEFAULTBUSINESSUNIT_ID, CUSTOMERLANGUAGECODE, LANGUAGECODE, PRICEWITHDISCOUNT, DISCOUNTPERCENTAGE, Q, W, E, R, T, Y, U, PLANT_CODE
, PLANT_NAME, QTYREJECT, QTYSHORTAGE)
as select /*+index(DELIVERYHISTORY XIE10DELIVERYHISTORY)*/
 1 linetype, rp.reportparam_id, 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, product.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,
 parentproduct.code parentproductcode,
 (select e.description
   from   product_link_desc e
   where  e.product_link_id = deliveryhistory.parentproduct_link_id
   and    e.language_id = languages.language_id) parentproductdescription,
 deliveryhistory.packindication, pack.code packcode,
 (select f.description
   from   product_link_desc f
   where  f.product_link_id = deliveryhistory.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,
 product.theoreticalweight, product.typeofmerchandise, product.model,
 (select productsize.theoreticalweight
   from   productsize
   where  productsize.product_id = deliveryhistory.product_link_id
   and    productsize.sizedefinition_id = deliveryhistory.sizedefinition_link_id) 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,
 finishingmethod.code finishingmethodcode,
 (select d.description
   from   finishingmethod_desc d
   where  d.finishingmethod_id = deliveryhistory.finishingmethod_id
   and    d.language_id = languages.language_id) finishingmethoddescription,
 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.internalprice, deliveryhistory.discount, deliveryhistory.parentpackproduct_link_id,
 deliveryhistory.parentproduct_link_id, processbu.code processbucode,
 processbu.description processbudescription, invoicebu.code invoicebucode,
 invoicebu.description invoicebudescription, deliveryhistory.systemuser_id,
 deliveryhistory.timestamp,
 f_getdelprodprice(rp.number_value, cu.customer_id, product.product_id,
                    sizedefinition_link.sizedefinition_id, finishingmethod.finishingmethod_id,
                    deliveryhistory.deliverydate, product.typeofmerchandise) price,
 f_getvat(rp.number_value,
          (case
             when cu.taxable = 'Y' then
              cu.customer_id
             else
              null
           end), product.product_id, rp.number_value1, cu.country_id, deliveryhistory.deliverydate) vatrate,
 cur.decimals, cur.invoiceamountdecimals, cu.taxable, deliveryhistory.processbusinessunit_id defaultbusinessunit_id,
 customer_link.languagecode customerlanguagecode, languages.code languagecode,
 f_getdelprodpricewithdisc(cu.customer_id, product.product_id, sizedefinition_link.sizedefinition_id,
                            finishingmethod.finishingmethod_id, deliveryhistory.deliverydate,
                            product.typeofmerchandise) pricewithdiscount,
 pack_price.wash_discount(cu.customer_id, product.product_id, sizedefinition_link.sizedefinition_id,
                           finishingmethod.finishingmethod_id, deliveryhistory.deliverydate) discountpercentage,
 rp.number_value q, cu.customer_id w, product.product_id e, sizedefinition_link.sizedefinition_id r,
 finishingmethod.finishingmethod_id t, deliveryhistory.deliverydate y, product.typeofmerchandise u,
 pl.code plant_code, pl.name plant_name, 0 qtyreject, 0 qtyshortage
from   deliveryhistory
join   product
on     (deliveryhistory.product_link_id = product.product_id)
join   productgroup
on     (productgroup.productgroup_id = product.productgroup_id)
join   sizedefinition
on     (deliveryhistory.sizedefinition_link_id = sizedefinition.sizedefinition_id), customer_link
left   outer join customer cu
on     cu.customer_id = customer_link.customer_id, department_link, distributionpoint_link,
 sizedefinition_link, businessunit processbu, businessunit invoicebu, finishingmethod,
 languages, product_link parentproduct, product_link pack, reportparam rp, currency cur,
 businessunit bu, plant pl
where  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_link.customer_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.processbusinessunit_id = processbu.businessunit_id
and    deliveryhistory.invoicebusinessunit_id = invoicebu.businessunit_id
and    finishingmethod.finishingmethod_id = deliveryhistory.finishingmethod_id
and    deliveryhistory.currency_id = cur.currency_id
and    bu.businessunit_id = deliveryhistory.processbusinessunit_id
and    bu.plant_id = pl.plant_id
union all
select /*+index(pn XIE10PACKINGNOTE)*/
 2 linetype, rp.reportparam_id, cu.customernumber, cu.name customername, depl.departmentnumber,
 depl.description departmentdescription, distl.distributionpointnumber,
 distl.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, product.code productcode,
 (select b.description
   from   product_link_desc b
   where  b.product_link_id = pnl.product_id
   and    b.language_id = languages.language_id) productdescription, '' parentproductcode,
 '' parentproductdescription, 1 packindication, '' packcode,
 (select f.description
   from   product_link_desc f
   where  f.product_link_id = pnl.product_id
   and    f.language_id = languages.language_id) packdescription,
 (select f.code from activity f where f.activity_id = productgroup.activity_id) activitycode,
 product.theoreticalweight, product.typeofmerchandise, product.model,
 (select productsize.theoreticalweight
   from   productsize
   where  productsize.product_id = pnl.product_id
   and    productsize.sizedefinition_id = pnl.sizedefinition_id) prodsize_theoreticalweight,
 sizedefinition.code sizecode,
 (select c.description
   from   sizedefinition_link_desc c
   where  c.sizedefinition_link_id = pnl.sizedefinition_id
   and    c.language_id = languages.language_id) sizedescription,
 finishingmethod.code finishingmethodcode,
 (select d.description
   from   finishingmethod_desc d
   where  d.finishingmethod_id = pnl.finishingmethod_id
   and    d.language_id = languages.language_id) finishingmethoddescription, pn.deliverydate,
 pn.year * 100 + pn.week yearweek, pn.week, pn.year, month(pn.deliverydate) realmonth,
 year(pn.deliverydate) realyear, pn.daynumber, 0 amountordered, 0 amountdelivered, 0 amountshortage,
 pnl.price internalprice, pnl.discount, 0 parentpackproduct_link_id, 0 parentproduct_link_id,
 processbu.code processbucode, processbu.description processbudescription,
 invoicebu.code invoicebucode, invoicebu.description invoicebudescription, pn.systemuser_id,
 pn.timestamp,
 f_getdelprodprice(rp.number_value, cu.customer_id, product.product_id,
                    sizedefinition.sizedefinition_id, finishingmethod.finishingmethod_id,
                    pn.deliverydate, product.typeofmerchandise) price,
 f_getvat(rp.number_value,
           (case
              when cu.taxable = 'Y' then
               cu.customer_id
              else
               null
            end), product.product_id, rp.number_value1, cu.country_id, pn.deliverydate)  vatrate,
 cur.decimals, cur.invoiceamountdecimals, cu.taxable,  cu.defaultbusinessunit_id defaultbusinessunit_id,
 (select ls.code from languages ls where ls.language_id = cu.language_id) customerlanguagecode,
 languages.code languagecode,
 f_getdelprodpricewithdisc(cu.customer_id, product.product_id, sizedefinition.sizedefinition_id,
                            finishingmethod.finishingmethod_id, pn.deliverydate,
                            product.typeofmerchandise)  pricewithdiscount,
 pack_price.wash_discount(cu.customer_id, product.product_id, sizedefinition.sizedefinition_id,
                           finishingmethod.finishingmethod_id, pn.deliverydate)  discountpercentage,
 rp.number_value q, cu.customer_id w, product.product_id e, sizedefinition.sizedefinition_id r,
 finishingmethod.finishingmethod_id t, pn.deliverydate y, product.typeofmerchandise u,
 pl.code plant_code, pl.name plant_name,
 coalesce((select /*+index (dvs XSPEEDDELIVERYVARIATIONS)*/ sum(dvs.amount)
           from   deliveryvariations dvs
           where  dvs.processed = 'Y'
           and    dvs.packingnote_id = pnl.packingnote_id
           and    dvs.distributionpoint_id = pn.distributionpoint_id
           and    dvs.product_id = pnl.product_id
           and    dvs.sizedefinition_id = pnl.sizedefinition_id
           and    dvs.finishingmethod_id = pnl.finishingmethod_id
           and    dvs.origin = 1
           and    dvs.soilcountsubtype = 3), 0)  qtyreject,
 coalesce((select /*+index (dvs1 XSPEEDDELIVERYVARIATIONS)*/ sum(dvs1.amount)
           from   deliveryvariations dvs1
           where  dvs1.processed = 'Y'
           and    dvs1.packingnote_id = pnl.packingnote_id
           and    dvs1.distributionpoint_id = pn.distributionpoint_id
           and    dvs1.product_id = pnl.product_id
           and    dvs1.sizedefinition_id = pnl.sizedefinition_id
           and    dvs1.finishingmethod_id = pnl.finishingmethod_id
           and    dvs1.origin = 1
           and    dvs1.soilcountsubtype = 2), 0)  qtyshortage
from   packingnote pn
join   packingnoteline pnl
on     pnl.packingnote_id = pn.packingnote_id
join   distributionpoint distl
on     pn.distributionpoint_id = distl.distributionpoint_id
join   department depl
on     distl.department_id = depl.department_id
join   customer cu
on     depl.customer_id = cu.customer_id
join   currency cur
on     cur.currency_id = cu.currency_id
join   businessunit processbu
on     pn.processbusinessunit_id = processbu.businessunit_id
join   plant pl
on     pl.plant_id = processbu.plant_id
join   businessunit invoicebu
on     pn.invoicebusinessunit_id = invoicebu.businessunit_id
join   product
on     pnl.product_id = product.product_id
join   sizedefinition
on     pnl.sizedefinition_id = sizedefinition.sizedefinition_id
join   finishingmethod
on     finishingmethod.finishingmethod_id = pnl.finishingmethod_id
join   productgroup
on     product.productgroup_id = productgroup.productgroup_id
, languages, reportparam rp
where  pn.status_id = (select s.status_id
                       from   status s
                       where  s.statustype = 'PN'
                       and    s.code = '30')

/
create or replace view V_DELIVEREDPRODUCTS_LLG
 (REPORTPARAM_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, INTERNALPRICE, DISCOUNT, PARENTPACKPRODUCT_LINK_ID, PARENTPRODUCT_LINK_ID, PROCESSBUCODE, PROCESSBUDESCRIPTION, INVOICEBUCODE, INVOICEBUDESCRIPTION, SYSTEMUSER_ID, TIMESTAMP, PRICE, VATRATE, DECIMALS, INVOICEAMOUNTDECIMALS, TAXABLE, DEFAULTBUSINESSUNIT_ID, CUSTOMERLANGUAGECODE, LANGUAGECODE, PRICEWITHDISCOUNT, DISCOUNTPERCENTAGE, Q, W, E, R, T, Y, U, PLANT_CODE
, PLANT_NAME, PLPC_BM, PLPC_CHARGEEXCESS, CLUSTER_CODE)
as SELECT RP.REPORTPARAM_ID,
       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,
       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,
       parentproduct.CODE parentproductcode,
       (SELECT E.DESCRIPTION FROM PRODUCT_LINK_DESC E WHERE E.PRODUCT_LINK_ID = DELIVERYHISTORY.PARENTPRODUCT_LINK_ID AND E.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) parentproductdescription,
       DELIVERYHISTORY.PACKINDICATION,
       pack.CODE packcode,
       (SELECT F.DESCRIPTION FROM PRODUCT_LINK_DESC F WHERE F.PRODUCT_LINK_ID = DELIVERYHISTORY.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,
       PRODUCT.THEORETICALWEIGHT, PRODUCT.typeofmerchandise, PRODUCT.MODEL,
       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,
       FINISHINGMETHOD.CODE finishingmethodcode,
       (SELECT D.DESCRIPTION FROM FINISHINGMETHOD_DESC D WHERE D.FINISHINGMETHOD_ID = DELIVERYHISTORY.FINISHINGMETHOD_ID AND D.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODdescription,
       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.PARENTPACKPRODUCT_LINK_ID, DELIVERYHISTORY.PARENTPRODUCT_LINK_ID,
       PROCESSBU.CODE processbucode, PROCESSBU.DESCRIPTION processbudescription, INVOICEBU.CODE invoicebucode,
       INVOICEBU.DESCRIPTION invoicebudescription, DELIVERYHISTORY.SYSTEMUSER_ID, DELIVERYHISTORY.TIMESTAMP,
       F_GETDELPRODPRICE(rp.number_value, cu.customer_id, product.product_id, SIZEDEFINITION_LINK.SIZEDEFINITION_ID,
         FINISHINGMETHOD.FINISHINGMETHOD_ID, rp.date_value1/*deliveryhistory.deliverydate*/,product.typeofmerchandise) price,
       F_GETVAT(rp.number_value, (CASE WHEN cu.taxable = 'Y' then cu.customer_id ELSE null END)
       , product.product_id, /*rp.number_value1*/ (CASE WHEN rp.number_value1 = -1 then cu.country_id ELSE rp.number_value1  END), cu.country_id, rp.date_value1/*deliveryhistory.deliverydate*/) vatrate,
       cur.decimals, cur.invoiceamountdecimals,
       cu.taxable, bu.businessunit_id defaultbusinessunit_id,
       CUSTOMER_LINK.LANGUAGECODE CUSTOMERLANGUAGECODE, LANGUAGES.CODE LANGUAGECODE,
       F_GETDELPRODPRICEWITHDISC(cu.customer_id, product.product_id, SIZEDEFINITION_LINK.SIZEDEFINITION_ID,
         FINISHINGMETHOD.FINISHINGMETHOD_ID, deliveryhistory.deliverydate, product.typeofmerchandise) PRICEWITHDISCOUNT,
       F_DiscountWash(cu.customer_id, product.product_id, SIZEDEFINITION_LINK.SIZEDEFINITION_ID,
         FINISHINGMETHOD.FINISHINGMETHOD_ID,deliveryhistory.deliverydate) DISCOUNTPERCENTAGE
         , rp.number_value q , cu.customer_id  w, product.product_id e, SIZEDEFINITION_LINK.SIZEDEFINITION_ID r,
         FINISHINGMETHOD.FINISHINGMETHOD_ID t, deliveryhistory.deliverydate y ,product.typeofmerchandise u
, pl.code Plant_Code, pl.name Plant_Name
, (select plpc.billingmethod from productlistpercustomer plpc where plpc.product_id = product.product_id
        and plpc.sizedefinition_id = sizedefinition.sizedefinition_id
        and plpc.finishingmethod_id = finishingmethod.finishingmethod_id
        and plpc.customer_id = customer_link.customer_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')) plpc_bm
,  (select plpc.chargeexcess from productlistpercustomer plpc where plpc.product_id = product.product_id
        and plpc.sizedefinition_id = sizedefinition.sizedefinition_id
        and plpc.finishingmethod_id = finishingmethod.finishingmethod_id
        and plpc.customer_id = customer_link.customer_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')) plpc_chargeexcess
, (select cc.code from customerspercluster cpc, customercluster cc
               where cpc.cluster_id = cc.cluster_id
               and cpc.customer_id = customer_link.customer_id) cluster_code
 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,
      CUSTOMER_LINK
        left outer join customer cu          --left join country ctr on cu.country_id = ctr.country_id)
        on cu.customer_id = CUSTOMER_LINK.CUSTOMER_ID,
      DEPARTMENT_LINK, DISTRIBUTIONPOINT_LINK,
      SIZEDEFINITION_LINK,
      BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU, FINISHINGMETHOD, LANGUAGES,
      PRODUCT_LINK parentproduct, PRODUCT_LINK pack,
      PRODUCT_LINK
        LEFT OUTER JOIN PRODUCTGROUP ON (PRODUCT_LINK.PRODUCTGROUPCODE = PRODUCTGROUP.CODE),
      REPORTPARAM RP, currency cur, Businessunit BU, plant pl
 WHERE 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_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.PARENTPACKPRODUCT_LINK_ID = pack.PRODUCT_LINK_ID
  AND DELIVERYHISTORY.SIZEDEFINITION_LINK_ID = SIZEDEFINITION_LINK.SIZEDEFINITION_LINK_ID
  AND DELIVERYHISTORY.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
	AND DELIVERYHISTORY.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  AND FINISHINGMETHOD.FINISHINGMETHOD_ID = DELIVERYHISTORY.FINISHINGMETHOD_ID
  AND PRODUCT.PRODUCT_ID = PRODUCTSIZE.PRODUCT_ID
  AND SIZEDEFINITION.SIZEDEFINITION_ID = PRODUCTSIZE.SIZEDEFINITION_ID
  and DELIVERYHISTORY.Currency_Id = cur.currency_id
  and (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 bu.plant_id = pl.plant_id

/
create or replace view V_DELIVEREDPRODUCTS_PLS
 (REPORTPARAM_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, INTERNALPRICE, DISCOUNT, PARENTPACKPRODUCT_LINK_ID, PARENTPRODUCT_LINK_ID, PROCESSBUCODE, PROCESSBUDESCRIPTION, INVOICEBUCODE, INVOICEBUDESCRIPTION, SYSTEMUSER_ID, TIMESTAMP, PRICE, VATRATE, DECIMALS, INVOICEAMOUNTDECIMALS, TAXABLE, DEFAULTBUSINESSUNIT_ID, CUSTOMERLANGUAGECODE, LANGUAGECODE, PRICEWITHDISCOUNT, DISCOUNTPERCENTAGE, Q, W, E, R, T, Y, U, PLANT_CODE
, PLANT_NAME, WIDTH_S, LENGTH_S)
as SELECT RP.REPORTPARAM_ID,
       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,
       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,
       parentproduct.CODE parentproductcode,
       (SELECT E.DESCRIPTION FROM PRODUCT_LINK_DESC E WHERE E.PRODUCT_LINK_ID = DELIVERYHISTORY.PARENTPRODUCT_LINK_ID AND E.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) parentproductdescription,
       DELIVERYHISTORY.PACKINDICATION,
       pack.CODE packcode,
       (SELECT F.DESCRIPTION FROM PRODUCT_LINK_DESC F WHERE F.PRODUCT_LINK_ID = DELIVERYHISTORY.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,
       PRODUCT.THEORETICALWEIGHT, PRODUCT.typeofmerchandise, PRODUCT.MODEL,
       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,
       FINISHINGMETHOD.CODE finishingmethodcode,
       (SELECT D.DESCRIPTION FROM FINISHINGMETHOD_DESC D WHERE D.FINISHINGMETHOD_ID = DELIVERYHISTORY.FINISHINGMETHOD_ID AND D.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODdescription,
       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.PARENTPACKPRODUCT_LINK_ID, DELIVERYHISTORY.PARENTPRODUCT_LINK_ID,
       PROCESSBU.CODE processbucode, PROCESSBU.DESCRIPTION processbudescription, INVOICEBU.CODE invoicebucode,
       INVOICEBU.DESCRIPTION invoicebudescription, DELIVERYHISTORY.SYSTEMUSER_ID, DELIVERYHISTORY.TIMESTAMP,
       (case when product.typeofmerchandise in (1,2) then
         case
         when pack_price.Wash_Price(customer_link.customer_id,product.product_id,sizedefinition.sizedefinition_id,FINISHINGMETHOD.FINISHINGMETHOD_ID) = 0 then
              pack_price.Rent_Price(customer_link.customer_id,product.product_id,sizedefinition.sizedefinition_id,FINISHINGMETHOD.FINISHINGMETHOD_ID)
         else
              pack_price.Wash_Price(customer_link.customer_id,product.product_id,sizedefinition.sizedefinition_id,FINISHINGMETHOD.FINISHINGMETHOD_ID)
         end
         else
       F_GETDELPRODPRICE(rp.number_value, cu.customer_id, product.product_id, SIZEDEFINITION_LINK.SIZEDEFINITION_ID,
         FINISHINGMETHOD.FINISHINGMETHOD_ID, rp.date_value1/*deliveryhistory.deliverydate*/,product.typeofmerchandise)
       end) price,
       F_GETVAT(rp.number_value, (CASE WHEN cu.taxable = 'Y' then cu.customer_id ELSE null END)
       , product.product_id, /*rp.number_value1*/ (CASE WHEN rp.number_value1 = -1 then cu.country_id ELSE rp.number_value1  END), cu.country_id, rp.date_value1/*deliveryhistory.deliverydate*/) vatrate,
       cur.decimals, cur.invoiceamountdecimals,
       cu.taxable, bu.businessunit_id defaultbusinessunit_id,
       CUSTOMER_LINK.LANGUAGECODE CUSTOMERLANGUAGECODE, LANGUAGES.CODE LANGUAGECODE,
       F_GETDELPRODPRICEWITHDISC(cu.customer_id, product.product_id, SIZEDEFINITION_LINK.SIZEDEFINITION_ID,
         FINISHINGMETHOD.FINISHINGMETHOD_ID, deliveryhistory.deliverydate, product.typeofmerchandise) PRICEWITHDISCOUNT,
       pack_price.Wash_Discount(cu.customer_id, product.product_id, SIZEDEFINITION_LINK.SIZEDEFINITION_ID,
         FINISHINGMETHOD.FINISHINGMETHOD_ID,deliveryhistory.deliverydate) DISCOUNTPERCENTAGE
         , rp.number_value q , cu.customer_id  w, product.product_id e, SIZEDEFINITION_LINK.SIZEDEFINITION_ID r,
         FINISHINGMETHOD.FINISHINGMETHOD_ID t, deliveryhistory.deliverydate y ,product.typeofmerchandise u
, pl.code Plant_Code, pl.name Plant_Name,
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),
      PRODUCTSIZE,
      CUSTOMER_LINK
        left outer join customer cu          --left join country ctr on cu.country_id = ctr.country_id)
        on cu.customer_id = CUSTOMER_LINK.CUSTOMER_ID,
      DEPARTMENT_LINK, DISTRIBUTIONPOINT_LINK,
      SIZEDEFINITION_LINK,
      BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU, FINISHINGMETHOD, LANGUAGES,
      PRODUCT_LINK parentproduct, PRODUCT_LINK pack,
      PRODUCT_LINK
        LEFT OUTER JOIN PRODUCTGROUP ON (PRODUCT_LINK.PRODUCTGROUPCODE = PRODUCTGROUP.CODE),
      REPORTPARAM RP, currency cur, Businessunit BU, plant pl
 WHERE 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_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.PARENTPACKPRODUCT_LINK_ID = pack.PRODUCT_LINK_ID
  AND DELIVERYHISTORY.SIZEDEFINITION_LINK_ID = SIZEDEFINITION_LINK.SIZEDEFINITION_LINK_ID
  AND DELIVERYHISTORY.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND DELIVERYHISTORY.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  AND FINISHINGMETHOD.FINISHINGMETHOD_ID = DELIVERYHISTORY.FINISHINGMETHOD_ID
  AND PRODUCT.PRODUCT_ID = PRODUCTSIZE.PRODUCT_ID
  AND SIZEDEFINITION.SIZEDEFINITION_ID = PRODUCTSIZE.SIZEDEFINITION_ID
  and DELIVERYHISTORY.Currency_Id = cur.currency_id
  and (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 bu.plant_id = pl.plant_id

/
create or replace view V_DELIVEREDPRODUCTS_RMI
 (LINETYPE, REPORTPARAM_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, INTERNALPRICE, DISCOUNT, PARENTPACKPRODUCT_LINK_ID, PARENTPRODUCT_LINK_ID, PROCESSBUCODE, PROCESSBUDESCRIPTION, INVOICEBUCODE, INVOICEBUDESCRIPTION, SYSTEMUSER_ID, TIMESTAMP, PRICE, VATRATE, DECIMALS, INVOICEAMOUNTDECIMALS, TAXABLE, DEFAULTBUSINESSUNIT_ID, CUSTOMERLANGUAGECODE, LANGUAGECODE, PRICEWITHDISCOUNT, DISCOUNTPERCENTAGE, Q, W, E, R, T, Y, U, PLANT_CODE
, PLANT_NAME, QTYREJECT, QTYSHORTAGE, ROUTENUMBER, ROUTE_DESC)
as select /*+index(DELIVERYHISTORY XIE10DELIVERYHISTORY)*/
 1 linetype, rp.reportparam_id, 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, product.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,
 parentproduct.code parentproductcode,
 (select e.description
   from   product_link_desc e
   where  e.product_link_id = deliveryhistory.parentproduct_link_id
   and    e.language_id = languages.language_id) parentproductdescription,
 deliveryhistory.packindication, pack.code packcode,
 (select f.description
   from   product_link_desc f
   where  f.product_link_id = deliveryhistory.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,
 product.theoreticalweight, product.typeofmerchandise, product.model,
 (select productsize.theoreticalweight
   from   productsize
   where  productsize.product_id = deliveryhistory.product_link_id
   and    productsize.sizedefinition_id = deliveryhistory.sizedefinition_link_id) 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,
 finishingmethod.code finishingmethodcode,
 (select d.description
   from   finishingmethod_desc d
   where  d.finishingmethod_id = deliveryhistory.finishingmethod_id
   and    d.language_id = languages.language_id) finishingmethoddescription,
 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.internalprice, deliveryhistory.discount, deliveryhistory.parentpackproduct_link_id,
 deliveryhistory.parentproduct_link_id, processbu.code processbucode,
 processbu.description processbudescription, invoicebu.code invoicebucode,
 invoicebu.description invoicebudescription, deliveryhistory.systemuser_id,
 deliveryhistory.timestamp,
 f_getdelprodprice(rp.number_value, cu.customer_id, product.product_id,
                    sizedefinition_link.sizedefinition_id, finishingmethod.finishingmethod_id,
                    deliveryhistory.deliverydate, product.typeofmerchandise) price,
 f_getvat(rp.number_value,
          (case
             when cu.taxable = 'Y' then
              cu.customer_id
             else
              null
           end), product.product_id, rp.number_value1, cu.country_id, deliveryhistory.deliverydate) vatrate,
 cur.decimals, cur.invoiceamountdecimals, cu.taxable, deliveryhistory.processbusinessunit_id defaultbusinessunit_id,
 customer_link.languagecode customerlanguagecode, languages.code languagecode,
 f_getdelprodpricewithdisc(cu.customer_id, product.product_id, sizedefinition_link.sizedefinition_id,
                            finishingmethod.finishingmethod_id, deliveryhistory.deliverydate,
                            product.typeofmerchandise) pricewithdiscount,
 pack_price.wash_discount(cu.customer_id, product.product_id, sizedefinition_link.sizedefinition_id,
                           finishingmethod.finishingmethod_id, deliveryhistory.deliverydate) discountpercentage,
 rp.number_value q, cu.customer_id w, product.product_id e, sizedefinition_link.sizedefinition_id r,
 finishingmethod.finishingmethod_id t, deliveryhistory.deliverydate y, product.typeofmerchandise u,
 pl.code plant_code, pl.name plant_name, 0 qtyreject, 0 qtyshortage
 , -1 routenumber, ' ' route_desc
from   deliveryhistory
join   product
on     (deliveryhistory.product_link_id = product.product_id)
join   productgroup
on     (productgroup.productgroup_id = product.productgroup_id)
join   sizedefinition
on     (deliveryhistory.sizedefinition_link_id = sizedefinition.sizedefinition_id), customer_link
left   outer join customer cu
on     cu.customer_id = customer_link.customer_id, department_link, distributionpoint_link,
 sizedefinition_link, businessunit processbu, businessunit invoicebu, finishingmethod,
 languages, product_link parentproduct, product_link pack, reportparam rp, currency cur,
 businessunit bu, plant pl
where  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_link.customer_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.processbusinessunit_id = processbu.businessunit_id
and    deliveryhistory.invoicebusinessunit_id = invoicebu.businessunit_id
and    finishingmethod.finishingmethod_id = deliveryhistory.finishingmethod_id
and    deliveryhistory.currency_id = cur.currency_id
and    bu.businessunit_id = deliveryhistory.processbusinessunit_id
and    bu.plant_id = pl.plant_id
union all
select /*+index(pn XIE10PACKINGNOTE)*/
 2 linetype, rp.reportparam_id, cu.customernumber, cu.name customername, depl.departmentnumber,
 depl.description departmentdescription, distl.distributionpointnumber,
 distl.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, product.code productcode,
 (select b.description
   from   product_link_desc b
   where  b.product_link_id = pnl.product_id
   and    b.language_id = languages.language_id) productdescription, '' parentproductcode,
 '' parentproductdescription, 1 packindication, '' packcode,
 (select f.description
   from   product_link_desc f
   where  f.product_link_id = pnl.product_id
   and    f.language_id = languages.language_id) packdescription,
 (select f.code from activity f where f.activity_id = productgroup.activity_id) activitycode,
 product.theoreticalweight, product.typeofmerchandise, product.model,
 (select productsize.theoreticalweight
   from   productsize
   where  productsize.product_id = pnl.product_id
   and    productsize.sizedefinition_id = pnl.sizedefinition_id) prodsize_theoreticalweight,
 sizedefinition.code sizecode,
 (select c.description
   from   sizedefinition_link_desc c
   where  c.sizedefinition_link_id = pnl.sizedefinition_id
   and    c.language_id = languages.language_id) sizedescription,
 finishingmethod.code finishingmethodcode,
 (select d.description
   from   finishingmethod_desc d
   where  d.finishingmethod_id = pnl.finishingmethod_id
   and    d.language_id = languages.language_id) finishingmethoddescription, pn.deliverydate,
 pn.year * 100 + pn.week yearweek, pn.week, pn.year, month(pn.deliverydate) realmonth,
 year(pn.deliverydate) realyear, pn.daynumber, 0 amountordered, pnl.deliveredamount amountdelivered, 0 amountshortage,
 pnl.price internalprice, pnl.discount, 0 parentpackproduct_link_id, 0 parentproduct_link_id,
 processbu.code processbucode, processbu.description processbudescription,
 invoicebu.code invoicebucode, invoicebu.description invoicebudescription, pn.systemuser_id,
 pn.timestamp,
 f_getdelprodprice(rp.number_value, cu.customer_id, product.product_id,
                    sizedefinition.sizedefinition_id, finishingmethod.finishingmethod_id,
                    pn.deliverydate, product.typeofmerchandise) price,
 f_getvat(rp.number_value,
           (case
              when cu.taxable = 'Y' then
               cu.customer_id
              else
               null
            end), product.product_id, rp.number_value1, cu.country_id, pn.deliverydate)  vatrate,
 cur.decimals, cur.invoiceamountdecimals, cu.taxable,  cu.defaultbusinessunit_id defaultbusinessunit_id,
 (select ls.code from languages ls where ls.language_id = cu.language_id) customerlanguagecode,
 languages.code languagecode,
 f_getdelprodpricewithdisc(cu.customer_id, product.product_id, sizedefinition.sizedefinition_id,
                            finishingmethod.finishingmethod_id, pn.deliverydate,
                            product.typeofmerchandise)  pricewithdiscount,
 pack_price.wash_discount(cu.customer_id, product.product_id, sizedefinition.sizedefinition_id,
                           finishingmethod.finishingmethod_id, pn.deliverydate)  discountpercentage,
 rp.number_value q, cu.customer_id w, product.product_id e, sizedefinition.sizedefinition_id r,
 finishingmethod.finishingmethod_id t, pn.deliverydate y, product.typeofmerchandise u,
 pl.code plant_code, pl.name plant_name,
 /*coalesce((select /*+index (dvs XSPEEDDELIVERYVARIATIONS)* / sum(dvs.amount)
           from   deliveryvariations dvs
           where  dvs.processed = 'Y'
           and    dvs.packingnote_id = pnl.packingnote_id
           and    dvs.distributionpoint_id = pn.distributionpoint_id
           and    dvs.product_id = pnl.product_id
           and    dvs.sizedefinition_id = pnl.sizedefinition_id
           and    dvs.finishingmethod_id = pnl.finishingmethod_id
           and    dvs.origin = 1
           and    dvs.soilcountsubtype = 3), 0) */0 qtyreject,
 /*coalesce((select /*+index (dvs1 XSPEEDDELIVERYVARIATIONS)* / sum(dvs1.amount)
           from   deliveryvariations dvs1
           where  dvs1.processed = 'Y'
           and    dvs1.packingnote_id = pnl.packingnote_id
           and    dvs1.distributionpoint_id = pn.distributionpoint_id
           and    dvs1.product_id = pnl.product_id
           and    dvs1.sizedefinition_id = pnl.sizedefinition_id
           and    dvs1.finishingmethod_id = pnl.finishingmethod_id
           and    dvs1.origin = 1
           and    dvs1.soilcountsubtype = 2), 0) */0 qtyshortage
, r.routenumber, r.description route_desc
from   packingnote pn
join   packingnoteline pnl
on     pnl.packingnote_id = pn.packingnote_id
join   distributionpoint distl
on     pn.distributionpoint_id = distl.distributionpoint_id
join   department depl
on     distl.department_id = depl.department_id
join   customer cu
on     depl.customer_id = cu.customer_id
join   currency cur
on     cur.currency_id = cu.currency_id
join   businessunit processbu
on     pn.processbusinessunit_id = processbu.businessunit_id
join   plant pl
on     pl.plant_id = processbu.plant_id
join   businessunit invoicebu
on     pn.invoicebusinessunit_id = invoicebu.businessunit_id
join   product
on     pnl.product_id = product.product_id
join   sizedefinition
on     pnl.sizedefinition_id = sizedefinition.sizedefinition_id
join   finishingmethod
on     finishingmethod.finishingmethod_id = pnl.finishingmethod_id
join   productgroup
on     product.productgroup_id = productgroup.productgroup_id
join   route r
on     r.route_id = pn.route_id
, languages, reportparam rp
where  pn.status_id = (select s.status_id
                       from   status s
                       where  s.statustype = 'PN'
                       and    s.code = '30')

/
create or replace view V_DELIVEREDPRODUCTS_SBN
 (REPORTPARAM_ID, LINETYPE, CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PRODUCTCODE, PRODUCTDESCRIPTION, PARENTPRODUCTCODE, PARENTPRODUCTDESCRIPTION, PACKINDICATION, ACTIVITYCODE, THEORETICALWEIGHT, TYPEOFMERCHANDISE, MODEL, PRODSIZE_THEORETICALWEIGHT, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODCODE, FINISHINGMETHODDESCRIPTION, DELIVERYDATE
, YEARWEEK, WEEK, YEAR, REALMONTH, REALYEAR, DAYNUMBER, PACKINGSEQUENCE, AMOUNTORDERED, AMOUNTDELIVERED, PROCESSBUCODE, PROCESSBUDESCRIPTION, INVOICEBUCODE, INVOICEBUDESCRIPTION, SYSTEMUSER_ID, TIMESTAMP, PRICE, VATRATE, DECIMALS, INVOICEAMOUNTDECIMALS, TAXABLE, DEFAULTBUSINESSUNIT_ID, CUSTOMERLANGUAGECODE, LANGUAGECODE, PRICEWITHDISCOUNT, DISCOUNTPERCENTAGE, Q, W, E, R, T, Y, U, PLANT_CODE, PLANT_NAME, WEIGHCAT_CODE, WEIGHCAT_DESC)
as select rp.reportparam_id,
       1 linetype,
       customer_link.customernumber,
       customer_link.name customername,
       department_link.departmentnumber,
       department_link.description departmentdescription,
       distributionpoint_link.distributionpointnumber,
       distributionpoint_link.description distributionpointdescription,
       (select pg.code from productgroup pg where pg.productgroup_id = product.product_id) productgroupcode,
       (select a.description
          from productgroup_desc a
         where a.productgroup_id = product.productgroup_id
           and a.language_id = languages.language_id) productgroupdescription,
       product.code productcode,
       (select b.description
          from product_link_desc b
         where b.product_link_id = packingnoteline.product_id
           and b.language_id = languages.language_id) productdescription,
       (select parentproduct.code
          from product_link parentproduct
         where parentproduct.product_id = product.parentproduct_id) parentproductcode,
       (select e.description
          from product_link_desc e
         where e.product_link_id = product.parentproduct_id
           and e.language_id = languages.language_id) parentproductdescription,
       1 packindication,
       (select f.code
          from activity f, productgroup prdg
         where f.activity_id = prdg.activity_id and prdg.productgroup_id = product.productgroup_id ) activitycode,
       product.theoreticalweight,
       product.typeofmerchandise,
       product.model,
       (select ps.theoreticalweight
          from productsize ps
         where ps.product_id = packingnoteline.product_id
           and ps.sizedefinition_id = packingnoteline.sizedefinition_id) prodsize_theoreticalweight,
       sizedefinition.code sizecode,
       (select c.description
          from sizedefinition_link_desc c
         where c.sizedefinition_link_id = sizedefinition.sizedefinition_id
           and c.language_id = languages.language_id) sizedescription,
       finishingmethod.code finishingmethodcode,
       (select d.description
          from finishingmethod_desc d
         where d.finishingmethod_id = finishingmethod.finishingmethod_id
           and d.language_id = languages.language_id) finishingmethoddescription,
       packingnote.deliverydate,
       packingnote.year * 100 + packingnote.week yearweek,
       packingnote.week,
       packingnote.year,
       month(packingnote.deliverydate) realmonth,
       year(packingnote.deliverydate) realyear,
       packingnote.daynumber, packingnoteline.packingsequence,
       packingnoteline.tobedeliveredamount amountordered,
       packingnoteline.deliveredamount amountdelivered,
       processbu.code processbucode,
       processbu.description processbudescription,
       invoicebu.code invoicebucode,
       invoicebu.description invoicebudescription,
       packingnote.systemuser_id,
       packingnote.timestamp,
       f_getdelprodprice(rp.number_value,
                         cu.customer_id,
                         product.product_id,
                         sizedefinition.sizedefinition_id,
                         finishingmethod.finishingmethod_id,
                         rp.date_value1 /*deliveryhistory.deliverydate*/,
                         product.typeofmerchandise) price,
       f_getvat(rp.number_value,
                (case
                  when cu.taxable = 'Y' then
                   cu.customer_id
                  else
                   null
                end),
                product.product_id, /*rp.number_value1*/
                (case
                  when rp.number_value1 = -1 then
                   cu.country_id
                  else
                   rp.number_value1
                end),
                cu.country_id,
                rp.date_value1 /*deliveryhistory.deliverydate*/) vatrate,
       cur.decimals,
       cur.invoiceamountdecimals,
       cu.taxable,
       bu.businessunit_id defaultbusinessunit_id,
       customer_link.languagecode customerlanguagecode,
       languages.code languagecode,
       f_getdelprodpricewithdisc(cu.customer_id,
                                 product.product_id,
                                 sizedefinition.sizedefinition_id,
                                 finishingmethod.finishingmethod_id,
                                 packingnote.deliverydate,
                                 product.typeofmerchandise) pricewithdiscount,
       pack_price.wash_discount(cu.customer_id,
                                product.product_id,
                                sizedefinition.sizedefinition_id,
                                finishingmethod.finishingmethod_id,
                                packingnote.deliverydate) discountpercentage,
       rp.number_value q,
       cu.customer_id w,
       product.product_id e,
       sizedefinition.sizedefinition_id r,
       finishingmethod.finishingmethod_id t,
       packingnote.deliverydate y,
       product.typeofmerchandise u,
       pl.code plant_code,
       pl.name plant_name,
       (select wc.code from weighingcategory wc where wc.weighingcategory_id = product.weighingcategory_id) weighcat_code,
       (select wcd.description from weighingcategory_desc wcd where wcd.weighingcategory_id = product.weighingcategory_id and wcd.language_id = languages.language_id) weighcat_desc
from   packingnoteline
,      packingnote, status st
,      product
,      sizedefinition
,      finishingmethod
,      languages
,      customer_link
               left outer join (customer cu inner join currency cur on cu.currency_id = cur.currency_id)
               on cu.customer_id = customer_link.customer_id
,      department_link,
       distributionpoint_link, businessunit processbu,
       businessunit invoicebu,
       reportparam rp,
       businessunit bu, plant pl
where  packingnoteline.packingnote_id = packingnote.packingnote_id
   and packingnote.status_id = st.status_id
   and st.statustype = 'PN'
   and st.code = '30'
   and packingnoteline.product_id = product.product_id
   and packingnoteline.sizedefinition_id = sizedefinition.sizedefinition_id
   and packingnoteline.finishingmethod_id = finishingmethod.finishingmethod_id
   and packingnote.distributionpoint_id = distributionpoint_link.distributionpoint_id
   and distributionpoint_link.department_link_id = department_link.department_link_id
   and department_link.customer_link_id = customer_link.customer_link_id
   and packingnote.processbusinessunit_id = processbu.businessunit_id
   and packingnote.invoicebusinessunit_id = invoicebu.businessunit_id
   and (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 bu.plant_id = pl.plant_id
union all
select rp.reportparam_id,
       2 linetype,
       customer_link.customernumber,
       customer_link.name customername,
       department_link.departmentnumber,
       department_link.description departmentdescription,
       distributionpoint_link.distributionpointnumber,
       distributionpoint_link.description distributionpointdescription,
       (select pg.code from productgroup pg where pg.productgroup_id = product.product_id) productgroupcode,
       (select a.description
          from productgroup_desc a
         where a.productgroup_id = product.productgroup_id
           and a.language_id = languages.language_id) productgroupdescription,
       product.code productcode,
       (select b.description
          from product_link_desc b
         where b.product_link_id = packingnoteline.product_id
           and b.language_id = languages.language_id) productdescription,
       (select parentproduct.code
          from product_link parentproduct
         where parentproduct.product_id = pc.pack_id) parentproductcode,
       (select e.description
          from product_link_desc e
         where e.product_link_id = pc.pack_id
           and e.language_id = languages.language_id) parentproductdescription,
       2 packindication,
       (select f.code
          from activity f, productgroup prdg, product prd
         where f.activity_id = prdg.activity_id and prdg.productgroup_id = prd.productgroup_id and prd.product_id = pc.pack_id ) activitycode,
       product.theoreticalweight,
       product.typeofmerchandise,
       product.model,
       (select ps.theoreticalweight
          from productsize ps
         where ps.product_id = pc.product_id
           and ps.sizedefinition_id = pc.sizedefinition_id) prodsize_theoreticalweight,
       sizedefinition.code sizecode,
       (select c.description
          from sizedefinition_link_desc c
         where c.sizedefinition_link_id = sizedefinition.sizedefinition_id
           and c.language_id = languages.language_id) sizedescription,
       finishingmethod.code finishingmethodcode,
       (select d.description
          from finishingmethod_desc d
         where d.finishingmethod_id = finishingmethod.finishingmethod_id
           and d.language_id = languages.language_id) finishingmethoddescription,
       packingnote.deliverydate,
       packingnote.year * 100 + packingnote.week yearweek,
       packingnote.week,
       packingnote.year,
       month(packingnote.deliverydate) realmonth,
       year(packingnote.deliverydate) realyear,
       packingnote.daynumber, pc.packsequence packingsequence,
       (pc.amount * packingnoteline.tobedeliveredamount) amountordered,
       (pc.amount * packingnoteline.deliveredamount) amountdelivered,
       processbu.code processbucode,
       processbu.description processbudescription,
       invoicebu.code invoicebucode,
       invoicebu.description invoicebudescription,
       packingnote.systemuser_id,
       packingnote.timestamp,
       f_getdelprodprice(rp.number_value,
                         cu.customer_id,
                         product.product_id,
                         sizedefinition.sizedefinition_id,
                         finishingmethod.finishingmethod_id,
                         rp.date_value1 /*deliveryhistory.deliverydate*/,
                         product.typeofmerchandise) price,
       f_getvat(rp.number_value,
                (case
                  when cu.taxable = 'Y' then
                   cu.customer_id
                  else
                   null
                end),
                product.product_id, /*rp.number_value1*/
                (case
                  when rp.number_value1 = -1 then
                   cu.country_id
                  else
                   rp.number_value1
                end),
                cu.country_id,
                rp.date_value1 /*deliveryhistory.deliverydate*/) vatrate,
       cur.decimals,
       cur.invoiceamountdecimals,
       cu.taxable,
       bu.businessunit_id defaultbusinessunit_id,
       customer_link.languagecode customerlanguagecode,
       languages.code languagecode,
       f_getdelprodpricewithdisc(cu.customer_id,
                                 product.product_id,
                                 sizedefinition.sizedefinition_id,
                                 finishingmethod.finishingmethod_id,
                                 packingnote.deliverydate,
                                 product.typeofmerchandise) pricewithdiscount,
       pack_price.wash_discount(cu.customer_id,
                                product.product_id,
                                sizedefinition.sizedefinition_id,
                                finishingmethod.finishingmethod_id,
                                packingnote.deliverydate) discountpercentage,
       rp.number_value q,
       cu.customer_id w,
       product.product_id e,
       sizedefinition.sizedefinition_id r,
       finishingmethod.finishingmethod_id t,
       packingnote.deliverydate y,
       product.typeofmerchandise u,
       pl.code plant_code,
       pl.name plant_name,
       (select wc.code from weighingcategory wc where wc.weighingcategory_id = product.weighingcategory_id) weighcat_code,
       (select wcd.description from weighingcategory_desc wcd where wcd.weighingcategory_id = product.weighingcategory_id and wcd.language_id = languages.language_id) weighcat_desc
from   packingnoteline
,      packingnote, status st
,      packcontents pc
,      product
,      sizedefinition
,      finishingmethod
,      languages
,      customer_link
               left outer join (customer cu inner join currency cur on cu.currency_id = cur.currency_id)
               on cu.customer_id = customer_link.customer_id
,      department_link,
       distributionpoint_link, businessunit processbu,
       businessunit invoicebu,
       reportparam rp,
       businessunit bu, plant pl
where  packingnoteline.packingnote_id = packingnote.packingnote_id
   and packingnote.status_id = st.status_id
   and st.statustype = 'PN'
   and st.code = '30'
   and packingnoteline.product_id = pc.pack_id
   and pc.product_id = product.product_id
   and pc.sizedefinition_id = sizedefinition.sizedefinition_id
   and pc.finishingmethod_id = finishingmethod.finishingmethod_id
   and packingnote.distributionpoint_id = distributionpoint_link.distributionpoint_id
   and distributionpoint_link.department_link_id = department_link.department_link_id
   and department_link.customer_link_id = customer_link.customer_link_id
   and packingnote.processbusinessunit_id = processbu.businessunit_id
   and packingnote.invoicebusinessunit_id = invoicebu.businessunit_id
   and (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 bu.plant_id = pl.plant_id

/
create or replace view V_DELIVEREDPRODUCTS_SGS
 (REPORTPARAM_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, INTERNALPRICE, DISCOUNT, PARENTPACKPRODUCT_LINK_ID, PARENTPRODUCT_LINK_ID, PROCESSBUCODE, PROCESSBUDESCRIPTION, INVOICEBUCODE, INVOICEBUDESCRIPTION, SYSTEMUSER_ID, TIMESTAMP, PRICE, VATRATE, DECIMALS, INVOICEAMOUNTDECIMALS, TAXABLE, DEFAULTBUSINESSUNIT_ID, CUSTOMERLANGUAGECODE, LANGUAGECODE, PRICEWITHDISCOUNT, DISCOUNTPERCENTAGE, Q, W, E, R, T, Y, U, PLANT_CODE
, PLANT_NAME, WIDTH_S, LENGTH_S, PURCHASEPRICE)
as SELECT RP.REPORTPARAM_ID,
       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,
       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,
       parentproduct.CODE parentproductcode,
       (SELECT E.DESCRIPTION FROM PRODUCT_LINK_DESC E WHERE E.PRODUCT_LINK_ID = DELIVERYHISTORY.PARENTPRODUCT_LINK_ID AND E.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) parentproductdescription,
       DELIVERYHISTORY.PACKINDICATION,
       pack.CODE packcode,
       (SELECT F.DESCRIPTION FROM PRODUCT_LINK_DESC F WHERE F.PRODUCT_LINK_ID = DELIVERYHISTORY.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,
       PRODUCT.THEORETICALWEIGHT, PRODUCT.typeofmerchandise, PRODUCT.MODEL,
       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,
       FINISHINGMETHOD.CODE finishingmethodcode,
       (SELECT D.DESCRIPTION FROM FINISHINGMETHOD_DESC D WHERE D.FINISHINGMETHOD_ID = DELIVERYHISTORY.FINISHINGMETHOD_ID AND D.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODdescription,
       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.PARENTPACKPRODUCT_LINK_ID, DELIVERYHISTORY.PARENTPRODUCT_LINK_ID,
       PROCESSBU.CODE processbucode, PROCESSBU.DESCRIPTION processbudescription, INVOICEBU.CODE invoicebucode,
       INVOICEBU.DESCRIPTION invoicebudescription, DELIVERYHISTORY.SYSTEMUSER_ID, DELIVERYHISTORY.TIMESTAMP,
       F_GETDELPRODPRICE(rp.number_value, cu.customer_id, product.product_id, SIZEDEFINITION_LINK.SIZEDEFINITION_ID,
         FINISHINGMETHOD.FINISHINGMETHOD_ID, rp.date_value1/*deliveryhistory.deliverydate*/,product.typeofmerchandise) price,
       F_GETVAT(rp.number_value, (CASE WHEN cu.taxable = 'Y' then cu.customer_id ELSE null END)
       , product.product_id, /*rp.number_value1*/ (CASE WHEN rp.number_value1 = -1 then cu.country_id ELSE rp.number_value1  END), cu.country_id, rp.date_value1/*deliveryhistory.deliverydate*/) vatrate,
       cur.decimals, cur.invoiceamountdecimals,
       cu.taxable, bu.businessunit_id defaultbusinessunit_id,
       CUSTOMER_LINK.LANGUAGECODE CUSTOMERLANGUAGECODE, LANGUAGES.CODE LANGUAGECODE,
       F_GETDELPRODPRICEWITHDISC(cu.customer_id, product.product_id, SIZEDEFINITION_LINK.SIZEDEFINITION_ID,
         FINISHINGMETHOD.FINISHINGMETHOD_ID, deliveryhistory.deliverydate, product.typeofmerchandise) PRICEWITHDISCOUNT,
       pack_price.Wash_Discount(cu.customer_id, product.product_id, SIZEDEFINITION_LINK.SIZEDEFINITION_ID,
         FINISHINGMETHOD.FINISHINGMETHOD_ID,deliveryhistory.deliverydate) DISCOUNTPERCENTAGE
         , rp.number_value q , cu.customer_id  w, product.product_id e, SIZEDEFINITION_LINK.SIZEDEFINITION_ID r,
         FINISHINGMETHOD.FINISHINGMETHOD_ID t, deliveryhistory.deliverydate y ,product.typeofmerchandise u
, pl.code Plant_Code, pl.name Plant_Name,
SIZEDEFINITION.WIDTH WIDTH_S,SIZEDEFINITION.LENGTH LENGTH_S--CSW,
,f_purchaseprice(PRODUCT.Supplier_Id,product.product_id,DELIVERYHISTORY.Sizedefinition_Link_Id,DELIVERYHISTORY.DELIVERYDATE) PURCHASEPRICE
 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,
      CUSTOMER_LINK
        left outer join customer cu          --left join country ctr on cu.country_id = ctr.country_id)
        on cu.customer_id = CUSTOMER_LINK.CUSTOMER_ID,
      DEPARTMENT_LINK, DISTRIBUTIONPOINT_LINK,
      SIZEDEFINITION_LINK,
      BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU, FINISHINGMETHOD, LANGUAGES,
      PRODUCT_LINK parentproduct, PRODUCT_LINK pack,
      PRODUCT_LINK
        LEFT OUTER JOIN PRODUCTGROUP ON (PRODUCT_LINK.PRODUCTGROUPCODE = PRODUCTGROUP.CODE),
      REPORTPARAM RP, currency cur, Businessunit BU, plant pl
 WHERE 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_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.PARENTPACKPRODUCT_LINK_ID = pack.PRODUCT_LINK_ID
  AND DELIVERYHISTORY.SIZEDEFINITION_LINK_ID = SIZEDEFINITION_LINK.SIZEDEFINITION_LINK_ID
  AND DELIVERYHISTORY.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND DELIVERYHISTORY.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  AND FINISHINGMETHOD.FINISHINGMETHOD_ID = DELIVERYHISTORY.FINISHINGMETHOD_ID
  AND PRODUCT.PRODUCT_ID = PRODUCTSIZE.PRODUCT_ID
  AND SIZEDEFINITION.SIZEDEFINITION_ID = PRODUCTSIZE.SIZEDEFINITION_ID
  and DELIVERYHISTORY.Currency_Id = cur.currency_id
  and (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 bu.plant_id = pl.plant_id

/
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_DELIVERIESPERWEEK_ECL
 (DATEACTIVE, DATEINACTIVE, CUSTOMER_ID)
as select rs.dateactive, rs.dateinactive, rs.customer_id
from routestop rs

/
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
  --DeliveryComparison.rpt

/
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 DELIVERYHISTORY.Processbusinessunit_Id, CUSTOMER_LINK.CUSTOMER_ID,
       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,
       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,
       parentproduct.CODE parentproductcode,
       (SELECT E.DESCRIPTION FROM PRODUCT_LINK_DESC E WHERE E.PRODUCT_LINK_ID = DELIVERYHISTORY.PARENTPRODUCT_LINK_ID AND E.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) parentproductdescription,
       DELIVERYHISTORY.PACKINDICATION,
       pack.CODE packcode,
       (SELECT F.DESCRIPTION FROM PRODUCT_LINK_DESC F WHERE F.PRODUCT_LINK_ID = DELIVERYHISTORY.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,
       PRODUCT.THEORETICALWEIGHT, PRODUCT.typeofmerchandise, PRODUCT.MODEL,
       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,
       FINISHINGMETHOD.CODE finishingmethodcode,
       (SELECT D.DESCRIPTION FROM FINISHINGMETHOD_DESC D WHERE D.FINISHINGMETHOD_ID = DELIVERYHISTORY.FINISHINGMETHOD_ID AND D.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODdescription,
       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.PARENTPACKPRODUCT_LINK_ID, DELIVERYHISTORY.PARENTPRODUCT_LINK_ID,
       PROCESSBU.CODE processbucode, PROCESSBU.DESCRIPTION processbudescription, INVOICEBU.CODE invoicebucode,
       INVOICEBU.DESCRIPTION invoicebudescription, DELIVERYHISTORY.SYSTEMUSER_ID, DELIVERYHISTORY.TIMESTAMP,
       CUSTOMER_LINK.LANGUAGECODE CUSTOMERLANGUAGECODE, 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),
      PRODUCTSIZE,
      CUSTOMER_LINK, DEPARTMENT_LINK, DISTRIBUTIONPOINT_LINK,
      SIZEDEFINITION_LINK,
      BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU, FINISHINGMETHOD, LANGUAGES,
      PRODUCT_LINK parentproduct, PRODUCT_LINK pack,
      PRODUCT_LINK
      LEFT OUTER JOIN PRODUCTGROUP ON (PRODUCT_LINK.PRODUCTGROUPCODE = PRODUCTGROUP.CODE)
 WHERE 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_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.PARENTPACKPRODUCT_LINK_ID = pack.PRODUCT_LINK_ID
  AND DELIVERYHISTORY.SIZEDEFINITION_LINK_ID = SIZEDEFINITION_LINK.SIZEDEFINITION_LINK_ID
  AND DELIVERYHISTORY.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND DELIVERYHISTORY.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  AND FINISHINGMETHOD.FINISHINGMETHOD_ID = DELIVERYHISTORY.FINISHINGMETHOD_ID
  AND PRODUCT.PRODUCT_ID = PRODUCTSIZE.PRODUCT_ID
  AND SIZEDEFINITION.SIZEDEFINITION_ID = PRODUCTSIZE.SIZEDEFINITION_ID

/
create or replace view V_DELIVERYHISTORY_BDM
 (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, INVOICEBU_ID, INVOICEBUCODE, INVOICEBUDESCRIPTION, SYSTEMUSER_ID, TIMESTAMP, CUSTOMERLANGUAGE_ID, LANGUAGECODE, LANGUAGE_ID, WIDTH_S, LENGTH_S, INVOICECLUSTER_CODE, DEFAULTINVOICEBUSINESSUNIT_ID)
as SELECT DELIVERYHISTORY.Processbusinessunit_Id, CUSTOMER.CUSTOMER_ID,
       CUSTOMER.CUSTOMERNUMBER, CUSTOMER.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,
       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,
       parentproduct.CODE parentproductcode,
       (SELECT E.DESCRIPTION FROM PRODUCT_LINK_DESC E WHERE E.PRODUCT_LINK_ID = DELIVERYHISTORY.PARENTPRODUCT_LINK_ID AND E.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) parentproductdescription,
       DELIVERYHISTORY.PACKINDICATION,
       pack.CODE packcode,
       (SELECT F.DESCRIPTION FROM PRODUCT_LINK_DESC F WHERE F.PRODUCT_LINK_ID = DELIVERYHISTORY.PARENTPACKPRODUCT_LINK_ID AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) packdescription,
       ' ' ACTIVITYCODE,
       PRODUCT.THEORETICALWEIGHT, PRODUCT.typeofmerchandise, PRODUCT.MODEL,
       PRODUCTSIZE.THEORETICALWEIGHT PRODSIZE_THEORETICALWEIGHT,
       SIZEDEFINITION.CODE sizecode,
       (SELECT C.DESCRIPTION FROM SIZEDEFINITION_DESC C WHERE C.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID AND C.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEdescription,
       FINISHINGMETHOD.CODE finishingmethodcode,
       (SELECT D.DESCRIPTION FROM FINISHINGMETHOD_DESC D WHERE D.FINISHINGMETHOD_ID = DELIVERYHISTORY.FINISHINGMETHOD_ID AND D.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODdescription,
       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.PARENTPACKPRODUCT_LINK_ID, DELIVERYHISTORY.PARENTPRODUCT_LINK_ID,
       PROCESSBU.CODE processbucode, PROCESSBU.DESCRIPTION processbudescription, INVOICEBU.Businessunit_Id invoicebu_ID, INVOICEBU.CODE invoicebucode,
       INVOICEBU.DESCRIPTION invoicebudescription, DELIVERYHISTORY.SYSTEMUSER_ID, DELIVERYHISTORY.TIMESTAMP,
       CUSTOMER.Language_Id CUSTOMERLANGUAGE_ID, LANGUAGES.CODE LANGUAGECODE, LANGUAGES.Language_Id,
       SIZEDEFINITION.WIDTH WIDTH_S, SIZEDEFINITION.LENGTH LENGTH_S--CSW
, (select min(cc.code) from customerspercluster cpc, customercluster cc where cpc.cluster_id = cc.cluster_id and cpc.customer_id = customer.customer_id) InvoiceCluster_Code
, customer.defaultinvoicebusinessunit_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,
      CUSTOMER, DEPARTMENT_LINK, DISTRIBUTIONPOINT_LINK,
      BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU, FINISHINGMETHOD, LANGUAGES,
      PRODUCT_LINK parentproduct, PRODUCT_LINK pack,
      PRODUCT_LINK
      LEFT OUTER JOIN PRODUCTGROUP ON (PRODUCT_LINK.PRODUCTGROUPCODE = PRODUCTGROUP.CODE)
WHERE 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 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.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND DELIVERYHISTORY.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  AND FINISHINGMETHOD.FINISHINGMETHOD_ID = DELIVERYHISTORY.FINISHINGMETHOD_ID
  AND PRODUCT.PRODUCT_ID = PRODUCTSIZE.PRODUCT_ID
  AND SIZEDEFINITION.SIZEDEFINITION_ID = PRODUCTSIZE.SIZEDEFINITION_ID
union all
SELECT wo.businessunit_id Processbusinessunit_Id, CUSTOMER.CUSTOMER_ID,
       CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME customername,
       DEPARTMENT_LINK.DEPARTMENTNUMBER, DEPARTMENT_LINK.DESCRIPTION departmentdescription,
       DISTRIBUTIONPOINT_LINK.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT_LINK.DESCRIPTION distributionpointdescription,
       'DIVERS / VENTE' productgroupcode,
       ' ' productgroupdescription,
       PRODUCT.CODE productcode,
       (SELECT B.DESCRIPTION FROM PRODUCT_DESC B WHERE B.PRODUCT_ID = PRODUCT.PRODUCT_ID AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
       product.CODE parentproductcode,
       (SELECT E.DESCRIPTION FROM PRODUCT_DESC E WHERE E.PRODUCT_ID = PRODUCT.PRODUCT_ID AND E.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) parentproductdescription,
       0 PACKINDICATION, ' ' packcode, ' ' packdescription, ' ' ACTIVITYCODE,
       PRODUCT.THEORETICALWEIGHT, PRODUCT.typeofmerchandise, PRODUCT.MODEL,
       PRODUCTSIZE.THEORETICALWEIGHT PRODSIZE_THEORETICALWEIGHT,
       SIZEDEFINITION.CODE sizecode,
       (SELECT C.DESCRIPTION FROM SIZEDEFINITION_DESC C WHERE C.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID AND C.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEdescription,
       FINISHINGMETHOD.CODE finishingmethodcode,
       (SELECT D.DESCRIPTION FROM FINISHINGMETHOD_DESC D WHERE D.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID AND D.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODdescription,
       wo.requestdate DELIVERYDATE, year(wo.requestdate)*100 + castvarcharasnumber(getweeknumber(wo.requestdate)) YEARWEEK,
      castvarcharasnumber(getweeknumber(wo.requestdate)) WEEK, year(wo.requestdate) year,
       month(wo.requestdate) realmonth,
       year(wo.requestdate) realyear,
       getabsdaynumber(wo.requestdate) DAYNUMBER,
       (wol.quantityordered - wol.quantitycancelled) AMOUNTORDERED, (wol.quantityordered - wol.quantitycancelled) AMOUNTDELIVERED,
       0 AMOUNTSHORTAGE, wol.salesprice price,
        wol.salesprice INTERNALPRICE, wol.discountpercentage DISCOUNT,
       -1 PARENTPACKPRODUCT_LINK_ID, -1 PARENTPRODUCT_LINK_ID,
       PROCESSBU.CODE processbucode, PROCESSBU.DESCRIPTION processbudescription, INVOICEBU.Businessunit_Id invoicebu_ID, INVOICEBU.CODE invoicebucode,
       INVOICEBU.DESCRIPTION invoicebudescription, wol.SYSTEMUSER_ID, wol.timestamp,
       CUSTOMER.Language_Id CUSTOMERLANGUAGE_ID, LANGUAGES.CODE LANGUAGECODE, LANGUAGES.Language_Id,
       SIZEDEFINITION.WIDTH WIDTH_S, SIZEDEFINITION.LENGTH LENGTH_S--CSW
, (select min(cc.code) from customerspercluster cpc, customercluster cc where cpc.cluster_id = cc.cluster_id and cpc.customer_id = customer.customer_id) InvoiceCluster_Code
, customer.defaultinvoicebusinessunit_id
FROM workorder wo, workorderline wol, PRODUCT, SIZEDEFINITION, PRODUCTSIZE, FINISHINGMETHOD,
     CUSTOMER, DEPARTMENT_LINK, DISTRIBUTIONPOINT_LINK, BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU, LANGUAGES
WHERE wo.workorder_id = wol.workorder_id
      and wol.product_link_id = PRODUCT.PRODUCT_ID
      and wol.sizedefinition_link_id = SIZEDEFINITION.SIZEDEFINITION_ID
      AND PRODUCT.PRODUCT_ID = PRODUCTSIZE.PRODUCT_ID
      AND SIZEDEFINITION.SIZEDEFINITION_ID = PRODUCTSIZE.SIZEDEFINITION_ID
      AND wol.finishingmethod_id = FINISHINGMETHOD.FINISHINGMETHOD_ID
      and wo.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 wo.businessunit_id = PROCESSBU.BUSINESSUNIT_ID
      AND wo.invoicebusinessunit_id = INVOICEBU.BUSINESSUNIT_ID
      AND wo.origin = 6 --SalesNote

/
create or replace view V_DELIVERYHISTORY_BUB
 (PROCESSBUSINESSUNIT_ID, CUSTOMER_ID, REPORTPARAM_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 DELIVERYHISTORY.Processbusinessunit_Id, CUSTOMER_LINK.CUSTOMER_ID, rp.reportparam_id,
       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,
       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,
       parentproduct.CODE parentproductcode,
       (SELECT E.DESCRIPTION FROM PRODUCT_LINK_DESC E WHERE E.PRODUCT_LINK_ID = DELIVERYHISTORY.PARENTPRODUCT_LINK_ID AND E.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) parentproductdescription,
       DELIVERYHISTORY.PACKINDICATION,
       pack.CODE packcode,
       (SELECT F.DESCRIPTION FROM PRODUCT_LINK_DESC F WHERE F.PRODUCT_LINK_ID = DELIVERYHISTORY.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,
       PRODUCT.THEORETICALWEIGHT, PRODUCT.typeofmerchandise, PRODUCT.MODEL,
       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,
       FINISHINGMETHOD.CODE finishingmethodcode,
       (SELECT D.DESCRIPTION FROM FINISHINGMETHOD_DESC D WHERE D.FINISHINGMETHOD_ID = DELIVERYHISTORY.FINISHINGMETHOD_ID AND D.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODdescription,
       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,
      -- nvl(PACK_PRICE.Wash_Price(CUSTOMER_LINK.Customer_Link_Id, DELIVERYHISTORY.PRODUCT_LINK_ID, DELIVERYHISTORY.SIZEDEFINITION_LINK_ID, DELIVERYHISTORY.Finishingmethod_Id, DELIVERYHISTORY.deliverydate, 0), DELIVERYHISTORY.PRICE) Price,
             F_GETDELPRODPRICE(1, CUSTOMER_LINK.Customer_Link_Id, DELIVERYHISTORY.PRODUCT_LINK_ID,  DELIVERYHISTORY.SIZEDEFINITION_LINK_ID,
          DELIVERYHISTORY.Finishingmethod_Id, rp.date_value1,product.typeofmerchandise) price,
      DELIVERYHISTORY.INTERNALPRICE, DELIVERYHISTORY.DISCOUNT,
       DELIVERYHISTORY.PARENTPACKPRODUCT_LINK_ID, DELIVERYHISTORY.PARENTPRODUCT_LINK_ID,
       PROCESSBU.CODE processbucode, PROCESSBU.DESCRIPTION processbudescription, INVOICEBU.CODE invoicebucode,
       INVOICEBU.DESCRIPTION invoicebudescription, DELIVERYHISTORY.SYSTEMUSER_ID, DELIVERYHISTORY.TIMESTAMP,
       CUSTOMER_LINK.LANGUAGECODE CUSTOMERLANGUAGECODE, 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),
      PRODUCTSIZE,
      CUSTOMER_LINK, DEPARTMENT_LINK, DISTRIBUTIONPOINT_LINK,
      SIZEDEFINITION_LINK,
      BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU, FINISHINGMETHOD, LANGUAGES,
      PRODUCT_LINK parentproduct, PRODUCT_LINK pack,
      PRODUCT_LINK
      LEFT OUTER JOIN PRODUCTGROUP ON (PRODUCT_LINK.PRODUCTGROUPCODE = PRODUCTGROUP.CODE), reportparam rp
 WHERE 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_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.PARENTPACKPRODUCT_LINK_ID = pack.PRODUCT_LINK_ID
  AND DELIVERYHISTORY.SIZEDEFINITION_LINK_ID = SIZEDEFINITION_LINK.SIZEDEFINITION_LINK_ID
  AND DELIVERYHISTORY.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND DELIVERYHISTORY.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  AND FINISHINGMETHOD.FINISHINGMETHOD_ID = DELIVERYHISTORY.FINISHINGMETHOD_ID
  AND PRODUCT.PRODUCT_ID = PRODUCTSIZE.PRODUCT_ID
  AND SIZEDEFINITION.SIZEDEFINITION_ID = PRODUCTSIZE.SIZEDEFINITION_ID

/
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, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERSTREET2, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, CUSTOMERCOUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION
, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, 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, WOREFNUMBER, DELIVERYNOTEREMARKDESC)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME,
ADDRESS.STREET CUSTOMERSTREET, ADDRESS.STREET2 CUSTOMERSTREET2,  ADDRESS.ZIPCODE CUSTOMERZIP, ADDRESS.CITY CUSTOMERCITY, ADDRESS.STATE CUSTOMERSTATE,
C1.CODE CUSTCOUNTRY, C1.DESCRIPTION CUSTCOUNTRY_DESC, ADDRESS.COUNTY CUSTOMERCOUNTY,
DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
PACKINGNOTE.SEQUENCENUMBER,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, --CAST(
PACKINGNOTE.REMARK --AS VARCHAR2(60) ) REMARK
, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL, --ORDER 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
cast (SS.VALUE as varchar2(60)) WEIGHTUNIT,
cast (SS1.VALUE as varchar2(1)) PRINTDELNOTEPERCONTAINER,
cast (SS2.VALUE as varchar2(1)) CONTAINERRECORDINGACTIVE,
cast (SS3.VALUE as varchar2(1)) PRINTDELNOTEZEROLINES,
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(60)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
      ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
coalesce((SELECT count(PNC.PACKINGNOTE_ID) FROM PACKINGNOTECONTAINER PNC
   LEFT OUTER JOIN CONTAINER C ON C.CONTAINER_ID = PNC.CONTAINER_ID
   LEFT OUTER JOIN CONTAINERTYPE CT ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   LEFT OUTER JOIN WEIGHINGCATEGORY W ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID),0) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC
, coalesce((select max(ds.packingnote_id)
                 from   deliveryscan ds
                 where  ds.packingnote_id = packingnote.packingnote_id),
                 (select max(o.packingnote_id)
                   from   outofcirculationhistory o
                   where  o.packingnote_id = packingnote.packingnote_id), 0) numberofpossiblelineswithscans
, PACKINGNOTE.YEAR YEAR
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.REFERENCENUMBER
, INVOICEBU.INTERNALVATNUMBER
, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE
, ROUTE.PUTUPREPORTPERCUSTOMER
, customer.signaturerequired
, dsig.personidentification personidentification
, dsig.signature signature
, (select rc.drivingdate from routecontrol rc where rc.routecontrol_id = stop.routecontrol_id) signaturedate
, to_char(stop.departuretime,'fmhhfm:MI:AM') signaturetime
, to_char(stop.departuretime,'fmhh24fm:MI') signaturetime24
, packingnote.distributionpoint_id
, packingnote.processbusinessunit_id
, DELIVERYPOINT. SIGNATUREBARCODE
, cast ((SELECT SS.VALUE FROM SYSTEMSETTING SS WHERE SS.PLANT_ID=PLANT.PLANT_ID AND SS.NAME ='CONTAINERTYPEUNQBRCLABEL')  as varchar2(60)) containertypedescription
, (select max(wo.referencenumber) from deliveryscan ds, issuehistory ih, workorder wo
where ds.uniqueitem_link_id = ih.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 ih.workorder_id = wo.workorder_id
and ds.packingnote_id = packingnote.packingnote_id
and wo.deliverfrom=2
) worefnumber,
(select dnrd.description from deliverynoteremark_desc dnrd where dnrd.deliverynoteremark_id = packingnote.deliverynoteremark_id
        and dnrd.language_id = customer.language_id) deliverynoteremarkdesc
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,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        PACKINGNOTE
          LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
          LEFT OUTER JOIN ROUTE ON (PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID)
          LEFT OUTER JOIN STOP ON (PACKINGNOTE.STOP_ID = STOP.STOP_ID)
          left outer join deliverysignature dsig on (dsig.stop_id = packingnote.stop_id and dsig.stop_id=packingnote.deliverysignature_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 STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20 or (packingnote.origin = 14 and status.code = 40))
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID

/
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
, LANGUAGECODE, DEP_NUMBER, DEP_DESCRIPTION, FREEOFCHARGEREASON_ID, PRICEFACTOR)
as select 1 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,
           (select prd.code
              from product prd
             where pnl.product_id = prd.product_id)) customcode,
       nvl(pnl.customdescription,
           (select product_desc.description
              from product_desc
             where product_desc.product_id = pnl.product_id
               and product_desc.language_id = languages.language_id)) customdesc,
       (select sz.code
          from sizedefinition sz
         where pnl.sizedefinition_id = sz.sizedefinition_id) sizecode,
       pnl.deliveredamount,
       pnl.packingnoteline_id,
       (select sum(packingnotecontainer.grossweight -
                   packingnotecontainer.tareweight)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id
         group by pn.packingnote_id) weight,
       (select max(packingnotecontainer.weightdecimals)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id) weightdecimals,
       coalesce(
         pnl.price
         , pack_price.Wash_Price(dep.customer_id, pnl.product_id, pnl.sizedefinition_id, pnl.finishingmethod_id, pn.deliverydate)
         /*, (select max(l.price)
               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 = '*'))*/)price,
       (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 = '*'))) discountpercentage, -- total, to be calculated in the report!
       currency.code currencycode,
       currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals,
       0 pnnotininvoice,
       pn.remark,
       (select ss.value
          from systemsetting ss
         where plant.plant_id = ss.plant_id
           and ss.name = 'WEIGHTUNIT') weightunit,
       languages.code languagecode,
       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
  from invoiceheader     ih,
       packingnoteline   pnl,
       product p,
       packingnote       pn,
       distributionpoint cons,
       department        dep,
       currency,
       status            statuspn,
       status            statusih,
       businessunit      processbu,
       plant,
       languages
 where ih.invoiceheader_id = pnl.invoiceheader_id
   and ih.documenttype = 1
   and ih.status_id = statusih.status_id
   and statusih.statustype = 'IN'
   and pnl.packingnote_id = pn.packingnote_id
   and pnl.product_id=p.product_id
   and p.typeofmerchandise<> 3
   and pn.status_id = statuspn.status_id
   and statuspn.statustype = 'PN'
   and statuspn.code = '30'
   and pn.distributionpoint_id = cons.distributionpoint_id
   and cons.department_id = dep.department_id
   and ih.currency_id = currency.currency_id
   and pn.processbusinessunit_id = processbu.businessunit_id
   and processbu.plant_id = plant.plant_id
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(packingnotecontainer.grossweight - packingnotecontainer.tareweight)
         from   packingnotecontainer
         where  pn.packingnote_id = packingnotecontainer.packingnote_id
         group  by pn.packingnote_id) weight,
       pnc.weightdecimals,
       0 price,
       0 discountpercentage,       -- total, to be calculated in the report!
       currency.code currencycode, currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals, 0 pnnotininvoice, pn.remark,
       (select ss.value from systemsetting ss where plant.plant_id = ss.plant_id and ss.name = 'WEIGHTUNIT') weightunit,
			 languages.code languagecode, dep.departmentnumber dep_number,
       dep.description dep_description, pn.freeofchargereason_id,
       1 pricefactor
from   invoiceheader ih, packingnote pn, packingnotecontainer pnc, distributionpoint cons, department dep,
       currency, status statuspn, status statusih,
       businessunit processbu, plant, languages
where  ih.invoiceheader_id = pnc.invoiceheader_id
and    pnc.packingnote_id = pn.packingnote_id
and    ih.documenttype = 1
and    ih.status_id = statusih.status_id
and    statusih.statustype = 'IN'
and    pn.status_id = statuspn.status_id
and    statuspn.statustype = 'PN'
and    statuspn.code = '30'
and    pn.distributionpoint_id = cons.distributionpoint_id
and    cons.department_id = dep.department_id
and    ih.currency_id = currency.currency_id
and    pn.processbusinessunit_id = processbu.businessunit_id
and    processbu.plant_id = plant.plant_id
and not exists (select 1 from packingnoteline pnl where pnl.packingnote_id = pn.packingnote_id)
union all-- sales items
select 3 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,
           (select prd.code
              from product prd
             where pnl.product_id = prd.product_id)) customcode,
       nvl(pnl.customdescription,
           (select product_desc.description
              from product_desc
             where product_desc.product_id = pnl.product_id
               and product_desc.language_id = languages.language_id)) customdesc,
       (select sz.code
          from sizedefinition sz
         where pnl.sizedefinition_id = sz.sizedefinition_id) sizecode,
       pnl.deliveredamount,
       pnl.packingnoteline_id,
       (select sum(packingnotecontainer.grossweight -
                   packingnotecontainer.tareweight)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id
         group by pn.packingnote_id) weight,
       (select max(packingnotecontainer.weightdecimals)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id) weightdecimals,
       coalesce(
         pnl.price
         , pack_price.Wash_Price(dep.customer_id, pnl.product_id, pnl.sizedefinition_id, pnl.finishingmethod_id, pn.deliverydate)
         /*, (select max(l.price)
             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 = 5
             and (ilp.sizedefinition_link_id = pnl.sizedefinition_id or
                  ilp.sizedefinition_link_id =
                  (select sizedefinition.sizedefinition_id
                     from sizedefinition
                     where sizedefinition.code = '*')))*/) price,
       0 discountpercentage, -- total, to be calculated in the report!
       currency.code currencycode,
       currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals,
       0 pnnotininvoice,
       pn.remark,
       (select ss.value
          from systemsetting ss
         where plant.plant_id = ss.plant_id
           and ss.name = 'WEIGHTUNIT') weightunit,
       languages.code languagecode,
       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
  from invoiceheader     ih,
       packingnoteline   pnl,
       product           p,
       packingnote       pn,
       distributionpoint cons,
       department        dep,
       currency,
       status            statuspn,
       status            statusih,
       businessunit      processbu,
       plant,
       languages
 where ih.invoiceheader_id = pnl.invoiceheader_id
   and ih.documenttype = 1
   and ih.status_id = statusih.status_id
   and statusih.statustype = 'IN'
   and pnl.packingnote_id = pn.packingnote_id
   and pnl.product_id=p.product_id
   and p.typeofmerchandise = 3
   and pn.status_id = statuspn.status_id
   and statuspn.statustype = 'PN'
   and statuspn.code = '30'
   and pn.distributionpoint_id = cons.distributionpoint_id
   and cons.department_id = dep.department_id
   and ih.currency_id = currency.currency_id
   and pn.processbusinessunit_id = processbu.businessunit_id
   and processbu.plant_id = plant.plant_id

/
create or replace view V_DELIVERYNOTEAPPENDIX_BDE
 (DELNUMBER, STREET, ZIPCODE, HOUSENUMBER, HOUSENUMBEREXT, DELNAME, DELTOCITY, CONTACTPERSONNAME, INVOICECOMMENTS, DELTOSTREET, DELTOZIPCODE, DELTOCOUNTRYDESCRIPTION, CITY, COUNTY, STATE, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, INVOICEDATE, DECIMALS, INVOICEHEADER_ID, INVOICENUMBER, PACKINGNOTE_ID, NOTENUMBER, DELIVERYDATE, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESC, PRODUCTCODE, CUSTOMCODE, CUSTOMDESC, PRODUCTDESCRIPTION, SIZECODE, SIZEDESC, DELIVEREDAMOUNT, FINMETHCODE
, FINMETHDESC, WEIGHT, WEIGHTDECIMALS, PRICE, DISCOUNTPERCENTAGE, TOTAL, CURRENCYCODE, PRICEDECIMALS, INVOICEDECIMALS, PNNOTININVOICE, REMARK, WEIGHTUNIT, LANGUAGECODE, DEP_NUMBER, DEP_DESCRIPTION, FREEOFCHARGEREASON_ID, PROCESSBU_CODE, PROCESSBU_DESC, PROCESSBU_PHONE, PROCESSBU_FAX, INV_BU_CODE, EXTRANAME2, NEXTPERIODSTARTDATE, INVOICEFREQUENCYNUMBER, PARENTINVOICEHEADER_ID, INVOICELAYOUTCODE, BILLTOCOUNTRYDESCRIPTION, PRICEFACTOR, CONSIGNMENTNOTE_ID, CONSIGNMENTNOTENUMBER
)
as select -- 1 -- PN with PNL and with Prices
      coalesce(ih.deltocustomernumber, ih.billtocustomernumber ) delnumber
     , ih.street
     , ih.zipcode
     , ih.HOUSENUMBER
     , ih.HOUSENUMBEREXT
     , coalesce(ih.deltocustomername, ih.billtocustomername) delname
     , ih.deltocity
     , ih.CONTACTPERSONNAME
     , ih.invoicecomments
     , ih.deltostreet
     , ih.deltozipcode
     , ihe.deltocountrydescription
     , ih.city
     , ih.county
     , ih.state
     , ih.billtocustomernumber
     , ih.billtocustomername
     , ih.invoicedate
     , currency.decimals
     , ih.invoiceheader_id
     , ih.invoicenumber
     , pn.packingnote_id
     , pn.notenumber
     , pn.deliverydate
, cons.distributionpointnumber, cons.description distributionpointDesc
, prd.code ProductCode
, il.code CustomCode, il.description CustomDesc
, ( select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) ProductDescription
, ilp.sizecode SizeCode
, (select szd.description from sizedefinition_desc szd where pnl.sizedefinition_id = szd.sizedefinition_id and szd.language_id = languages.language_id) SizeDesc
, pnl.deliveredamount
, ilp.finishingmethodcode FinMethCode
, (select fmd.description from finishingmethod_desc fmd where pnl.finishingmethod_id = fmd.finishingmethod_id and fmd.language_id = languages.language_id) FinMethDesc
, ( select sum(packingnotecontainer.grossweight - packingnotecontainer.tareweight) from packingnotecontainer where pn.packingnote_id = packingnotecontainer.packingnote_id
  group by pn.packingnote_id) Weight
, pnc.weightdecimals weightdecimals
, il.price , il.discountpercentage, coalesce((pnl.deliveredamount*il.price*(1-il.discountpercentage/100)),0) Total
, currency.code currencyCode, currency.decimals PriceDecimals, currency.invoiceamountdecimals InvoiceDecimals
, 0 PnNotInInvoice, pn.remark, SS.VALUE WEIGHTUNIT, languages.code languageCode
, dep.departmentnumber dep_number, dep.description dep_description
, PN.FREEOFCHARGEREASON_ID
, PROCESSBU.Code PROCESSBU_code, PROCESSBU.Description PROCESSBU_desc
, PLANT.Phoneno PROCESSBU_phone, PLANT.Faxno PROCESSBU_fax
, (select ibu.code from businessunit ibu where ibu.businessunit_id=pn.invoicebusinessunit_id) Inv_bu_code
, ih.extraname2, ih.nextperiodstartdate, ih.invoicefrequency_id invoicefrequencynumber, ih.parentinvoiceheader_id
, ihe.formlayoutcode INVOICELAYOUTCODE, ihe.billtocountrydescription
, ilp.pricefactor
, pn.consignmentnote_id
, cn.consignmentnotenumber
from Packingnote pn
left outer join packingnotecontainer pnc
           on pn.packingnote_id = pnc.packingnote_id
left outer join consignmentnote cn on pn.consignmentnote_id = cn.consignmentnote_id
   , Packingnoteline pnl
   , distributionpoint cons
   , department dep
   , invoiceheader ih
   , invoiceline il
   , product prd
   , sizedefinition sz
   , invoicelineproduct ilp
   , currency
   , status statusPN
   , status statusIH
   , businessunit PROCESSBU
   , PLANT
   , systemsetting ss
   , languages
   , invoiceheaderextrainfo ihe
where
    pn.status_id = statusPN.status_id
    and statusPN.statustype = 'PN'
        and statusPN.code = '30'
and pn.distributionpoint_id = cons.distributionpoint_id
and cons.department_id = dep.department_id
and pnl.invoiceheader_id = ih.invoiceheader_id
    and ih.documenttype = 1
    and ih.status_id = statusIH.Status_Id
        and statusIH.Statustype = 'IN' -- and statusIH.Code = '2'
and ih.invoiceheader_id = il.invoiceheader_id
and il.code = coalesce(pnl.customcode,prd.code)
and il.invoicelinetype_id in (select ilt.invoicelinetype_id from  invoicelinetype ilt where
                            ilt.type = case prd.typeofmerchandise
                                            when 3 then 5 else 2 end )
/*and il.linenumber = (select max(invoiceline.linenumber) from invoiceline
                            where invoiceline.invoiceheader_id= il.invoiceheader_id
                                  and invoiceline.invoicelinetype_id = il.invoicelinetype_id
                                  and invoiceline.code = il.code )*/
and ih.currency_id = currency.currency_id
and pnl.packingnote_id = pn.packingnote_id
    and pnl.product_id = prd.product_id
    and pnl.sizedefinition_id = sz.sizedefinition_id
and ilp.product_link_id = pnl.product_id
-------- MBA todo 7769 - the old condition return the chartesian product between pnl and ilh when in ilh size * replace specific sizez from pnl
/*    and pnl.sizedefinition_id = case ilp.sizedefinition_link_id when (select sizedefinition.sizedefinition_id from sizedefinition where sizedefinition.code = '*')
                                     then pnl.sizedefinition_id else ilp.sizedefinition_link_id end
*/
and ilp.sizedefinition_link_id = coalesce((select ilp1.sizedefinition_link_id from invoicelineproduct ilp1
    where ilp1.product_link_id = pnl.product_id
    and ilp1.sizedefinition_link_id = pnl.sizedefinition_id
    and ilp1.invoiceline_id in (select il1.invoiceline_id from invoiceline il1
                                       where il1.invoiceheader_id = ih.invoiceheader_id
                                       and il1.invoicelinetype_id in
                                         (select ilt.invoicelinetype_id from invoicelinetype ilt where ilt.type = case prd.typeofmerchandise
                                            when 3 then 5 else 2 end))  and rownum = 1),
                                (select sizedefinition.sizedefinition_id from sizedefinition where sizedefinition.code = '*'))
-------- end todo 7769
        and ilp.invoiceline_id = il.invoiceline_id
AND pn.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
    AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
        AND PLANT.PLANT_ID = SS.PLANT_ID
            AND SS.NAME = 'WEIGHTUNIT'
and ihe.invoiceheader_id = ih.invoiceheader_id
and il.price = case (select ss1.value from systemsetting ss1 where ss1.name like 'INVPRICEDETERMMETHOD' and ss1.plant_id = plant.plant_id)
               when '0' then (f_getdelprodprice(1, ih.deltocustomer_link_id, pnl.product_id, pnl.sizedefinition_id, pnl.finishingmethod_id, ih.invoicedate, prd.typeofmerchandise))
               else (f_getdelprodprice(1, ih.deltocustomer_link_id, pnl.product_id, pnl.sizedefinition_id, pnl.finishingmethod_id, TRUNC(pn.deliverydate,'D')+6, prd.typeofmerchandise))
               end
UNION
select -- 2 -- PN with PNL and NO Prices
  coalesce(ih.deltocustomernumber, ih.billtocustomernumber ) delnumber, ih.street, ih.zipcode, ih.HOUSENUMBER, ih.HOUSENUMBEREXT
, coalesce(ih.deltocustomername, ih.billtocustomername) delname, ih.deltocity, ih.CONTACTPERSONNAME, ih.invoicecomments
, ih.deltostreet, ih.deltozipcode, ihe.deltocountrydescription
, ih.city, ih.county, ih.state, ih.billtocustomernumber, ih.billtocustomername, ih.invoicedate, currency.decimals
, ih.invoiceheader_id, ih.invoicenumber, pn.packingnote_id, pn.notenumber, pn.deliverydate
, cons.distributionpointnumber, cons.description distributionpointDesc
, prd.code ProductCode , COALESCE(pnl.customcode, prd.code) CustomCode
, coalesce(pnl.customdescription
, (select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id )
  ) CustomDesc
, (select product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) ProductDescription, sz.code SizeCode
, (select szd.description from sizedefinition_desc szd where pnl.sizedefinition_id = szd.sizedefinition_id and szd.language_id = languages.language_id) SizeDesc
, pnl.deliveredamount
, fm.code FinMethCode
, (select fmd.description from finishingmethod_desc fmd where pnl.finishingmethod_id = fmd.finishingmethod_id and fmd.language_id = languages.language_id) FinMethDesc
, ( select sum(packingnotecontainer.grossweight - packingnotecontainer.tareweight) from packingnotecontainer where pn.packingnote_id = packingnotecontainer.packingnote_id
  group by pn.packingnote_id) Weight
, pnc.weightdecimals weightdecimals
, 0 price , 0 discountpercentage, 0 Total, currency.code currencyCode, currency.decimals PriceDecimals, currency.invoiceamountdecimals InvoiceDecimals
, 1 PnNotInInvoice, pn.remark, SS.VALUE WEIGHTUNIT, languages.code languageCode
, dep.departmentnumber dep_number, dep.description dep_description
, PN.FREEOFCHARGEREASON_ID
, PROCESSBU.Code PROCESSBU_code, PROCESSBU.Description PROCESSBU_desc
, PLANT.Phoneno PROCESSBU_phone, PLANT.Faxno PROCESSBU_fax
, (select ibu.code from businessunit ibu where ibu.businessunit_id=pn.invoicebusinessunit_id) Inv_bu_code
, ih.extraname2, ih.nextperiodstartdate, ih.invoicefrequency_id invoicefrequencynumber, ih.parentinvoiceheader_id
, ihe.formlayoutcode INVOICELAYOUTCODE, ihe.billtocountrydescription
--, (select max(emp.name) from employee emp where exists (select * from customer cust where cust.defaultbusinessunit_id = PROCESSBU.businessunit_id and cust.serviceemployee_id = emp.employee_id)) ContactPerson_name
, 0 pricefactor
, pn.consignmentnote_id
, cn.consignmentnotenumber
from
  Packingnote pn
    left outer join Packingnoteline pnl on pnl.packingnote_id = pn.packingnote_id
    left outer join packingnotecontainer pnc -- left outer join weighingcategory wgh on pnc.weighingcategory_id = wgh.weighingcategory_id)
           on pn.packingnote_id = pnc.packingnote_id
left outer join consignmentnote cn on pn.consignmentnote_id = cn.consignmentnote_id
, product prd, status statusPN, status statusIH, invoiceheader ih, businessunit PROCESSBU, PLANT, systemsetting ss
, distributionpoint cons, department dep, sizedefinition sz, languages
, invoiceheaderextrainfo ihe, currency, finishingmethod fm
where
    pn.status_id = statusPN.status_id
    and statusPN.statustype = 'PN'
        and statusPN.code = '30'
and pn.distributionpoint_id = cons.distributionpoint_id
and cons.department_id = dep.department_id
and pnl.invoiceheader_id = ih.invoiceheader_id
and ihe.invoiceheader_id = ih.invoiceheader_id
    and ih.documenttype = 1
and ih.status_id = statusIH.Status_Id
    and statusIH.Statustype = 'IN'
        -- and statusIH.Code = '2'
and pnl.product_id = prd.product_id
and pnl.sizedefinition_id = sz.sizedefinition_id
and pnl.finishingmethod_id = fm.finishingmethod_id
and CONCATENATE(coalesce(pnl.customcode, prd.code), sz.code) not in
     ( select CONCATENATE(il.code, case ilp.sizecode when '*' then sz.code else ilp.sizecode end)
              from invoiceline il, invoicelineproduct ilp
              where ih.invoiceheader_id = il.invoiceheader_id
              and il.code = coalesce(pnl.customcode,prd.code)
              and il.invoicelinetype_id = (select ilt.invoicelinetype_id from  invoicelinetype ilt where
                                                  ilt.type = case prd.typeofmerchandise
                                                                  when 3 then 5 else 2 end )
              and il.linenumber = (select max(il0.linenumber)
		                   from invoiceline il0
				       , invoicelineproduct ilp0
                                   where il0.invoiceheader_id= il.invoiceheader_id
				     and il0.invoiceline_id = ilp0.invoiceline_id
				     and pnl.product_id = ilp0.product_link_id
				     and pnl.sizedefinition_id = ilp0.sizedefinition_link_id
				     and pnl.finishingmethod_id = ilp0.finishingmethod_id
                                     and il0.invoicelinetype_id = il.invoicelinetype_id
                                     and il0.code = il.code
		                   )
              and il.invoiceline_id = ilp.invoiceline_id
              and ilp.product_link_id = prd.product_id
              --and pnl.sizedefinition_id = ilp.sizedefinition_link_id
              )
AND pn.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
    AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
        AND PLANT.PLANT_ID = SS.PLANT_ID
            AND SS.NAME = 'WEIGHTUNIT'
and ih.currency_id = currency.currency_id
/*
BDE will have only PN with lines --and prices
UNION
select -- 3 -- PN without PNL and with Prices
  coalesce(ih.deltocustomernumber, ih.billtocustomernumber ) delnumber, ih.street, ih.zipcode, ih.HOUSENUMBER, ih.HOUSENUMBEREXT
, coalesce(ih.deltocustomername, ih.billtocustomername) delname, ih.CONTACTPERSONNAME
, ih.city, ih.county, ih.state, ih.billtocustomernumber, ih.billtocustomername, ih.invoicedate
, ih.invoiceheader_id, ih.invoicenumber, pn.packingnote_id, pn.notenumber, pn.deliverydate, cons.distributionpointnumber
, cons.description distributionpointDesc, ' ' ProductCode , ' ' CustomCode, ' ' CustomDesc
, ' ' ProductDescription, ' ' SizeCode, 0 deliveredamount
, ( select sum(packingnotecontainer.grossweight - packingnotecontainer.tareweight) from packingnotecontainer where pn.packingnote_id = packingnotecontainer.packingnote_id
  group by pn.packingnote_id) Weight
, pnc.weightdecimals weightdecimals /*
, wgh.code weighingcategoryCode
, ( select weighingcategory_desc.description from weighingcategory_desc where weighingcategory_desc.weighingcategory_id = wgh.weighingcategory_id
  and weighingcategory_desc.language_id = languages.language_id ) weighingcategoryDesc * /
, il.price price , il.discountpercentage
, coalesce(((pnc.grossweight - pnc.tareweight)*il.price*(1-il.discountpercentage/100)), 0) Total
, currency.code currencyCode, currency.decimals PriceDecimals, currency.invoiceamountdecimals InvoiceDecimals
, 0 PnNotInInvoice, pn.remark, SS.VALUE WEIGHTUNIT, languages.code languageCode
, dep.departmentnumber dep_number, dep.description dep_description
, PN.FREEOFCHARGEREASON_ID
, PROCESSBU.Code PROCESSBU_code, PROCESSBU.Description PROCESSBU_desc
, PLANT.Phoneno PROCESSBU_phone, PLANT.Faxno PROCESSBU_fax
, (select ibu.code from businessunit ibu where ibu.businessunit_id=pn.invoicebusinessunit_id) Inv_bu_code
, ih.extraname2, ih.nextperiodstartdate, ih.invoicefrequency_id invoicefrequencynumber, ih.parentinvoiceheader_id
, ihe.formlayoutcode INVOICELAYOUTCODE, ihe.billtocountrydescription
, (select max(emp.name) from employee emp where exists (select * from customer cust where cust.defaultbusinessunit_id = PROCESSBU.businessunit_id and cust.serviceemployee_id = emp.employee_id)) ContactPerson_name
from
  Packingnote pn
              left outer join packingnoteline pnl on pn.packingnote_id = pnl.packingnote_id -- SEE ##
              left outer join
                     packingnotecontainer pnc -- left outer join weighingcategory wgh on pnc.weighingcategory_id = wgh.weighingcategory_id)
                   on pn.packingnote_id = pnc.packingnote_id
, distributionpoint cons, department dep
, invoiceheader ih, invoiceline il
, invoicelinetype ilt
, currency, status statusPN, status statusIH, businessunit PROCESSBU, PLANT, systemsetting ss
, languages
, invoiceheaderextrainfo ihe
where
    pnl.packingnoteline_id is null -- ## IS MORE FASTER THEN pn.packingnote_id not in ( select distinct pnl.packingnote_id  from Packingnoteline pnl )
AND pn.status_id = statusPN.status_id
    and statusPN.statustype = 'PN'
        and statusPN.code = '30'
and pn.distributionpoint_id = cons.distributionpoint_id
and cons.department_id = dep.department_id
and pn.invoiceheader_id = ih.invoiceheader_id
and ihe.invoiceheader_id = ih.invoiceheader_id
    and ih.documenttype = 1
    and ih.status_id = statusIH.Status_Id
        and statusIH.Statustype = 'IN'
            -- and statusIH.Code = '2'
and ih.invoiceheader_id = il.invoiceheader_id
and il.linenumber = (select max(invoiceline.linenumber) from invoiceline
                                      where invoiceline.invoiceheader_id= il.invoiceheader_id
                                            and invoiceline.invoicelinetype_id = il.invoicelinetype_id
                                            and invoiceline.code = il.code )
and il.invoicelinetype_id = ilt.invoicelinetype_id
                          and ilt.type = 4 -- and ilt.type in (3, 4) ???
and ih.currency_id = currency.currency_id
AND pn.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
    AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
        AND PLANT.PLANT_ID = SS.PLANT_ID
            AND SS.NAME = 'WEIGHTUNIT'
UNION
select -- 4 -- PN without PNL and without Prices
  coalesce(ih.deltocustomernumber, ih.billtocustomernumber ) delnumber, ih.street, ih.zipcode, ih.HOUSENUMBER, ih.HOUSENUMBEREXT
, coalesce(ih.deltocustomername, ih.billtocustomername) delname, ih.CONTACTPERSONNAME
, ih.city, ih.county, ih.state, ih.billtocustomernumber, ih.billtocustomername, ih.invoicedate
, ih.invoiceheader_id, ih.invoicenumber, pn.packingnote_id, pn.notenumber, pn.deliverydate, cons.distributionpointnumber
, cons.description distributionpointDesc, ' ' ProductCode , ' ' CustomCode, ' ' CustomDesc
, ' ' ProductDescription, ' ' SizeCode
, 0 deliveredamount
, ( select sum(packingnotecontainer.grossweight - packingnotecontainer.tareweight) from packingnotecontainer where pn.packingnote_id = packingnotecontainer.packingnote_id
  group by pn.packingnote_id) Weight
, pnc.weightdecimals weightdecimals /*, wgh.code weighingcategoryCode
, ( select weighingcategory_desc.description from weighingcategory_desc where weighingcategory_desc.weighingcategory_id = wgh.weighingcategory_id
  and weighingcategory_desc.language_id = languages.language_id ) weighingcategoryDesc * /
, 0 price , 0 discountpercentage, 0 Total
, currency.code currencyCode, currency.decimals PriceDecimals, currency.invoiceamountdecimals InvoiceDecimals
, 1 PnNotInInvoice, pn.remark, SS.VALUE WEIGHTUNIT, languages.code languageCode
, dep.departmentnumber dep_number, dep.description dep_description
, PN.FREEOFCHARGEREASON_ID
, PROCESSBU.Code PROCESSBU_code, PROCESSBU.Description PROCESSBU_desc
, PLANT.Phoneno PROCESSBU_phone, PLANT.Faxno PROCESSBU_fax
, (select ibu.code from businessunit ibu where ibu.businessunit_id=pn.invoicebusinessunit_id) Inv_bu_code
, ih.extraname2, ih.nextperiodstartdate, ih.invoicefrequency_id invoicefrequencynumber, ih.parentinvoiceheader_id
, ihe.formlayoutcode INVOICELAYOUTCODE, ihe.billtocountrydescription
, (select max(emp.name) from employee emp where exists (select * from customer cust where cust.defaultbusinessunit_id = PROCESSBU.businessunit_id and cust.serviceemployee_id = emp.employee_id)) ContactPerson_name
from
  Packingnote pn
              left outer join packingnoteline pnl on pn.packingnote_id = pnl.packingnote_id -- SEE ##
              left outer join
                     packingnotecontainer pnc -- left outer join weighingcategory wgh on pnc.weighingcategory_id = wgh.weighingcategory_id)
                   on pn.packingnote_id = pnc.packingnote_id
, distributionpoint cons, department dep
, invoiceheader ih
, currency, status statusPN, status statusIH, businessunit PROCESSBU, PLANT, systemsetting ss
, languages
, invoiceheaderextrainfo ihe
where
    pnl.packingnoteline_id is null -- ## IS MORE FASTER THEN pn.packingnote_id not in ( select distinct pnl.packingnote_id  from Packingnoteline pnl )
AND pn.status_id = statusPN.status_id
    and statusPN.statustype = 'PN'
        and statusPN.code = '30'
and pn.distributionpoint_id = cons.distributionpoint_id
and cons.department_id = dep.department_id
and pn.invoiceheader_id = ih.invoiceheader_id
and ihe.invoiceheader_id = ih.invoiceheader_id
    and ih.documenttype = 1
    and ih.status_id = statusIH.Status_Id
        and statusIH.Statustype = 'IN'
            -- and statusIH.Code = '2'
and not exists ( select 'x' from invoiceline il, invoicelinetype ilt
          where ih.invoiceheader_id = il.invoiceheader_id
          and il.invoicelinetype_id = ilt.invoicelinetype_id
                                    and ilt.type = 4 -- and ilt.type in (3, 4) ???
          and il.linenumber = (select max(invoiceline.linenumber) from invoiceline
                                      where invoiceline.invoiceheader_id= il.invoiceheader_id
                                            and invoiceline.invoicelinetype_id = il.invoicelinetype_id
                                            and invoiceline.code = il.code ))
and ih.currency_id = currency.currency_id
AND pn.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
    AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
        AND PLANT.PLANT_ID = SS.PLANT_ID
            AND SS.NAME = 'WEIGHTUNIT'
*/

/
create or replace view V_DELIVERYNOTEAPPENDIX_BUT
 (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, TOTAL, CURRENCYCODE, PRICEDECIMALS, INVOICEDECIMALS, PNNOTININVOICE, REMARK, WEIGHTUNIT, LANGUAGECODE
, DEP_NUMBER, DEP_DESCRIPTION, FREEOFCHARGEREASON_ID, PRICEFACTOR, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, REFERENCENUMBER)
as SELECT -- 1 -- PN WITH PNL AND WITH PRICES
  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
, IL.CODE CUSTOMCODE, IL.DESCRIPTION CUSTOMDESC
  ,
  ILP.SIZECODE SIZECODE
, PNL.DELIVEREDAMOUNT, PNL.PACKINGNOTELINE_ID
, ( SELECT SUM(PACKINGNOTECONTAINER.GROSSWEIGHT - PACKINGNOTECONTAINER.TAREWEIGHT) FROM PACKINGNOTECONTAINER WHERE PN.PACKINGNOTE_ID = PACKINGNOTECONTAINER.PACKINGNOTE_ID
  GROUP BY PN.PACKINGNOTE_ID) WEIGHT
,  ( SELECT MAX(PACKINGNOTECONTAINER.WEIGHTDECIMALS) FROM PACKINGNOTECONTAINER WHERE PN.PACKINGNOTE_ID = PACKINGNOTECONTAINER.PACKINGNOTE_ID) WEIGHTDECIMALS
, IL.PRICE , IL.DISCOUNTPERCENTAGE, COALESCE((PNL.DELIVEREDAMOUNT*IL.PRICE*(1-IL.DISCOUNTPERCENTAGE/100)),0) TOTAL
, CURRENCY.CODE CURRENCYCODE, CURRENCY.DECIMALS PRICEDECIMALS, CURRENCY.INVOICEAMOUNTDECIMALS INVOICEDECIMALS
, 0 PNNOTININVOICE, PN.REMARK, SS.VALUE WEIGHTUNIT, LANGUAGES.CODE LANGUAGECODE
, DEP.DEPARTMENTNUMBER DEP_NUMBER, DEP.DESCRIPTION DEP_DESCRIPTION
, PN.FREEOFCHARGEREASON_ID
, ILP.PRICEFACTOR
, (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
, (SELECT MAX(DV.REFERENCE) FROM DELIVERYVARIATIONS DV WHERE DV.PACKINGNOTE_ID = PN.PACKINGNOTE_ID)	REFERENCENUMBER
FROM
  PACKINGNOTE PN
, PACKINGNOTELINE PNL
, DISTRIBUTIONPOINT CONS, DEPARTMENT DEP, INVOICEHEADER IH, INVOICELINE IL, PRODUCT PRD
, SIZEDEFINITION SZ
, INVOICELINEPRODUCT ILP, CURRENCY, STATUS STATUSPN, STATUS STATUSIH, BUSINESSUNIT PROCESSBU, PLANT, SYSTEMSETTING SS
, LANGUAGES
WHERE
    PN.STATUS_ID = STATUSPN.STATUS_ID
    AND STATUSPN.STATUSTYPE = 'PN'
        AND STATUSPN.CODE = '30'
AND PN.DISTRIBUTIONPOINT_ID = CONS.DISTRIBUTIONPOINT_ID
AND CONS.DEPARTMENT_ID = DEP.DEPARTMENT_ID
AND PNL.INVOICEHEADER_ID = IH.INVOICEHEADER_ID
    AND IH.DOCUMENTTYPE = 1
    AND IH.STATUS_ID = STATUSIH.STATUS_ID
        AND STATUSIH.STATUSTYPE = 'IN'
            -- AND STATUSIH.CODE = '2'
AND IH.INVOICEHEADER_ID = IL.INVOICEHEADER_ID
AND ILP.FINISHINGMETHOD_ID = PNL.FINISHINGMETHOD_ID -- LCO, TODO 7207
AND IL.CODE = COALESCE(PNL.CUSTOMCODE,PRD.CODE)------?????????????????????????????????
AND IL.INVOICELINETYPE_ID IN (SELECT ILT.INVOICELINETYPE_ID FROM  INVOICELINETYPE ILT WHERE
                            ILT.TYPE = CASE PRD.TYPEOFMERCHANDISE
                                            WHEN 3 THEN 5 ELSE 2 END )
AND IH.CURRENCY_ID = CURRENCY.CURRENCY_ID
AND PNL.PACKINGNOTE_ID = PN.PACKINGNOTE_ID
    AND PNL.PRODUCT_ID = PRD.PRODUCT_ID
    AND PNL.SIZEDEFINITION_ID = SZ.SIZEDEFINITION_ID
AND ILP.PRODUCT_LINK_ID = PNL.PRODUCT_ID
AND ILP.SIZEDEFINITION_LINK_ID = COALESCE((SELECT ILP1.SIZEDEFINITION_LINK_ID FROM INVOICELINEPRODUCT ILP1
    WHERE ILP1.PRODUCT_LINK_ID = PNL.PRODUCT_ID
    AND ILP1.SIZEDEFINITION_LINK_ID = PNL.SIZEDEFINITION_ID
    AND ILP1.INVOICELINE_ID IN (SELECT IL1.INVOICELINE_ID FROM INVOICELINE IL1
                                       WHERE IL1.INVOICEHEADER_ID = IH.INVOICEHEADER_ID
                                       AND IL1.INVOICELINETYPE_ID IN
                                          (SELECT ILT.INVOICELINETYPE_ID FROM INVOICELINETYPE ILT WHERE ILT.TYPE = CASE PRD.TYPEOFMERCHANDISE
                                            WHEN 3 THEN 5 ELSE 2 END))  AND ROWNUM = 1),
    (SELECT SIZEDEFINITION.SIZEDEFINITION_ID FROM SIZEDEFINITION WHERE SIZEDEFINITION.CODE = '*'))
        AND ILP.INVOICELINE_ID = IL.INVOICELINE_ID
AND PN.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
    AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
        AND PLANT.PLANT_ID = SS.PLANT_ID
            AND SS.NAME = 'WEIGHTUNIT'
AND IL.PRICE = CASE (SELECT SS1.VALUE FROM SYSTEMSETTING SS1 WHERE SS1.NAME LIKE 'INVPRICEDETERMMETHOD' AND SS1.PLANT_ID = PLANT.PLANT_ID)
               WHEN '0' THEN (F_GETDELPRODPRICE(1, IH.DELTOCUSTOMER_LINK_ID, PNL.PRODUCT_ID, PNL.SIZEDEFINITION_ID, PNL.FINISHINGMETHOD_ID, IH.INVOICEDATE, PRD.TYPEOFMERCHANDISE))
               ELSE (F_GETDELPRODPRICE(1, IH.DELTOCUSTOMER_LINK_ID, PNL.PRODUCT_ID, PNL.SIZEDEFINITION_ID, PNL.FINISHINGMETHOD_ID, TRUNC(PN.DELIVERYDATE,'D')+6, PRD.TYPEOFMERCHANDISE))
               END
UNION ALL
SELECT -- 2 -- PN WITH PNL AND NO PRICES
  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 --TODO6892
, CONS.DISTRIBUTIONPOINTNUMBER
, CONS.DESCRIPTION DISTRIBUTIONPOINTDESC
, COALESCE(PNL.CUSTOMCODE, PRD.CODE) CUSTOMCODE
, COALESCE(PNL.CUSTOMDESCRIPTION
, (SELECT PRODUCT_DESC.DESCRIPTION FROM PRODUCT_DESC WHERE PRODUCT_DESC.PRODUCT_ID = PRD.PRODUCT_ID
  AND PRODUCT_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID )
  ) CUSTOMDESC
  , SZ.CODE SIZECODE
, PNL.DELIVEREDAMOUNT, PNL.PACKINGNOTELINE_ID
, ( SELECT SUM(PACKINGNOTECONTAINER.GROSSWEIGHT - PACKINGNOTECONTAINER.TAREWEIGHT) FROM PACKINGNOTECONTAINER WHERE PN.PACKINGNOTE_ID = PACKINGNOTECONTAINER.PACKINGNOTE_ID
  GROUP BY PN.PACKINGNOTE_ID) WEIGHT
,  ( SELECT MAX(PACKINGNOTECONTAINER.WEIGHTDECIMALS) FROM PACKINGNOTECONTAINER WHERE PN.PACKINGNOTE_ID = PACKINGNOTECONTAINER.PACKINGNOTE_ID) WEIGHTDECIMALS
, 0 PRICE , 0 DISCOUNTPERCENTAGE, 0 TOTAL, '' CURRENCYCODE, 0 PRICEDECIMALS, 0 INVOICEDECIMALS
, 1 PNNOTININVOICE, PN.REMARK, SS.VALUE WEIGHTUNIT, LANGUAGES.CODE LANGUAGECODE
, DEP.DEPARTMENTNUMBER DEP_NUMBER, DEP.DESCRIPTION DEP_DESCRIPTION
, PN.FREEOFCHARGEREASON_ID
, 1 PRICEFACTOR
, (COALESCE(PNL.NOCHARGEPREVSHORTAGE, 0) + 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
, (COALESCE(PNL.NOCHARGEPREVREJECTED, 0) + 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
, (SELECT MAX(DV.REFERENCE) FROM DELIVERYVARIATIONS DV WHERE DV.PACKINGNOTE_ID = PN.PACKINGNOTE_ID)	REFERENCENUMBER
FROM
  PACKINGNOTE PN
    LEFT OUTER JOIN PACKINGNOTELINE PNL ON PNL.PACKINGNOTE_ID = PN.PACKINGNOTE_ID
, PRODUCT PRD, STATUS STATUSPN, STATUS STATUSIH, INVOICEHEADER IH, BUSINESSUNIT PROCESSBU, PLANT, SYSTEMSETTING SS
, DISTRIBUTIONPOINT CONS, DEPARTMENT DEP, SIZEDEFINITION SZ, LANGUAGES
WHERE
    PN.STATUS_ID = STATUSPN.STATUS_ID
    AND STATUSPN.STATUSTYPE = 'PN'
        AND STATUSPN.CODE = '30'
AND PN.DISTRIBUTIONPOINT_ID = CONS.DISTRIBUTIONPOINT_ID
AND CONS.DEPARTMENT_ID = DEP.DEPARTMENT_ID
AND PNL.INVOICEHEADER_ID = IH.INVOICEHEADER_ID
    AND IH.DOCUMENTTYPE = 1
AND IH.STATUS_ID = STATUSIH.STATUS_ID
    AND STATUSIH.STATUSTYPE = 'IN'
        -- AND STATUSIH.CODE = '2'
AND PNL.PRODUCT_ID = PRD.PRODUCT_ID
AND PNL.SIZEDEFINITION_ID = SZ.SIZEDEFINITION_ID
AND CONCATENATE(COALESCE(PNL.CUSTOMCODE, PRD.CODE), SZ.CODE) NOT IN
     ( SELECT CONCATENATE(IL.CODE, CASE ILP.SIZECODE WHEN '*' THEN SZ.CODE ELSE ILP.SIZECODE END)
              FROM INVOICELINE IL, INVOICELINEPRODUCT ILP
              WHERE IH.INVOICEHEADER_ID = IL.INVOICEHEADER_ID
              AND IL.CODE = COALESCE(PNL.CUSTOMCODE,PRD.CODE)
              AND IL.INVOICELINETYPE_ID = (SELECT ILT.INVOICELINETYPE_ID FROM  INVOICELINETYPE ILT WHERE
                                                  ILT.TYPE = CASE PRD.TYPEOFMERCHANDISE
                                                                  WHEN 3 THEN 5 ELSE 2 END )
              AND IL.INVOICELINE_ID = ILP.INVOICELINE_ID
              AND ILP.PRODUCT_LINK_ID = PRD.PRODUCT_ID
              )
AND PN.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
    AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
        AND PLANT.PLANT_ID = SS.PLANT_ID
            AND SS.NAME = 'WEIGHTUNIT'
UNION ALL
SELECT -- 3 -- PN WITHOUT PNL AND WITH PRICES
  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, PNL.PACKINGNOTELINE_ID
, (SELECT SUM(PACKINGNOTECONTAINER.GROSSWEIGHT - PACKINGNOTECONTAINER.TAREWEIGHT) FROM PACKINGNOTECONTAINER WHERE PN.PACKINGNOTE_ID = PACKINGNOTECONTAINER.PACKINGNOTE_ID
  GROUP BY PN.PACKINGNOTE_ID) WEIGHT
,  ( SELECT MAX(PACKINGNOTECONTAINER.WEIGHTDECIMALS) FROM PACKINGNOTECONTAINER WHERE PN.PACKINGNOTE_ID = PACKINGNOTECONTAINER.PACKINGNOTE_ID) WEIGHTDECIMALS
, IL.PRICE PRICE , IL.DISCOUNTPERCENTAGE
, COALESCE(((SELECT SUM(PACKINGNOTECONTAINER.GROSSWEIGHT - PACKINGNOTECONTAINER.TAREWEIGHT) FROM PACKINGNOTECONTAINER WHERE PN.PACKINGNOTE_ID = PACKINGNOTECONTAINER.PACKINGNOTE_ID
  GROUP BY PN.PACKINGNOTE_ID)*IL.PRICE*(1-IL.DISCOUNTPERCENTAGE/100)), 0) TOTAL
, CURRENCY.CODE CURRENCYCODE, CURRENCY.DECIMALS PRICEDECIMALS, CURRENCY.INVOICEAMOUNTDECIMALS INVOICEDECIMALS
, 0 PNNOTININVOICE, PN.REMARK, SS.VALUE WEIGHTUNIT, LANGUAGES.CODE LANGUAGECODE
, DEP.DEPARTMENTNUMBER DEP_NUMBER, DEP.DESCRIPTION DEP_DESCRIPTION
, PN.FREEOFCHARGEREASON_ID
, 1 PRICEFACTOR
, (COALESCE(PNL.NOCHARGEPREVSHORTAGE, 0) + 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
, (COALESCE(PNL.NOCHARGEPREVREJECTED, 0) + 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
, (SELECT MAX(DV.REFERENCE) FROM DELIVERYVARIATIONS DV WHERE DV.PACKINGNOTE_ID = PN.PACKINGNOTE_ID)	REFERENCENUMBER
FROM
  PACKINGNOTE PN
              LEFT OUTER JOIN PACKINGNOTELINE PNL ON PN.PACKINGNOTE_ID = PNL.PACKINGNOTE_ID
, DISTRIBUTIONPOINT CONS, DEPARTMENT DEP
, INVOICEHEADER IH, INVOICELINE IL
, INVOICELINETYPE ILT
, CURRENCY, STATUS STATUSPN, STATUS STATUSIH, BUSINESSUNIT PROCESSBU, PLANT, SYSTEMSETTING SS
, LANGUAGES
WHERE
    PNL.PACKINGNOTELINE_ID IS NULL
AND PN.STATUS_ID = STATUSPN.STATUS_ID
    AND STATUSPN.STATUSTYPE = 'PN'
        AND STATUSPN.CODE = '30'
AND PN.DISTRIBUTIONPOINT_ID = CONS.DISTRIBUTIONPOINT_ID
AND CONS.DEPARTMENT_ID = DEP.DEPARTMENT_ID
AND PNL.INVOICEHEADER_ID = IH.INVOICEHEADER_ID
    AND IH.DOCUMENTTYPE = 1
    AND IH.STATUS_ID = STATUSIH.STATUS_ID
        AND STATUSIH.STATUSTYPE = 'IN'
            -- AND STATUSIH.CODE = '2'
AND IH.INVOICEHEADER_ID = IL.INVOICEHEADER_ID
AND IL.INVOICELINETYPE_ID = ILT.INVOICELINETYPE_ID
                          AND ILT.TYPE = 4
AND IH.CURRENCY_ID = CURRENCY.CURRENCY_ID
AND PN.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
    AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
        AND PLANT.PLANT_ID = SS.PLANT_ID
            AND SS.NAME = 'WEIGHTUNIT'
UNION ALL
SELECT -- 4 -- PN WITHOUT PNL AND WITHOUT PRICES
  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, PNL.PACKINGNOTELINE_ID
, ( SELECT SUM(PACKINGNOTECONTAINER.GROSSWEIGHT - PACKINGNOTECONTAINER.TAREWEIGHT) FROM PACKINGNOTECONTAINER WHERE PN.PACKINGNOTE_ID = PACKINGNOTECONTAINER.PACKINGNOTE_ID
  GROUP BY PN.PACKINGNOTE_ID) WEIGHT
,  ( SELECT MAX(PACKINGNOTECONTAINER.WEIGHTDECIMALS) FROM PACKINGNOTECONTAINER WHERE PN.PACKINGNOTE_ID = PACKINGNOTECONTAINER.PACKINGNOTE_ID) WEIGHTDECIMALS
, 0 PRICE , 0 DISCOUNTPERCENTAGE, 0 TOTAL
, CURRENCY.CODE CURRENCYCODE, CURRENCY.DECIMALS PRICEDECIMALS, CURRENCY.INVOICEAMOUNTDECIMALS INVOICEDECIMALS
, 1 PNNOTININVOICE, PN.REMARK, SS.VALUE WEIGHTUNIT, LANGUAGES.CODE LANGUAGECODE
, DEP.DEPARTMENTNUMBER DEP_NUMBER, DEP.DESCRIPTION DEP_DESCRIPTION
, PN.FREEOFCHARGEREASON_ID
, 1 PRICEFACTOR
, (COALESCE(PNL.NOCHARGEPREVSHORTAGE, 0) + 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
, (COALESCE(PNL.NOCHARGEPREVREJECTED, 0) + 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
, (SELECT MAX(DV.REFERENCE) FROM DELIVERYVARIATIONS DV WHERE DV.PACKINGNOTE_ID = PN.PACKINGNOTE_ID)	REFERENCENUMBER
FROM
  PACKINGNOTE PN
              LEFT OUTER JOIN PACKINGNOTELINE PNL ON PN.PACKINGNOTE_ID = PNL.PACKINGNOTE_ID
, DISTRIBUTIONPOINT CONS, DEPARTMENT DEP
, INVOICEHEADER IH
, CURRENCY, STATUS STATUSPN, STATUS STATUSIH, BUSINESSUNIT PROCESSBU, PLANT, SYSTEMSETTING SS
, LANGUAGES
WHERE
    PNL.PACKINGNOTELINE_ID IS NULL
AND PN.STATUS_ID = STATUSPN.STATUS_ID
    AND STATUSPN.STATUSTYPE = 'PN'
        AND STATUSPN.CODE = '30'
AND PN.DISTRIBUTIONPOINT_ID = CONS.DISTRIBUTIONPOINT_ID
AND CONS.DEPARTMENT_ID = DEP.DEPARTMENT_ID
AND PNL.INVOICEHEADER_ID = IH.INVOICEHEADER_ID
    AND IH.DOCUMENTTYPE = 1
    AND IH.STATUS_ID = STATUSIH.STATUS_ID
        AND STATUSIH.STATUSTYPE = 'IN'
            -- AND STATUSIH.CODE = '2'
AND NOT EXISTS ( SELECT 'X' FROM INVOICELINE IL, INVOICELINETYPE ILT
          WHERE IH.INVOICEHEADER_ID = IL.INVOICEHEADER_ID
          AND IL.INVOICELINETYPE_ID = ILT.INVOICELINETYPE_ID
                                    AND ILT.TYPE = 4 )
AND IH.CURRENCY_ID = CURRENCY.CURRENCY_ID
AND PN.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
    AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
        AND PLANT.PLANT_ID = SS.PLANT_ID
            AND SS.NAME = 'WEIGHTUNIT'

/
create or replace view V_DELIVERYNOTEAPPENDIX_CBD
 (LINETYPE, DELNUMBER, STREET, ZIPCODE, DELNAME, DELSTREET, DELZIPCODE, DELCITY, CITY, COUNTY, STATE, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, INVOICEDATE, ENDDATE, 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, LANGUAGECODE, DEP_NUMBER, DEP_DESCRIPTION, FREEOFCHARGEREASON_ID, PRICEFACTOR, PROCESSBUDESCRIPTION, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTPHONENO, PLANTFAXNO, EMPLOYEENAME, EMPLOYEEPHONENO, EMPLOYEEMOBILENO, EMPLOYEEFAXNO, EMPLOYEEEMAIL, SALESAREA)
as select 1 linetype,
       coalesce(ih.deltocustomernumber, ih.billtocustomernumber) delnumber,
       ih.street,
       ih.zipcode,
       coalesce(ih.deltocustomername, ih.billtocustomername) delname,
       coalesce(ih.deltostreet, ih.street) delstreet,
       coalesce(ih.deltozipcode, ih.zipcode) delzipcode,
       coalesce(ih.deltocity, ih.city) delcity,
       ih.city,
       ih.county,
       ih.state,
       ih.billtocustomernumber,
       ih.billtocustomername,
       ih.invoicedate, ih.enddate,
       ih.invoiceheader_id,
       ih.invoicenumber,
       pn.packingnote_id,
       pn.notenumber,
       pn.deliverydate,
       pn.showoninvoiceappendix,
       pn.origin,
       cons.distributionpointnumber,
       cons.description distributionpointdesc,
       nvl(pnl.customcode,
           (select prd.code
              from product prd
             where pnl.product_id = prd.product_id)) customcode,
       nvl(pnl.customdescription,
           (select product_desc.description
              from product_desc
             where product_desc.product_id = pnl.product_id
               and product_desc.language_id = languages.language_id)) customdesc,
       (select sz.code
          from sizedefinition sz
         where pnl.sizedefinition_id = sz.sizedefinition_id) sizecode,
       pnl.deliveredamount,
       pnl.packingnoteline_id,
       (select sum(packingnotecontainer.grossweight -
                   packingnotecontainer.tareweight)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id
         group by pn.packingnote_id) weight,
       (select max(packingnotecontainer.weightdecimals)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id) weightdecimals,
       (select max(l.price)
             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 = '*'))) price,
       (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 = '*'))) discountpercentage, -- total, to be calculated in the report!
       currency.code currencycode,
       currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals,
       0 pnnotininvoice,
       pn.remark,
       cast((select ss.value
          from systemsetting ss
         where plant.plant_id = ss.plant_id
           and ss.name = 'WEIGHTUNIT') as varchar2(5)) weightunit,
       languages.code languagecode,
       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
, processbu.description processbudescription, plant.code plantcode, plant.name plantname
, plant.website plantwebsite, plant.email plantemail, plantaddress.street plantstreet
, plantaddress.zipcode plantzipcode, plantaddress.city plantcity, plant.phoneno plantphoneno, plant.faxno plantfaxno
, emp.name employeename, emp.phoneno employeephoneno, emp.mobileno employeemobileno, emp.faxno employeefaxno, emp.email employeeemail, cu.salesarea_id Salesarea
  from invoiceheader     ih
             left outer join  customer cu
                  left outer join employee emp on cu.serviceemployee_id = emp.employee_id
             on cu.customer_id = ih.deltocustomer_link_id,
       packingnoteline   pnl,
       product p,
       packingnote       pn,
       distributionpoint cons,
       department        dep,
       currency,
       status            statuspn,
       status            statusih,
       businessunit      processbu,
       plant, address plantaddress,
       languages
 where ih.invoiceheader_id = pnl.invoiceheader_id
   and ih.documenttype = 1
   and ih.status_id = statusih.status_id
   and statusih.statustype = 'IN'
   and pnl.packingnote_id = pn.packingnote_id
   and pnl.product_id=p.product_id
   and p.typeofmerchandise<> 3
   and pn.status_id = statuspn.status_id
   and statuspn.statustype = 'PN'
   and statuspn.code = '30'
   and pn.distributionpoint_id = cons.distributionpoint_id
   and cons.department_id = dep.department_id
   and ih.currency_id = currency.currency_id
   and pn.processbusinessunit_id = processbu.businessunit_id
   and processbu.plant_id = plant.plant_id
   and plant.address_id = plantaddress.address_id
union all
select distinct 2 linetype, coalesce(ih.deltocustomernumber, ih.billtocustomernumber) delnumber, ih.street, ih.zipcode,
       coalesce(ih.deltocustomername, ih.billtocustomername) delname, coalesce(ih.deltostreet, ih.street) delstreet,
       coalesce(ih.deltozipcode, ih.zipcode) delzipcode, coalesce(ih.deltocity, ih.city) delcity, ih.city, ih.county, ih.state,
       ih.billtocustomernumber, ih.billtocustomername, ih.invoicedate,  ih.enddate, 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(packingnotecontainer.grossweight - packingnotecontainer.tareweight)
         from   packingnotecontainer
         where  pn.packingnote_id = packingnotecontainer.packingnote_id
         group  by pn.packingnote_id) weight,
       pnc.weightdecimals,
       0 price,
       0 discountpercentage,       -- total, to be calculated in the report!
       currency.code currencycode, currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals, 0 pnnotininvoice, pn.remark,
       cast((select ss.value
          from systemsetting ss
         where plant.plant_id = ss.plant_id
           and ss.name = 'WEIGHTUNIT') as varchar2(5)) weightunit,
       languages.code languagecode, dep.departmentnumber dep_number,
       dep.description dep_description, pn.freeofchargereason_id,
       1 pricefactor
, processbu.description processbudescription, plant.code plantcode, plant.name plantname
, plant.website plantwebsite, plant.email plantemail, plantaddress.street plantstreet
, plantaddress.zipcode plantzipcode, plantaddress.city plantcity, plant.phoneno plantphoneno, plant.faxno plantfaxno
, emp.name employeename, emp.phoneno employeephoneno, emp.mobileno employeemobileno, emp.faxno employeefaxno, emp.email employeeemail, cu.salesarea_id Salesarea
from   invoiceheader ih
             left outer join  customer cu
                  left outer join employee emp on cu.serviceemployee_id = emp.employee_id
             on cu.customer_id = ih.deltocustomer_link_id,
       packingnote pn, packingnotecontainer pnc, distributionpoint cons, department dep,
       currency, status statuspn, status statusih,
       businessunit processbu, plant, address plantaddress, languages
where  ih.invoiceheader_id = pnc.invoiceheader_id
and    pnc.packingnote_id = pn.packingnote_id
and    ih.documenttype = 1
and    ih.status_id = statusih.status_id
and    statusih.statustype = 'IN'
and    pn.status_id = statuspn.status_id
and    statuspn.statustype = 'PN'
and    statuspn.code = '30'
and    pn.distributionpoint_id = cons.distributionpoint_id
and    cons.department_id = dep.department_id
and    ih.currency_id = currency.currency_id
and    pn.processbusinessunit_id = processbu.businessunit_id
and    processbu.plant_id = plant.plant_id
and not exists (select 1 from packingnoteline pnl where pnl.packingnote_id = pn.packingnote_id)
and plant.address_id = plantaddress.address_id
union all-- sales items
select 3 linetype,
       coalesce(ih.deltocustomernumber, ih.billtocustomernumber) delnumber,
       ih.street,
       ih.zipcode,
       coalesce(ih.deltocustomername, ih.billtocustomername) delname,
       coalesce(ih.deltostreet, ih.street) delstreet,
       coalesce(ih.deltozipcode, ih.zipcode) delzipcode,
       coalesce(ih.deltocity, ih.city) delcity,
       ih.city,
       ih.county,
       ih.state,
       ih.billtocustomernumber,
       ih.billtocustomername,
       ih.invoicedate, ih.enddate,
       ih.invoiceheader_id,
       ih.invoicenumber,
       pn.packingnote_id,
       pn.notenumber,
       pn.deliverydate,
       pn.showoninvoiceappendix,
       pn.origin,
       cons.distributionpointnumber,
       cons.description distributionpointdesc,
       nvl(pnl.customcode,
           (select prd.code
              from product prd
             where pnl.product_id = prd.product_id)) customcode,
       nvl(pnl.customdescription,
           (select product_desc.description
              from product_desc
             where product_desc.product_id = pnl.product_id
               and product_desc.language_id = languages.language_id)) customdesc,
       (select sz.code
          from sizedefinition sz
         where pnl.sizedefinition_id = sz.sizedefinition_id) sizecode,
       pnl.deliveredamount,
       pnl.packingnoteline_id,
       (select sum(packingnotecontainer.grossweight -
                   packingnotecontainer.tareweight)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id
         group by pn.packingnote_id) weight,
       (select max(packingnotecontainer.weightdecimals)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id) weightdecimals,
       (select max(l.price)
             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 = 5
              and (ilp.sizedefinition_link_id = pnl.sizedefinition_id or
                  ilp.sizedefinition_link_id =
                  (select sizedefinition.sizedefinition_id
                      from sizedefinition
                     where sizedefinition.code = '*'))) price,
       0 discountpercentage, -- total, to be calculated in the report!
       currency.code currencycode,
       currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals,
       0 pnnotininvoice,
       pn.remark,
       cast((select ss.value
          from systemsetting ss
         where plant.plant_id = ss.plant_id
           and ss.name = 'WEIGHTUNIT') as varchar2(5)) weightunit,
       languages.code languagecode,
       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
, processbu.description processbudescription, plant.code plantcode, plant.name plantname
, plant.website plantwebsite, plant.email plantemail, plantaddress.street plantstreet
, plantaddress.zipcode plantzipcode, plantaddress.city plantcity, plant.phoneno plantphoneno, plant.faxno plantfaxno
, emp.name employeename, emp.phoneno employeephoneno, emp.mobileno employeemobileno, emp.faxno employeefaxno, emp.email employeeemail, cu.salesarea_id Salesarea
  from invoiceheader ih
             left outer join  customer cu
                  left outer join employee emp on cu.serviceemployee_id = emp.employee_id
             on cu.customer_id = ih.deltocustomer_link_id,
       packingnoteline   pnl,
       product           p,
       packingnote       pn,
       distributionpoint cons,
       department        dep,
       currency,
       status            statuspn,
       status            statusih,
       businessunit      processbu,
       plant, address plantaddress,
       languages
 where ih.invoiceheader_id = pnl.invoiceheader_id
   and ih.documenttype = 1
   and ih.status_id = statusih.status_id
   and statusih.statustype = 'IN'
   and pnl.packingnote_id = pn.packingnote_id
   and pnl.product_id=p.product_id
   and p.typeofmerchandise = 3
   and pn.status_id = statuspn.status_id
   and statuspn.statustype = 'PN'
   and statuspn.code = '30'
   and pn.distributionpoint_id = cons.distributionpoint_id
   and cons.department_id = dep.department_id
   and ih.currency_id = currency.currency_id
   and pn.processbusinessunit_id = processbu.businessunit_id
   and processbu.plant_id = plant.plant_id
   and plant.address_id = plantaddress.address_id

/
create or replace view V_DELIVERYNOTEAPPENDIX_CIW
 (LINETYPE, DELNUMBER, CNLEVEL, STREET, ZIPCODE, DELNAME, CITY, COUNTY, STATE, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, INVOICEDATE, INVOICEHEADER_ID, INVOICENUMBER, PACKINGNOTE_ID, NOTENUMBER, CONSIGNMENTNOTENO, CONSIGNMENTNOTEDELDATE, DELIVERYDATE, SHOWONINVOICEAPPENDIX, ORIGIN, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESC, CUSTOMCODE, CUSTOMDESC, SIZECODE, DELIVEREDAMOUNT, PACKINGNOTELINE_ID, WEIGHT, WEIGHTDECIMALS, PRICE, DISCOUNTPERCENTAGE, CURRENCYCODE, PRICEDECIMALS
, INVOICEDECIMALS, PNNOTININVOICE, REMARK, WEIGHTUNIT, LANGUAGECODE, DEP_NUMBER, DEP_DESCRIPTION, FREEOFCHARGEREASON_ID, PRICEFACTOR)
as select 1 linetype,
       coalesce(ih.deltocustomernumber, ih.billtocustomernumber) delnumber,
       (select c.consignmentnotelevel from customer c where c.customer_id = coalesce(ih.deltocustomer_link_id,ih.billtocustomer_link_id)) CNLevel,
       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,
       (select cn.consignmentnotenumber from consignmentnote cn where cn.consignmentnote_id = pn.consignmentnote_id) consignmentnoteno,
       (select cn.deliverydate from consignmentnote cn where cn.consignmentnote_id = pn.consignmentnote_id) consignmentnotedeldate,
       pn.deliverydate,
       pn.showoninvoiceappendix,
       pn.origin,
       cons.distributionpointnumber,
       cons.description distributionpointdesc,
       nvl(pnl.customcode,
           (select prd.code
              from product prd
             where pnl.product_id = prd.product_id)) customcode,
       nvl(pnl.customdescription,
           (select product_desc.description
              from product_desc
             where product_desc.product_id = pnl.product_id
               and product_desc.language_id = languages.language_id)) customdesc,
       (select sz.code
          from sizedefinition sz
         where pnl.sizedefinition_id = sz.sizedefinition_id) sizecode,
       pnl.deliveredamount,
       pnl.packingnoteline_id,
       (select sum(packingnotecontainer.grossweight -
                   packingnotecontainer.tareweight)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id
         group by pn.packingnote_id) weight,
       (select max(packingnotecontainer.weightdecimals)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id) weightdecimals,
       (select max(l.price)
             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 = '*'))) price,
       (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 = '*'))) discountpercentage, -- total, to be calculated in the report!
       currency.code currencycode,
       currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals,
       0 pnnotininvoice,
       pn.remark,
       (select ss.value
          from systemsetting ss
         where plant.plant_id = ss.plant_id
           and ss.name = 'WEIGHTUNIT') weightunit,
       languages.code languagecode,
       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
  from invoiceheader     ih,
       packingnoteline   pnl,
       product p,
       packingnote       pn,
       distributionpoint cons,
       department        dep,
       currency,
       status            statuspn,
       status            statusih,
       businessunit      processbu,
       plant,
       languages
 where ih.invoiceheader_id = pnl.invoiceheader_id
   and ih.documenttype = 1
   and ih.status_id = statusih.status_id
   and statusih.statustype = 'IN'
   and pnl.packingnote_id = pn.packingnote_id
   and pnl.product_id=p.product_id
   and p.typeofmerchandise<> 3
   and pn.status_id = statuspn.status_id
   and statuspn.statustype = 'PN'
   and statuspn.code = '30'
   and pn.distributionpoint_id = cons.distributionpoint_id
   and cons.department_id = dep.department_id
   and ih.currency_id = currency.currency_id
   and pn.processbusinessunit_id = processbu.businessunit_id
   and processbu.plant_id = plant.plant_id
union all
select distinct 2 linetype, coalesce(ih.deltocustomernumber, ih.billtocustomernumber) delnumber,
       (select c.consignmentnotelevel from customer c where c.customer_id = coalesce(ih.deltocustomer_link_id,ih.billtocustomer_link_id)) CNLevel,
       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,
      (select cn.consignmentnotenumber from consignmentnote cn where cn.consignmentnote_id = pn.consignmentnote_id) consignmentnoteno,
      (select cn.deliverydate from consignmentnote cn where cn.consignmentnote_id = pn.consignmentnote_id) consignmentnotedeldate,
       pn.deliverydate,
       pn.showoninvoiceappendix,
       pn.origin, cons.distributionpointnumber, cons.description distributionpointdesc,
       '' customcode,       '' customdesc,       '' sizecode,
       0 deliveredamount, 0 packingnoteline_id,
       (select sum(packingnotecontainer.grossweight - packingnotecontainer.tareweight)
         from   packingnotecontainer
         where  pn.packingnote_id = packingnotecontainer.packingnote_id
         group  by pn.packingnote_id) weight,
       pnc.weightdecimals,
       0 price,
       0 discountpercentage,       -- total, to be calculated in the report!
       currency.code currencycode, currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals, 0 pnnotininvoice, pn.remark,
       (select ss.value from systemsetting ss where plant.plant_id = ss.plant_id and ss.name = 'WEIGHTUNIT') weightunit,
       languages.code languagecode, dep.departmentnumber dep_number,
       dep.description dep_description, pn.freeofchargereason_id,
       1 pricefactor
from   invoiceheader ih, packingnote pn, packingnotecontainer pnc, distributionpoint cons, department dep,
       currency, status statuspn, status statusih,
       businessunit processbu, plant, languages
where  ih.invoiceheader_id = pnc.invoiceheader_id
and    pnc.packingnote_id = pn.packingnote_id
and    ih.documenttype = 1
and    ih.status_id = statusih.status_id
and    statusih.statustype = 'IN'
and    pn.status_id = statuspn.status_id
and    statuspn.statustype = 'PN'
and    statuspn.code = '30'
and    pn.distributionpoint_id = cons.distributionpoint_id
and    cons.department_id = dep.department_id
and    ih.currency_id = currency.currency_id
and    pn.processbusinessunit_id = processbu.businessunit_id
and    processbu.plant_id = plant.plant_id
and not exists (select 1 from packingnoteline pnl where pnl.packingnote_id = pn.packingnote_id)
union all-- sales items
select 3 linetype,
       coalesce(ih.deltocustomernumber, ih.billtocustomernumber) delnumber,
       (select c.consignmentnotelevel from customer c where c.customer_id = coalesce(ih.deltocustomer_link_id,ih.billtocustomer_link_id)) CNLevel,
       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,
      (select cn.consignmentnotenumber from consignmentnote cn where cn.consignmentnote_id = pn.consignmentnote_id) consignmentnoteno,
      (select cn.deliverydate from consignmentnote cn where cn.consignmentnote_id = pn.consignmentnote_id) consignmentnotedeldate,
       pn.deliverydate,
       pn.showoninvoiceappendix,
       pn.origin,
       cons.distributionpointnumber,
       cons.description distributionpointdesc,
       nvl(pnl.customcode,
           (select prd.code
              from product prd
             where pnl.product_id = prd.product_id)) customcode,
       nvl(pnl.customdescription,
           (select product_desc.description
              from product_desc
             where product_desc.product_id = pnl.product_id
               and product_desc.language_id = languages.language_id)) customdesc,
       (select sz.code
          from sizedefinition sz
         where pnl.sizedefinition_id = sz.sizedefinition_id) sizecode,
       pnl.deliveredamount,
       pnl.packingnoteline_id,
       (select sum(packingnotecontainer.grossweight -
                   packingnotecontainer.tareweight)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id
         group by pn.packingnote_id) weight,
       (select max(packingnotecontainer.weightdecimals)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id) weightdecimals,
       (select max(l.price)
             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 = 5
              and (ilp.sizedefinition_link_id = pnl.sizedefinition_id or
                  ilp.sizedefinition_link_id =
                  (select sizedefinition.sizedefinition_id
                      from sizedefinition
                     where sizedefinition.code = '*'))) price,
       0 discountpercentage, -- total, to be calculated in the report!
       currency.code currencycode,
       currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals,
       0 pnnotininvoice,
       pn.remark,
       (select ss.value
          from systemsetting ss
         where plant.plant_id = ss.plant_id
           and ss.name = 'WEIGHTUNIT') weightunit,
       languages.code languagecode,
       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
  from invoiceheader     ih,
       packingnoteline   pnl,
       product           p,
       packingnote       pn,
       distributionpoint cons,
       department        dep,
       currency,
       status            statuspn,
       status            statusih,
       businessunit      processbu,
       plant,
       languages
 where ih.invoiceheader_id = pnl.invoiceheader_id
   and ih.documenttype = 1
   and ih.status_id = statusih.status_id
   and statusih.statustype = 'IN'
   and pnl.packingnote_id = pn.packingnote_id
   and pnl.product_id=p.product_id
   and p.typeofmerchandise = 3
   and pn.status_id = statuspn.status_id
   and statuspn.statustype = 'PN'
   and statuspn.code = '30'
   and pn.distributionpoint_id = cons.distributionpoint_id
   and cons.department_id = dep.department_id
   and ih.currency_id = currency.currency_id
   and pn.processbusinessunit_id = processbu.businessunit_id
   and processbu.plant_id = plant.plant_id

/
create or replace view V_DELIVERYNOTEAPPENDIX_DFD
 (LINETYPE, DELNUMBER, STREET, STREET2, ZIPCODE, DELNAME, CITY, COUNTY, STATE, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, INVOICEDATE, INVOICEHEADER_ID, INVOICENUMBER, DELTOCUSTVATNUMBER, CONTACTPERSONNAME, PACKINGNOTE_ID, NOTENUMBER, DELIVERYDATE, SHOWONINVOICEAPPENDIX, ORIGIN, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESC, CUSTOMCODE, CUSTOMDESC, SIZECODE, DELIVEREDAMOUNT, PACKINGNOTELINE_ID, WEIGHT, WEIGHTDECIMALS, PRICE, DISCOUNTPERCENTAGE, CURRENCYCODE, PRICEDECIMALS, INVOICEDECIMALS
, PNNOTININVOICE, REMARK, WEIGHTUNIT, LANGUAGECODE, DEP_NUMBER, DEP_DESCRIPTION, FREEOFCHARGEREASON_ID, PRICEFACTOR)
as select 1 linetype,
       coalesce(ih.deltocustomernumber, ih.billtocustomernumber) delnumber,
       ih.street, ih.street2,
       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,
       (select ihextr.deltocustvatnumber from invoiceheaderextrainfo ihextr where ihextr.invoiceheader_id = ih.invoiceheader_id) deltocustvatnumber,
       ih.contactpersonname,
       pn.packingnote_id,
       pn.notenumber,
       pn.deliverydate,
       pn.showoninvoiceappendix,
       pn.origin,
       cons.distributionpointnumber,
       cons.description distributionpointdesc,
       nvl(pnl.customcode,
           (select prd.code
              from product prd
             where pnl.product_id = prd.product_id)) customcode,
       nvl(pnl.customdescription,
           (select product_desc.description
              from product_desc
             where product_desc.product_id = pnl.product_id
               and product_desc.language_id = languages.language_id)) customdesc,
       (select sz.code
          from sizedefinition sz
         where pnl.sizedefinition_id = sz.sizedefinition_id) sizecode,
       pnl.deliveredamount,
       pnl.packingnoteline_id,
       (select sum(packingnotecontainer.grossweight -
                   packingnotecontainer.tareweight)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id
         group by pn.packingnote_id) weight,
       (select max(packingnotecontainer.weightdecimals)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id) weightdecimals,
       coalesce((select max(l.price)
             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 = '*')))
             , pnl.price
             , pack_price.Wash_Price(dep.customer_id, pnl.product_id, pnl.sizedefinition_id, pnl.finishingmethod_id, ih.invoicedate)) price,
       (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 = '*'))) discountpercentage, -- total, to be calculated in the report!
       currency.code currencycode,
       currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals,
       0 pnnotininvoice,
       pn.remark,
       (select ss.value
          from systemsetting ss
         where plant.plant_id = ss.plant_id
           and ss.name = 'WEIGHTUNIT') weightunit,
       languages.code languagecode,
       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
  from invoiceheader     ih,
       packingnoteline   pnl,
       product p,
       packingnote       pn,
       distributionpoint cons,
       department        dep,
       currency,
       status            statuspn,
       status            statusih,
       businessunit      processbu,
       plant,
       languages
 where ih.invoiceheader_id = pnl.invoiceheader_id
   and ih.documenttype = 1
   and ih.status_id = statusih.status_id
   and statusih.statustype = 'IN'
   and pnl.packingnote_id = pn.packingnote_id
   and pnl.product_id=p.product_id
   and p.typeofmerchandise<> 3
   and pn.status_id = statuspn.status_id
   and statuspn.statustype = 'PN'
   and statuspn.code = '30'
   and pn.distributionpoint_id = cons.distributionpoint_id
   and cons.department_id = dep.department_id
   and ih.currency_id = currency.currency_id
   and pn.processbusinessunit_id = processbu.businessunit_id
   and processbu.plant_id = plant.plant_id
union all
select distinct 2 linetype, coalesce(ih.deltocustomernumber, ih.billtocustomernumber) delnumber, ih.street, ih.street2, 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,
       (select ihextr.deltocustvatnumber from invoiceheaderextrainfo ihextr where ihextr.invoiceheader_id = ih.invoiceheader_id) deltocustvatnumber,
       ih.contactpersonname,
       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(packingnotecontainer.grossweight - packingnotecontainer.tareweight)
         from   packingnotecontainer
         where  pn.packingnote_id = packingnotecontainer.packingnote_id
         group  by pn.packingnote_id) weight,
       pnc.weightdecimals,
       0 price,
       0 discountpercentage,       -- total, to be calculated in the report!
       currency.code currencycode, currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals, 0 pnnotininvoice, pn.remark,
       (select ss.value from systemsetting ss where plant.plant_id = ss.plant_id and ss.name = 'WEIGHTUNIT') weightunit,
       languages.code languagecode, dep.departmentnumber dep_number,
       dep.description dep_description, pn.freeofchargereason_id,
       1 pricefactor
from   invoiceheader ih, packingnote pn, packingnotecontainer pnc, distributionpoint cons, department dep,
       currency, status statuspn, status statusih,
       businessunit processbu, plant, languages
where  ih.invoiceheader_id = pnc.invoiceheader_id
and    pnc.packingnote_id = pn.packingnote_id
and    ih.documenttype = 1
and    ih.status_id = statusih.status_id
and    statusih.statustype = 'IN'
and    pn.status_id = statuspn.status_id
and    statuspn.statustype = 'PN'
and    statuspn.code = '30'
and    pn.distributionpoint_id = cons.distributionpoint_id
and    cons.department_id = dep.department_id
and    ih.currency_id = currency.currency_id
and    pn.processbusinessunit_id = processbu.businessunit_id
and    processbu.plant_id = plant.plant_id
and not exists (select 1 from packingnoteline pnl where pnl.packingnote_id = pn.packingnote_id)
union all-- sales items
select 3 linetype,
       coalesce(ih.deltocustomernumber, ih.billtocustomernumber) delnumber,
       ih.street, ih.street2,
       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,
       (select ihextr.deltocustvatnumber from invoiceheaderextrainfo ihextr where ihextr.invoiceheader_id = ih.invoiceheader_id) deltocustvatnumber,
       ih.contactpersonname,
       pn.packingnote_id,
       pn.notenumber,
       pn.deliverydate,
       pn.showoninvoiceappendix,
       pn.origin,
       cons.distributionpointnumber,
       cons.description distributionpointdesc,
       nvl(pnl.customcode,
           (select prd.code
              from product prd
             where pnl.product_id = prd.product_id)) customcode,
       nvl(pnl.customdescription,
           (select product_desc.description
              from product_desc
             where product_desc.product_id = pnl.product_id
               and product_desc.language_id = languages.language_id)) customdesc,
       (select sz.code
          from sizedefinition sz
         where pnl.sizedefinition_id = sz.sizedefinition_id) sizecode,
       pnl.deliveredamount,
       pnl.packingnoteline_id,
       (select sum(packingnotecontainer.grossweight -
                   packingnotecontainer.tareweight)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id
         group by pn.packingnote_id) weight,
       (select max(packingnotecontainer.weightdecimals)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id) weightdecimals,
       coalesce((select max(l.price)
             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 = 5
              and (ilp.sizedefinition_link_id = pnl.sizedefinition_id or
                  ilp.sizedefinition_link_id =
                  (select sizedefinition.sizedefinition_id
                      from sizedefinition
                     where sizedefinition.code = '*')))
             , pnl.price
             , pack_price.Wash_Price(dep.customer_id, pnl.product_id, pnl.sizedefinition_id, pnl.finishingmethod_id, ih.invoicedate)) price,
       0 discountpercentage, -- total, to be calculated in the report!
       currency.code currencycode,
       currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals,
       0 pnnotininvoice,
       pn.remark,
       (select ss.value
          from systemsetting ss
         where plant.plant_id = ss.plant_id
           and ss.name = 'WEIGHTUNIT') weightunit,
       languages.code languagecode,
       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
  from invoiceheader     ih,
       packingnoteline   pnl,
       product           p,
       packingnote       pn,
       distributionpoint cons,
       department        dep,
       currency,
       status            statuspn,
       status            statusih,
       businessunit      processbu,
       plant,
       languages
 where ih.invoiceheader_id = pnl.invoiceheader_id
   and ih.documenttype = 1
   and ih.status_id = statusih.status_id
   and statusih.statustype = 'IN'
   and pnl.packingnote_id = pn.packingnote_id
   and pnl.product_id=p.product_id
   and p.typeofmerchandise = 3
   and pn.status_id = statuspn.status_id
   and statuspn.statustype = 'PN'
   and statuspn.code = '30'
   and pn.distributionpoint_id = cons.distributionpoint_id
   and cons.department_id = dep.department_id
   and ih.currency_id = currency.currency_id
   and pn.processbusinessunit_id = processbu.businessunit_id
   and processbu.plant_id = plant.plant_id

/
create or replace view V_DELIVERYNOTEAPPENDIX_PLS
 (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, TOTAL, CURRENCYCODE, PRICEDECIMALS, INVOICEDECIMALS, PNNOTININVOICE, REMARK, WEIGHTUNIT, LANGUAGECODE
, DEP_NUMBER, DEP_DESCRIPTION, FREEOFCHARGEREASON_ID, PRICEFACTOR, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, REFERENCENUMBER)
as SELECT -- 1 -- PN WITH PNL AND WITH PRICES
  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
, IL.CODE CUSTOMCODE, IL.DESCRIPTION CUSTOMDESC
  ,
  ILP.SIZECODE SIZECODE
, PNL.DELIVEREDAMOUNT, PNL.PACKINGNOTELINE_ID
, ( SELECT SUM(PACKINGNOTECONTAINER.GROSSWEIGHT - PACKINGNOTECONTAINER.TAREWEIGHT) FROM PACKINGNOTECONTAINER WHERE PN.PACKINGNOTE_ID = PACKINGNOTECONTAINER.PACKINGNOTE_ID
  GROUP BY PN.PACKINGNOTE_ID) WEIGHT
,  ( SELECT MAX(PACKINGNOTECONTAINER.WEIGHTDECIMALS) FROM PACKINGNOTECONTAINER WHERE PN.PACKINGNOTE_ID = PACKINGNOTECONTAINER.PACKINGNOTE_ID) WEIGHTDECIMALS
, IL.PRICE , IL.DISCOUNTPERCENTAGE, COALESCE((PNL.DELIVEREDAMOUNT*IL.PRICE*(1-IL.DISCOUNTPERCENTAGE/100)),0) TOTAL
, CURRENCY.CODE CURRENCYCODE, CURRENCY.DECIMALS PRICEDECIMALS, CURRENCY.INVOICEAMOUNTDECIMALS INVOICEDECIMALS
, 0 PNNOTININVOICE, PN.REMARK, SS.VALUE WEIGHTUNIT, LANGUAGES.CODE LANGUAGECODE
, DEP.DEPARTMENTNUMBER DEP_NUMBER, DEP.DESCRIPTION DEP_DESCRIPTION
, PN.FREEOFCHARGEREASON_ID
, ILP.PRICEFACTOR
, (PNL.NOCHARGEPREVSHORTAGE + COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
WHERE DV.PACKINGNOTE_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.PACKINGNOTE_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
, (SELECT MAX(DV.REFERENCE) FROM DELIVERYVARIATIONS DV WHERE DV.PACKINGNOTE_ID = PN.PACKINGNOTE_ID)	REFERENCENUMBER
FROM
  PACKINGNOTE PN
, PACKINGNOTELINE PNL
, DISTRIBUTIONPOINT CONS, DEPARTMENT DEP, INVOICEHEADER IH, INVOICELINE IL, PRODUCT PRD
, SIZEDEFINITION SZ
, INVOICELINEPRODUCT ILP, CURRENCY, STATUS STATUSPN, STATUS STATUSIH, BUSINESSUNIT PROCESSBU, PLANT, SYSTEMSETTING SS
, LANGUAGES
WHERE
    PN.STATUS_ID = STATUSPN.STATUS_ID
    AND STATUSPN.STATUSTYPE = 'PN'
        AND STATUSPN.CODE = '30'
AND PN.DISTRIBUTIONPOINT_ID = CONS.DISTRIBUTIONPOINT_ID
AND CONS.DEPARTMENT_ID = DEP.DEPARTMENT_ID
AND PNL.INVOICEHEADER_ID = IH.INVOICEHEADER_ID
    AND IH.DOCUMENTTYPE = 1
    AND IH.STATUS_ID = STATUSIH.STATUS_ID
        AND STATUSIH.STATUSTYPE = 'IN'
            -- AND STATUSIH.CODE = '2'
AND IH.INVOICEHEADER_ID = IL.INVOICEHEADER_ID
AND ILP.FINISHINGMETHOD_ID = PNL.FINISHINGMETHOD_ID -- LCO, TODO 7207
AND IL.CODE = COALESCE(PNL.CUSTOMCODE,PRD.CODE)------?????????????????????????????????
AND IL.INVOICELINETYPE_ID IN (SELECT ILT.INVOICELINETYPE_ID FROM  INVOICELINETYPE ILT WHERE
                            ILT.TYPE = CASE PRD.TYPEOFMERCHANDISE
                                            WHEN 3 THEN 5 ELSE 2 END )
AND IH.CURRENCY_ID = CURRENCY.CURRENCY_ID
AND PNL.PACKINGNOTE_ID = PN.PACKINGNOTE_ID
    AND PNL.PRODUCT_ID = PRD.PRODUCT_ID
    AND PNL.SIZEDEFINITION_ID = SZ.SIZEDEFINITION_ID
AND ILP.PRODUCT_LINK_ID = PNL.PRODUCT_ID
AND ILP.SIZEDEFINITION_LINK_ID = COALESCE((SELECT ILP1.SIZEDEFINITION_LINK_ID FROM INVOICELINEPRODUCT ILP1
    WHERE ILP1.PRODUCT_LINK_ID = PNL.PRODUCT_ID
    AND ILP1.SIZEDEFINITION_LINK_ID = PNL.SIZEDEFINITION_ID
    AND ILP1.INVOICELINE_ID IN (SELECT IL1.INVOICELINE_ID FROM INVOICELINE IL1
                                       WHERE IL1.INVOICEHEADER_ID = IH.INVOICEHEADER_ID
                                       AND IL1.INVOICELINETYPE_ID IN
                                          (SELECT ILT.INVOICELINETYPE_ID FROM INVOICELINETYPE ILT WHERE ILT.TYPE = CASE PRD.TYPEOFMERCHANDISE
                                            WHEN 3 THEN 5 ELSE 2 END))  AND ROWNUM = 1),
    (SELECT SIZEDEFINITION.SIZEDEFINITION_ID FROM SIZEDEFINITION WHERE SIZEDEFINITION.CODE = '*'))
        AND ILP.INVOICELINE_ID = IL.INVOICELINE_ID
AND PN.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
    AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
        AND PLANT.PLANT_ID = SS.PLANT_ID
            AND SS.NAME = 'WEIGHTUNIT'
AND IL.PRICE = CASE (SELECT SS1.VALUE FROM SYSTEMSETTING SS1 WHERE SS1.NAME LIKE 'INVPRICEDETERMMETHOD' AND SS1.PLANT_ID = PLANT.PLANT_ID)
               WHEN '0' THEN (F_GETDELPRODPRICE(1, IH.DELTOCUSTOMER_LINK_ID, PNL.PRODUCT_ID, PNL.SIZEDEFINITION_ID, PNL.FINISHINGMETHOD_ID, IH.INVOICEDATE, PRD.TYPEOFMERCHANDISE))
               ELSE (F_GETDELPRODPRICE(1, IH.DELTOCUSTOMER_LINK_ID, PNL.PRODUCT_ID, PNL.SIZEDEFINITION_ID, PNL.FINISHINGMETHOD_ID, TRUNC(PN.DELIVERYDATE,'D')+6, PRD.TYPEOFMERCHANDISE))
               END
UNION ALL
SELECT -- 2 -- PN WITH PNL AND NO PRICES
  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 --TODO6892
, CONS.DISTRIBUTIONPOINTNUMBER
, CONS.DESCRIPTION DISTRIBUTIONPOINTDESC
, COALESCE(PNL.CUSTOMCODE, PRD.CODE) CUSTOMCODE
, COALESCE(PNL.CUSTOMDESCRIPTION
, (SELECT PRODUCT_DESC.DESCRIPTION FROM PRODUCT_DESC WHERE PRODUCT_DESC.PRODUCT_ID = PRD.PRODUCT_ID
  AND PRODUCT_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID )
  ) CUSTOMDESC
  , SZ.CODE SIZECODE
, PNL.DELIVEREDAMOUNT, PNL.PACKINGNOTELINE_ID
, ( SELECT SUM(PACKINGNOTECONTAINER.GROSSWEIGHT - PACKINGNOTECONTAINER.TAREWEIGHT) FROM PACKINGNOTECONTAINER WHERE PN.PACKINGNOTE_ID = PACKINGNOTECONTAINER.PACKINGNOTE_ID
  GROUP BY PN.PACKINGNOTE_ID) WEIGHT
,  ( SELECT MAX(PACKINGNOTECONTAINER.WEIGHTDECIMALS) FROM PACKINGNOTECONTAINER WHERE PN.PACKINGNOTE_ID = PACKINGNOTECONTAINER.PACKINGNOTE_ID) WEIGHTDECIMALS
, 0 PRICE , 0 DISCOUNTPERCENTAGE, 0 TOTAL, '' CURRENCYCODE, 0 PRICEDECIMALS, 0 INVOICEDECIMALS
, 1 PNNOTININVOICE, PN.REMARK, SS.VALUE WEIGHTUNIT, LANGUAGES.CODE LANGUAGECODE
, DEP.DEPARTMENTNUMBER DEP_NUMBER, DEP.DESCRIPTION DEP_DESCRIPTION
, PN.FREEOFCHARGEREASON_ID
, 1 PRICEFACTOR
, (COALESCE(PNL.NOCHARGEPREVSHORTAGE, 0) + 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
, (COALESCE(PNL.NOCHARGEPREVREJECTED, 0) + 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
, (SELECT MAX(DV.REFERENCE) FROM DELIVERYVARIATIONS DV WHERE DV.PACKINGNOTE_ID = PN.PACKINGNOTE_ID)	REFERENCENUMBER
FROM
  PACKINGNOTE PN
    LEFT OUTER JOIN PACKINGNOTELINE PNL ON PNL.PACKINGNOTE_ID = PN.PACKINGNOTE_ID
, PRODUCT PRD, STATUS STATUSPN, STATUS STATUSIH, INVOICEHEADER IH, BUSINESSUNIT PROCESSBU, PLANT, SYSTEMSETTING SS
, DISTRIBUTIONPOINT CONS, DEPARTMENT DEP, SIZEDEFINITION SZ, LANGUAGES
WHERE
    PN.STATUS_ID = STATUSPN.STATUS_ID
    AND STATUSPN.STATUSTYPE = 'PN'
        AND STATUSPN.CODE = '30'
AND PN.DISTRIBUTIONPOINT_ID = CONS.DISTRIBUTIONPOINT_ID
AND CONS.DEPARTMENT_ID = DEP.DEPARTMENT_ID
AND PNL.INVOICEHEADER_ID = IH.INVOICEHEADER_ID
    AND IH.DOCUMENTTYPE = 1
AND IH.STATUS_ID = STATUSIH.STATUS_ID
    AND STATUSIH.STATUSTYPE = 'IN'
        -- AND STATUSIH.CODE = '2'
AND PNL.PRODUCT_ID = PRD.PRODUCT_ID
AND PNL.SIZEDEFINITION_ID = SZ.SIZEDEFINITION_ID
AND CONCATENATE(COALESCE(PNL.CUSTOMCODE, PRD.CODE), SZ.CODE) NOT IN
     ( SELECT CONCATENATE(IL.CODE, CASE ILP.SIZECODE WHEN '*' THEN SZ.CODE ELSE ILP.SIZECODE END)
              FROM INVOICELINE IL, INVOICELINEPRODUCT ILP
              WHERE IH.INVOICEHEADER_ID = IL.INVOICEHEADER_ID
              AND IL.CODE = COALESCE(PNL.CUSTOMCODE,PRD.CODE)
              AND IL.INVOICELINETYPE_ID = (SELECT ILT.INVOICELINETYPE_ID FROM  INVOICELINETYPE ILT WHERE
                                                  ILT.TYPE = CASE PRD.TYPEOFMERCHANDISE
                                                                  WHEN 3 THEN 5 ELSE 2 END )
              AND IL.INVOICELINE_ID = ILP.INVOICELINE_ID
              AND ILP.PRODUCT_LINK_ID = PRD.PRODUCT_ID
              )
AND PN.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
    AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
        AND PLANT.PLANT_ID = SS.PLANT_ID
            AND SS.NAME = 'WEIGHTUNIT'
UNION ALL
SELECT -- 3 -- PN WITHOUT PNL AND WITH PRICES
  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, PNL.PACKINGNOTELINE_ID
, (SELECT SUM(PACKINGNOTECONTAINER.GROSSWEIGHT - PACKINGNOTECONTAINER.TAREWEIGHT) FROM PACKINGNOTECONTAINER WHERE PN.PACKINGNOTE_ID = PACKINGNOTECONTAINER.PACKINGNOTE_ID
  GROUP BY PN.PACKINGNOTE_ID) WEIGHT
,  ( SELECT MAX(PACKINGNOTECONTAINER.WEIGHTDECIMALS) FROM PACKINGNOTECONTAINER WHERE PN.PACKINGNOTE_ID = PACKINGNOTECONTAINER.PACKINGNOTE_ID) WEIGHTDECIMALS
, IL.PRICE PRICE , IL.DISCOUNTPERCENTAGE
, COALESCE(((SELECT SUM(PACKINGNOTECONTAINER.GROSSWEIGHT - PACKINGNOTECONTAINER.TAREWEIGHT) FROM PACKINGNOTECONTAINER WHERE PN.PACKINGNOTE_ID = PACKINGNOTECONTAINER.PACKINGNOTE_ID
  GROUP BY PN.PACKINGNOTE_ID)*IL.PRICE*(1-IL.DISCOUNTPERCENTAGE/100)), 0) TOTAL
, CURRENCY.CODE CURRENCYCODE, CURRENCY.DECIMALS PRICEDECIMALS, CURRENCY.INVOICEAMOUNTDECIMALS INVOICEDECIMALS
, 0 PNNOTININVOICE, PN.REMARK, SS.VALUE WEIGHTUNIT, LANGUAGES.CODE LANGUAGECODE
, DEP.DEPARTMENTNUMBER DEP_NUMBER, DEP.DESCRIPTION DEP_DESCRIPTION
, PN.FREEOFCHARGEREASON_ID
, 1 PRICEFACTOR
, (COALESCE(PNL.NOCHARGEPREVSHORTAGE, 0) + 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
, (COALESCE(PNL.NOCHARGEPREVREJECTED, 0) + 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
, (SELECT MAX(DV.REFERENCE) FROM DELIVERYVARIATIONS DV WHERE DV.PACKINGNOTE_ID = PN.PACKINGNOTE_ID)	REFERENCENUMBER
FROM
  PACKINGNOTE PN
              LEFT OUTER JOIN PACKINGNOTELINE PNL ON PN.PACKINGNOTE_ID = PNL.PACKINGNOTE_ID
, DISTRIBUTIONPOINT CONS, DEPARTMENT DEP
, INVOICEHEADER IH, INVOICELINE IL
, INVOICELINETYPE ILT
, CURRENCY, STATUS STATUSPN, STATUS STATUSIH, BUSINESSUNIT PROCESSBU, PLANT, SYSTEMSETTING SS
, LANGUAGES
WHERE
    PNL.PACKINGNOTELINE_ID IS NULL
AND PN.STATUS_ID = STATUSPN.STATUS_ID
    AND STATUSPN.STATUSTYPE = 'PN'
        AND STATUSPN.CODE = '30'
AND PN.DISTRIBUTIONPOINT_ID = CONS.DISTRIBUTIONPOINT_ID
AND CONS.DEPARTMENT_ID = DEP.DEPARTMENT_ID
AND PNL.INVOICEHEADER_ID = IH.INVOICEHEADER_ID
    AND IH.DOCUMENTTYPE = 1
    AND IH.STATUS_ID = STATUSIH.STATUS_ID
        AND STATUSIH.STATUSTYPE = 'IN'
            -- AND STATUSIH.CODE = '2'
AND IH.INVOICEHEADER_ID = IL.INVOICEHEADER_ID
AND IL.INVOICELINETYPE_ID = ILT.INVOICELINETYPE_ID
                          AND ILT.TYPE = 4
AND IH.CURRENCY_ID = CURRENCY.CURRENCY_ID
AND PN.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
    AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
        AND PLANT.PLANT_ID = SS.PLANT_ID
            AND SS.NAME = 'WEIGHTUNIT'
UNION ALL
SELECT -- 4 -- PN WITHOUT PNL AND WITHOUT PRICES
  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, PNL.PACKINGNOTELINE_ID
, ( SELECT SUM(PACKINGNOTECONTAINER.GROSSWEIGHT - PACKINGNOTECONTAINER.TAREWEIGHT) FROM PACKINGNOTECONTAINER WHERE PN.PACKINGNOTE_ID = PACKINGNOTECONTAINER.PACKINGNOTE_ID
  GROUP BY PN.PACKINGNOTE_ID) WEIGHT
,  ( SELECT MAX(PACKINGNOTECONTAINER.WEIGHTDECIMALS) FROM PACKINGNOTECONTAINER WHERE PN.PACKINGNOTE_ID = PACKINGNOTECONTAINER.PACKINGNOTE_ID) WEIGHTDECIMALS
, 0 PRICE , 0 DISCOUNTPERCENTAGE, 0 TOTAL
, CURRENCY.CODE CURRENCYCODE, CURRENCY.DECIMALS PRICEDECIMALS, CURRENCY.INVOICEAMOUNTDECIMALS INVOICEDECIMALS
, 1 PNNOTININVOICE, PN.REMARK, SS.VALUE WEIGHTUNIT, LANGUAGES.CODE LANGUAGECODE
, DEP.DEPARTMENTNUMBER DEP_NUMBER, DEP.DESCRIPTION DEP_DESCRIPTION
, PN.FREEOFCHARGEREASON_ID
, 1 PRICEFACTOR
, (COALESCE(PNL.NOCHARGEPREVSHORTAGE, 0) + 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
, (COALESCE(PNL.NOCHARGEPREVREJECTED, 0) + 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
, (SELECT MAX(DV.REFERENCE) FROM DELIVERYVARIATIONS DV WHERE DV.PACKINGNOTE_ID = PN.PACKINGNOTE_ID)	REFERENCENUMBER
FROM
  PACKINGNOTE PN
              LEFT OUTER JOIN PACKINGNOTELINE PNL ON PN.PACKINGNOTE_ID = PNL.PACKINGNOTE_ID
, DISTRIBUTIONPOINT CONS, DEPARTMENT DEP
, INVOICEHEADER IH
, CURRENCY, STATUS STATUSPN, STATUS STATUSIH, BUSINESSUNIT PROCESSBU, PLANT, SYSTEMSETTING SS
, LANGUAGES
WHERE
    PNL.PACKINGNOTELINE_ID IS NULL
AND PN.STATUS_ID = STATUSPN.STATUS_ID
    AND STATUSPN.STATUSTYPE = 'PN'
        AND STATUSPN.CODE = '30'
AND PN.DISTRIBUTIONPOINT_ID = CONS.DISTRIBUTIONPOINT_ID
AND CONS.DEPARTMENT_ID = DEP.DEPARTMENT_ID
AND PNL.INVOICEHEADER_ID = IH.INVOICEHEADER_ID
    AND IH.DOCUMENTTYPE = 1
    AND IH.STATUS_ID = STATUSIH.STATUS_ID
        AND STATUSIH.STATUSTYPE = 'IN'
            -- AND STATUSIH.CODE = '2'
AND NOT EXISTS ( SELECT 'X' FROM INVOICELINE IL, INVOICELINETYPE ILT
          WHERE IH.INVOICEHEADER_ID = IL.INVOICEHEADER_ID
          AND IL.INVOICELINETYPE_ID = ILT.INVOICELINETYPE_ID
                                    AND ILT.TYPE = 4 )
AND IH.CURRENCY_ID = CURRENCY.CURRENCY_ID
AND PN.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
    AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
        AND PLANT.PLANT_ID = SS.PLANT_ID
            AND SS.NAME = 'WEIGHTUNIT'
/
create or replace view V_DELIVERYNOTEAPPENDIX_SGS
 (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
, LANGUAGECODE, DEP_NUMBER, DEP_DESCRIPTION, FREEOFCHARGEREASON_ID, PRICEFACTOR, CORRECTEDNOTENUMBER)
as select 1 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,
           (select prd.code
              from product prd
             where pnl.product_id = prd.product_id)) customcode,
       nvl(pnl.customdescription,
           (select product_desc.description
              from product_desc
             where product_desc.product_id = pnl.product_id
               and product_desc.language_id = languages.language_id)) customdesc,
       (select sz.code
          from sizedefinition sz
         where pnl.sizedefinition_id = sz.sizedefinition_id) sizecode,
       pnl.deliveredamount,
       pnl.packingnoteline_id,
       (select sum(packingnotecontainer.grossweight -
                   packingnotecontainer.tareweight)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id
         group by pn.packingnote_id) weight,
       (select max(packingnotecontainer.weightdecimals)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id) weightdecimals,
       coalesce((select max(l.price)
             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 = '*')))
             , pnl.price
             , pack_price.Wash_Price(dep.customer_id, pnl.product_id, pnl.sizedefinition_id, pnl.finishingmethod_id, ih.invoicedate)) price,
       (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 = '*'))) discountpercentage, -- total, to be calculated in the report!
       currency.code currencycode,
       currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals,
       0 pnnotininvoice,
       pn.remark,
       (select ss.value
          from systemsetting ss
         where plant.plant_id = ss.plant_id
           and ss.name = 'WEIGHTUNIT') weightunit,
       languages.code languagecode,
       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,
       pn.correctednotenumber correctednotenumber
  from invoiceheader     ih,
       packingnoteline   pnl,
       product p,
       packingnote       pn,
       distributionpoint cons,
       department        dep,
       currency,
       status            statuspn,
       status            statusih,
       businessunit      processbu,
       plant,
       languages
 where ih.invoiceheader_id = pnl.invoiceheader_id
   and ih.documenttype = 1
   and ih.status_id = statusih.status_id
   and statusih.statustype = 'IN'
   and pnl.packingnote_id = pn.packingnote_id
   and pnl.product_id=p.product_id
   and p.typeofmerchandise<> 3
   and pn.status_id = statuspn.status_id
   and statuspn.statustype = 'PN'
   and statuspn.code = '30'
   and pn.distributionpoint_id = cons.distributionpoint_id
   and cons.department_id = dep.department_id
   and ih.currency_id = currency.currency_id
   and pn.processbusinessunit_id = processbu.businessunit_id
   and processbu.plant_id = plant.plant_id
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(packingnotecontainer.grossweight - packingnotecontainer.tareweight)
         from   packingnotecontainer
         where  pn.packingnote_id = packingnotecontainer.packingnote_id
         group  by pn.packingnote_id) weight,
       pnc.weightdecimals,
       0 price,
       0 discountpercentage,       -- total, to be calculated in the report!
       currency.code currencycode, currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals, 0 pnnotininvoice, pn.remark,
       (select ss.value from systemsetting ss where plant.plant_id = ss.plant_id and ss.name = 'WEIGHTUNIT') weightunit,
			 languages.code languagecode, dep.departmentnumber dep_number,
       dep.description dep_description, pn.freeofchargereason_id,
       1 pricefactor,
       pn.correctednotenumber correctednotenumber
from   invoiceheader ih, packingnote pn, packingnotecontainer pnc, distributionpoint cons, department dep,
       currency, status statuspn, status statusih,
       businessunit processbu, plant, languages
where  ih.invoiceheader_id = pnc.invoiceheader_id
and    pnc.packingnote_id = pn.packingnote_id
and    ih.documenttype = 1
and    ih.status_id = statusih.status_id
and    statusih.statustype = 'IN'
and    pn.status_id = statuspn.status_id
and    statuspn.statustype = 'PN'
and    statuspn.code = '30'
and    pn.distributionpoint_id = cons.distributionpoint_id
and    cons.department_id = dep.department_id
and    ih.currency_id = currency.currency_id
and    pn.processbusinessunit_id = processbu.businessunit_id
and    processbu.plant_id = plant.plant_id
and not exists (select 1 from packingnoteline pnl where pnl.packingnote_id = pn.packingnote_id)
union all-- sales items
select 3 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,
           (select prd.code
              from product prd
             where pnl.product_id = prd.product_id)) customcode,
       nvl(pnl.customdescription,
           (select product_desc.description
              from product_desc
             where product_desc.product_id = pnl.product_id
               and product_desc.language_id = languages.language_id)) customdesc,
       (select sz.code
          from sizedefinition sz
         where pnl.sizedefinition_id = sz.sizedefinition_id) sizecode,
       pnl.deliveredamount,
       pnl.packingnoteline_id,
       (select sum(packingnotecontainer.grossweight -
                   packingnotecontainer.tareweight)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id
         group by pn.packingnote_id) weight,
       (select max(packingnotecontainer.weightdecimals)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id) weightdecimals,
       coalesce((select max(l.price)
             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 = 5
              and (ilp.sizedefinition_link_id = pnl.sizedefinition_id or
                  ilp.sizedefinition_link_id =
                  (select sizedefinition.sizedefinition_id
                      from sizedefinition
                     where sizedefinition.code = '*')))
             , pnl.price
             , pack_price.Wash_Price(dep.customer_id, pnl.product_id, pnl.sizedefinition_id, pnl.finishingmethod_id, ih.invoicedate)) price,
       0 discountpercentage, -- total, to be calculated in the report!
       currency.code currencycode,
       currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals,
       0 pnnotininvoice,
       pn.remark,
       (select ss.value
          from systemsetting ss
         where plant.plant_id = ss.plant_id
           and ss.name = 'WEIGHTUNIT') weightunit,
       languages.code languagecode,
       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,
         pn.correctednotenumber correctednotenumber
  from invoiceheader     ih,
       packingnoteline   pnl,
       product           p,
       packingnote       pn,
       distributionpoint cons,
       department        dep,
       currency,
       status            statuspn,
       status            statusih,
       businessunit      processbu,
       plant,
       languages
 where ih.invoiceheader_id = pnl.invoiceheader_id
   and ih.documenttype = 1
   and ih.status_id = statusih.status_id
   and statusih.statustype = 'IN'
   and pnl.packingnote_id = pn.packingnote_id
   and pnl.product_id=p.product_id
   and p.typeofmerchandise = 3
   and pn.status_id = statuspn.status_id
   and statuspn.statustype = 'PN'
   and statuspn.code = '30'
   and pn.distributionpoint_id = cons.distributionpoint_id
   and cons.department_id = dep.department_id
   and ih.currency_id = currency.currency_id
   and pn.processbusinessunit_id = processbu.businessunit_id
   and processbu.plant_id = plant.plant_id

/
create or replace view V_DELIVERYNOTEAPPENDIX_SPI
 (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
, LANGUAGECODE, DEP_NUMBER, DEP_DESCRIPTION, FREEOFCHARGEREASON_ID, PRICEFACTOR, PONUMBER)
as select 1 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,
           (select prd.code
              from product prd
             where pnl.product_id = prd.product_id)) customcode,
       nvl(pnl.customdescription,
           (select product_desc.description
              from product_desc
             where product_desc.product_id = pnl.product_id
               and product_desc.language_id = languages.language_id)) customdesc,
       (select sz.code
          from sizedefinition sz
         where pnl.sizedefinition_id = sz.sizedefinition_id) sizecode,
       pnl.deliveredamount,
       pnl.packingnoteline_id,
       CAST((select sum(packingnotecontainer.grossweight -
                   packingnotecontainer.tareweight)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id
         group by pn.packingnote_id) AS NUMBER) weight,
       (select max(packingnotecontainer.weightdecimals)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id) weightdecimals,
       (select max(l.price)
             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 = '*'))) price,
       (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 = '*'))) discountpercentage, -- total, to be calculated in the report!
       currency.code currencycode,
       currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals,
       0 pnnotininvoice,
       pn.remark,
       (select ss.value
          from systemsetting ss
         where plant.plant_id = ss.plant_id
           and ss.name = 'WEIGHTUNIT') weightunit,
       languages.code languagecode,
       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, cc.ponumber
  from invoiceheader     ih,
       packingnoteline   pnl,
       product p,
       packingnote       pn,
       distributionpoint cons left outer join costcenter cc on cons.costcenter_id = cc.costcenter_id,
       department        dep,
       currency,
       status            statuspn,
       status            statusih,
       businessunit      processbu,
       plant,
       languages
 where ih.invoiceheader_id = pnl.invoiceheader_id
   and ih.documenttype = 1
   and ih.status_id = statusih.status_id
   and statusih.statustype = 'IN'
   and pnl.packingnote_id = pn.packingnote_id
   and pnl.product_id=p.product_id
   and p.typeofmerchandise<> 3
   and pn.status_id = statuspn.status_id
   and statuspn.statustype = 'PN'
   and statuspn.code = '30'
   and pn.distributionpoint_id = cons.distributionpoint_id
   and cons.department_id = dep.department_id
   and ih.currency_id = currency.currency_id
   and pn.processbusinessunit_id = processbu.businessunit_id
   and processbu.plant_id = plant.plant_id
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,
       CAST((select sum(packingnotecontainer.grossweight - packingnotecontainer.tareweight)
         from   packingnotecontainer
         where  pn.packingnote_id = packingnotecontainer.packingnote_id
         group  by pn.packingnote_id) AS NUMBER) weight,
       pnc.weightdecimals,
       0 price,
       0 discountpercentage,       -- total, to be calculated in the report!
       currency.code currencycode, currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals, 0 pnnotininvoice, pn.remark,
       (select ss.value from systemsetting ss where plant.plant_id = ss.plant_id and ss.name = 'WEIGHTUNIT') weightunit,
			 languages.code languagecode, dep.departmentnumber dep_number,
       dep.description dep_description, pn.freeofchargereason_id,
       1 pricefactor, cc.ponumber
from   invoiceheader ih, packingnote pn, packingnotecontainer pnc, distributionpoint cons left outer join costcenter cc on cons.costcenter_id = cc.costcenter_id,   department dep,
       currency, status statuspn, status statusih,
       businessunit processbu, plant, languages
where  ih.invoiceheader_id = pnc.invoiceheader_id
and    pnc.packingnote_id = pn.packingnote_id
and    ih.documenttype = 1
and    ih.status_id = statusih.status_id
and    statusih.statustype = 'IN'
and    pn.status_id = statuspn.status_id
and    statuspn.statustype = 'PN'
and    statuspn.code = '30'
and    pn.distributionpoint_id = cons.distributionpoint_id
and    cons.department_id = dep.department_id
and    ih.currency_id = currency.currency_id
and    pn.processbusinessunit_id = processbu.businessunit_id
and    processbu.plant_id = plant.plant_id
and not exists (select 1 from packingnoteline pnl where pnl.packingnote_id = pn.packingnote_id)
union all-- sales items
select 3 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,
           (select prd.code
              from product prd
             where pnl.product_id = prd.product_id)) customcode,
       nvl(pnl.customdescription,
           (select product_desc.description
              from product_desc
             where product_desc.product_id = pnl.product_id
               and product_desc.language_id = languages.language_id)) customdesc,
       (select sz.code
          from sizedefinition sz
         where pnl.sizedefinition_id = sz.sizedefinition_id) sizecode,
       pnl.deliveredamount,
       pnl.packingnoteline_id,
       CAST((select sum(packingnotecontainer.grossweight -
                   packingnotecontainer.tareweight)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id
         group by pn.packingnote_id) AS NUMBER) weight,
       (select max(packingnotecontainer.weightdecimals)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id) weightdecimals,
       (select max(l.price)
             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 = 5
              and (ilp.sizedefinition_link_id = pnl.sizedefinition_id or
                  ilp.sizedefinition_link_id =
                  (select sizedefinition.sizedefinition_id
                      from sizedefinition
                     where sizedefinition.code = '*'))) price,
       0 discountpercentage, -- total, to be calculated in the report!
       currency.code currencycode,
       currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals,
       0 pnnotininvoice,
       pn.remark,
       (select ss.value
          from systemsetting ss
         where plant.plant_id = ss.plant_id
           and ss.name = 'WEIGHTUNIT') weightunit,
       languages.code languagecode,
       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, cc.ponumber
  from invoiceheader     ih,
       packingnoteline   pnl,
       product           p,
       packingnote       pn,
       distributionpoint cons left outer join costcenter cc on cons.costcenter_id = cc.costcenter_id,
       department        dep,
       currency,
       status            statuspn,
       status            statusih,
       businessunit      processbu,
       plant,
       languages
 where ih.invoiceheader_id = pnl.invoiceheader_id
   and ih.documenttype = 1
   and ih.status_id = statusih.status_id
   and statusih.statustype = 'IN'
   and pnl.packingnote_id = pn.packingnote_id
   and pnl.product_id=p.product_id
   and p.typeofmerchandise = 3
   and pn.status_id = statuspn.status_id
   and statuspn.statustype = 'PN'
   and statuspn.code = '30'
   and pn.distributionpoint_id = cons.distributionpoint_id
   and cons.department_id = dep.department_id
   and ih.currency_id = currency.currency_id
   and pn.processbusinessunit_id = processbu.businessunit_id
   and processbu.plant_id = plant.plant_id

/
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, PRODUCTDESCRIPTION, PRODUCTGROUPDESCRIPTION, PGCUSTOMDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, 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, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, PACKINGNOTELINE_ID, DELIVERYSCHEME, DELIVERYNOTELAYOUT)
as SELECT PACKINGNOTE.NOTENUMBER PACKINGNOTENUMBER, PRODUCT.CODE PRODUCTCODE,
       (SELECT DESCRIPTION
         FROM   PRODUCT_DESC P
         WHERE  P.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
PRODUCTDESCRIPTION,
       (SELECT DESCRIPTION
         FROM   PRODUCTGROUP_DESC A
         WHERE  A.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
PRODUCTGROUPDESCRIPTION,
       (SELECT PGPC.CUSTOMDESCRITPION
         FROM   PRODUCTGROUPPERCUSTOMER PGPC, DISTRIBUTIONPOINT DP, DEPARTMENT DEP
         WHERE  PGPC.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND PGPC.CUSTOMER_ID = DEP.CUSTOMER_ID
                AND DEP.DEPARTMENT_ID = DP.DEPARTMENT_ID AND DP.DISTRIBUTIONPOINT_ID = PACKINGNOTE.DISTRIBUTIONPOINT_ID)
PGCUSTOMDESCRIPTION,
       PACKINGNOTELINE.CUSTOMCODE, PACKINGNOTELINE.CUSTOMDESCRIPTION, SIZEDEFINITION.CODE,
       (SELECT DESCRIPTION
         FROM   SIZEDEFINITION_DESC S
         WHERE  S.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND
                S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDESCRIPTION,
       (SELECT DESCRIPTION
         FROM   FINISHINGMETHOD_DESC F
         WHERE  F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID AND
                F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODDESCRIPTION,
       PACKINGNOTELINE.PACKINGSEQUENCE, PACKINGNOTELINE.STANDARDAMOUNT,
       PACKINGNOTELINE.VARIATIONAMOUNT, PACKINGNOTELINE.DELIVEREDAMOUNT,
       PACKINGNOTELINE.TOBEDELIVEREDAMOUNT, PACKINGNOTELINE.REMARKFORPACKINGINSTRUCTIONS,
       PACKINGNOTELINE.SYSTEMUSER_ID, PACKINGNOTELINE.TIMESTAMP, LANGUAGES.CODE,
       PRODUCT.TYPEOFMERCHANDISE,
       (SELECT R.CODE
         FROM   REASONCODE R
         WHERE  R.REASONCODE_ID = PACKINGNOTELINE.FREEOFCHARGEREASON_ID) FREEOFCHARGEREASON,
       (SELECT DESCRIPTION
         FROM   REASONCODE_DESC RD
         WHERE  RD.REASONCODE_ID = PACKINGNOTELINE.FREEOFCHARGEREASON_ID AND
                RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREEOFCHARGEREASON_DESC,
       PACKINGNOTELINE.NOCHARGEFIRSTISSUE, PACKINGNOTELINE.NOCHARGEACTIVESEASON,
       PACKINGNOTELINE.DELIVEREDCOGQTY, PACKINGNOTELINE.ORIGIN LINE_ORIGIN,
       (CASE WHEN PACKINGNOTELINE.PRICE IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICE END) PRICE,
             PACKINGNOTELINE.AMOUNT, PACKINGNOTELINE.TAXGROUPCODE,
       (SELECT RG.CODE
         FROM   REGISTRATIONUNIT RG
         WHERE  RG.REGISTRATIONUNIT_ID = PRODUCT.REGISTRATIONUNIT_ID) REGUNIT,
       (CASE
          WHEN PACKINGNOTE.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 = PACKINGNOTELINE.PRODUCT_ID AND
                   PAL.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND
                   PAL.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID AND
                   PA.NOTENUMBER = PACKINGNOTE.CORRECTEDNOTENUMBER)
        END) OLD_QTY,
         (CASE WHEN PACKINGNOTELINE.PRICECOG IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICECOG END) PRICECOG,
   (SELECT MAX(PSZ.SEQUENCENUMBER) FROM PRODUCTSIZE PSZ WHERE PSZ.PRODUCT_ID = PRODUCT.PRODUCT_ID AND PSZ.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID) SEQUENCENUMBER
  , (SELECT CODE FROM FINISHINGMETHOD F
         WHERE  F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID) FINISHINGMETHODCODE
, (PACKINGNOTELINE.NOCHARGEPREVSHORTAGE + COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
WHERE DV.CAUSENOTE_ID = PACKINGNOTELINE.PACKINGNOTE_ID AND DV.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
AND DV.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND DV.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
AND DV.ORIGIN = 1 AND DV.SOILCOUNTSUBTYPE = 2), 0))  NOCHARGEPREVSHORTAGE
, (PACKINGNOTELINE.NOCHARGEPREVREJECTED + COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
WHERE DV.CAUSENOTE_ID = PACKINGNOTELINE.PACKINGNOTE_ID AND DV.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
AND DV.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND DV.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
AND DV.ORIGIN = 1 AND DV.SOILCOUNTSUBTYPE = 3), 0)) NOCHARGEPREVREJECTED, PACKINGNOTELINE.PACKINGNOTELINE_ID,
(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 = PACKINGNOTE.DISTRIBUTIONPOINT_ID
        AND PLPD.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
        AND PLPD.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID
        AND PLPD.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
        AND SDL.DATEACTIVE < PACKINGNOTE.DELIVERYDATE
        AND SDL.DATEINACTIVE > PACKINGNOTE.DELIVERYDATE
         AND SW.WEEKNUMBER = GETISOWEEK(PACKINGNOTE.DELIVERYDATE)
        AND SDA.DAY_ID = GETDAYNUMBER(PACKINGNOTE.DELIVERYDATE)) DELIVERYSCHEME,
(SELECT FL.CODE
         FROM FORMLAYOUT FL, CUSTOMER C, DISTRIBUTIONPOINT DP, DEPARTMENT DEP
         WHERE  FL.FORMLAYOUT_ID = C.DELIVERYNOTELAYOUT_ID AND C.CUSTOMER_ID = DEP.CUSTOMER_ID
                AND DEP.DEPARTMENT_ID = DP.DEPARTMENT_ID AND DP.DISTRIBUTIONPOINT_ID = PACKINGNOTE.DISTRIBUTIONPOINT_ID) DELIVERYNOTELAYOUT
FROM   PACKINGNOTELINE, PACKINGNOTE, PRODUCT, SIZEDEFINITION, LANGUAGES
WHERE  PACKINGNOTELINE.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID AND
       PACKINGNOTELINE.PRODUCT_ID = PRODUCT.PRODUCT_ID AND
       PACKINGNOTELINE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID

/
create or replace view V_DELIVERYNOTELINE_BDE
 (PACKINGNOTENUMBER, PRODUCTCODE, PRODUCTDESCRIPTION, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PGCUSTOMDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, PACKINGSEQUENCE, STANDARDAMOUNT, VARIATIONAMOUNT, DELIVEREDAMOUNT, TOBEDELIVEREDAMOUNT, REMARKFORPACKINGINSTRUCTIONS, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE, TYPEOFMERCHANDISE, FREEOFCHARGEREASON, FREEOFCHARGEREASON_DESC, NOCHARGEFIRSTISSUE, NOCHARGEACTIVESEASON
, NOCHARGENOTCOG, LINE_ORIGIN, PRICE, AMOUNT, TAXGROUPCODE, REGUNIT, OLD_QTY, PRICECOG, SEQUENCENUMBER, FINISHINGMETHODCODE, PACKORDER, INVENTORY, SUMNIVEAU, LOCATION)
as select packingnote.notenumber packingnotenumber
       , product.code productcode
       ,(select description
         from   product_desc p
         where  p.product_id = packingnoteline.product_id and p.language_id = languages.language_id) productdescription
       , pgrp.code as productgroupcode
       ,(select description
         from   productgroup_desc a
         where  a.productgroup_id = product.productgroup_id and a.language_id = languages.language_id)
productgroupdescription,
       (select pgpc.customdescritpion
         from   productgrouppercustomer pgpc, distributionpoint dp, department dep
         where  pgpc.productgroup_id = product.productgroup_id AND pgpc.customer_id = dep.customer_id
                AND dep.department_id = dp.department_id AND dp.distributionpoint_id = packingnote.distributionpoint_id)
pgcustomdescription,
       packingnoteline.customcode as productcustomcode
     , packingnoteline.customdescription as productcustomdescription
     , sizedefinition.code sizecode,
       (select description
         from   sizedefinition_desc s
         where  s.sizedefinition_id = packingnoteline.sizedefinition_id and
                s.language_id = languages.language_id) sizedescription,
       (select description
         from   finishingmethod_desc f
         where  f.finishingmethod_id = packingnoteline.finishingmethod_id and
                f.language_id = languages.language_id) finishingmethoddescription,
       packingnoteline.packingsequence, packingnoteline.standardamount,
       packingnoteline.variationamount, packingnoteline.deliveredamount,
       packingnoteline.tobedeliveredamount, packingnoteline.remarkforpackinginstructions,
       packingnoteline.systemuser_id, packingnoteline.timestamp
     , languages.code as languagecode,
       product.typeofmerchandise,
       (select r.code
         from   reasoncode r
         where  r.reasoncode_id = packingnoteline.freeofchargereason_id) freeofchargereason,
       (select description
         from   reasoncode_desc rd
         where  rd.reasoncode_id = packingnoteline.freeofchargereason_id and
                rd.language_id = languages.language_id) freeofchargereason_desc,
       packingnoteline.nochargefirstissue, packingnoteline.nochargeactiveseason,
       packingnoteline.deliveredcogqty as NOCHARGENOTCOG
     , packingnoteline.origin line_origin, packingnoteline.price,
       packingnoteline.amount, packingnoteline.taxgroupcode,
       (select rg.code
         from   registrationunit rg
         where  rg.registrationunit_id = product.registrationunit_id) regunit,
       (case
          when packingnote.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 = packingnoteline.product_id and
                   pal.sizedefinition_id = packingnoteline.sizedefinition_id and
                   pal.finishingmethod_id = packingnoteline.finishingmethod_id and
                   pa.notenumber = packingnote.correctednotenumber)
        end) old_qty, packingnoteline.pricecog
  , (select max(psz.sequencenumber) from productsize psz where psz.product_id = product.product_id and psz.sizedefinition_id = sizedefinition.sizedefinition_id) sequencenumber
  , (select code from finishingmethod f
         where  f.finishingmethod_id = packingnoteline.finishingmethod_id) finishingmethodcode
  , packingnoteline.scannedbundles as packorder
  , (select sum(rqa.quantity)
     from   rentalqtyadjustment rqa
          , productlistperdistribpoint plpd
     where  plpd.distributionpoint_id = packingnote.distributionpoint_id
       and  rqa.adjustmentdate <= packingnote.deliverydate
       and  rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
       and  plpd.product_id = packingnoteline.product_id
       and  plpd.sizedefinition_id = packingnoteline.sizedefinition_id
       and  plpd.finishingmethod_id = packingnoteline.finishingmethod_id) as inventory
  , decode(mod(cust.scansondeliverynote, 2), 0, 1, 1, 2, null) as sumniveau
  , packingnoteline.location as location
from   packingnoteline
     , packingnote
     , product
     , sizedefinition
     , languages
     , distributionpoint dist
     , department dep
     , customer cust
     , productgroup pgrp
where  packingnoteline.packingnote_id = packingnote.packingnote_id
   and packingnoteline.product_id = product.product_id
   and packingnoteline.sizedefinition_id = sizedefinition.sizedefinition_id
   and packingnote.distributionpoint_id = dist.distributionpoint_id
   and dist.department_id = dep.department_id
   and dep.customer_id = cust.customer_id
   and product.productgroup_id = pgrp.productgroup_id

/
create or replace view V_DELIVERYNOTELINE_BLY
 (PACKINGNOTENUMBER, PRODUCTCODE, PRODUCTDESCRIPTION, PRODUCTLONGDESCRIPTION, CUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, DELIVEREDAMOUNT, LANGUAGECODE, PACKINGNOTELINE_ID)
as select pn.notenumber packingnotenumber,
       pr.code productcode,
       (select description
          from product_desc p
         where p.product_id = pnl.product_id
           and p.language_id = l.language_id) productdescription,
        (select p.longdescription
          from product_desc p
         where p.product_id = pnl.product_id
           and p.language_id = l.language_id) productlongdescription,
       pnl.customcode,
       pnl.customdescription as productcustomdescription,
       pnl.deliveredamount,
       l.code as languagecode,
       pnl.packingnoteline_id
  from packingnoteline pnl, packingnote pn, product pr, languages l
 where pnl.packingnote_id = pn.packingnote_id
   and pnl.product_id = pr.product_id

/
create or replace view V_DELIVERYNOTELINE_BNL
 (LINETYPE, PACKINGNOTENUMBER, PRODUCTCODE, PRODUCTDESCRIPTION, PRODUCTGROUPDESCRIPTION, PGCUSTOMDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, 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, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, INGELEVERD, OUTSCANNODELIVERY, PRIMARYID, WEARERNUMBER, WEARERFULLNAME, BANK, LOCKER, REASON)
as select 1 linetype, packingnote.notenumber packingnotenumber, product.code productcode,
       (select description
         from   product_desc p
         where  p.product_id = packingnoteline.product_id and p.language_id = languages.language_id)
productdescription,
       (select description
         from   productgroup_desc a
         where  a.productgroup_id = product.productgroup_id and a.language_id = languages.language_id)
productgroupdescription,
       (select pgpc.customdescritpion
         from   productgrouppercustomer pgpc, distributionpoint dp, department dep
         where  pgpc.productgroup_id = product.productgroup_id and pgpc.customer_id = dep.customer_id
                and dep.department_id = dp.department_id and dp.distributionpoint_id = packingnote.distributionpoint_id)
pgcustomdescription,
       packingnoteline.customcode, packingnoteline.customdescription, sizedefinition.code,
       (select description
         from   sizedefinition_desc s
         where  s.sizedefinition_id = packingnoteline.sizedefinition_id and
                s.language_id = languages.language_id) sizedescription,
       (select description
         from   finishingmethod_desc f
         where  f.finishingmethod_id = packingnoteline.finishingmethod_id and
                f.language_id = languages.language_id) finishingmethoddescription,
       packingnoteline.packingsequence, packingnoteline.standardamount,
       packingnoteline.variationamount, packingnoteline.deliveredamount,
       packingnoteline.tobedeliveredamount, packingnoteline.remarkforpackinginstructions,
       packingnoteline.systemuser_id, packingnoteline.timestamp, languages.code,
       product.typeofmerchandise,
       (select r.code
         from   reasoncode r
         where  r.reasoncode_id = packingnoteline.freeofchargereason_id) freeofchargereason,
       (select description
         from   reasoncode_desc rd
         where  rd.reasoncode_id = packingnoteline.freeofchargereason_id and
                rd.language_id = languages.language_id) freeofchargereason_desc,
       packingnoteline.nochargefirstissue, packingnoteline.nochargeactiveseason,
       packingnoteline.deliveredcogqty, packingnoteline.origin line_origin,
       (case when packingnoteline.price is null then 0 else packingnoteline.price end) price,
             packingnoteline.amount, packingnoteline.taxgroupcode,
       (select rg.code
         from   registrationunit rg
         where  rg.registrationunit_id = product.registrationunit_id) regunit,
       (case
          when packingnote.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 = packingnoteline.product_id and
                   pal.sizedefinition_id = packingnoteline.sizedefinition_id and
                   pal.finishingmethod_id = packingnoteline.finishingmethod_id and
                   pa.notenumber = packingnote.correctednotenumber)
        end) old_qty,
         (case when packingnoteline.pricecog is null then 0 else packingnoteline.pricecog end) pricecog,
   (select max(psz.sequencenumber) from productsize psz where psz.product_id = product.product_id and psz.sizedefinition_id = sizedefinition.sizedefinition_id) sequencenumber
  , (select code from finishingmethod f
         where  f.finishingmethod_id = packingnoteline.finishingmethod_id) finishingmethodcode
, (packingnoteline.nochargeprevshortage + coalesce((select sum (dv.amount) from deliveryvariations dv
where dv.causenote_id = packingnoteline.packingnote_id and dv.product_id = packingnoteline.product_id
and dv.sizedefinition_id = packingnoteline.sizedefinition_id and dv.finishingmethod_id = packingnoteline.finishingmethod_id
and dv.origin = 1 and dv.soilcountsubtype = 2), 0))  nochargeprevshortage
, (packingnoteline.nochargeprevrejected + coalesce((select sum (dv.amount) from deliveryvariations dv
where dv.causenote_id = packingnoteline.packingnote_id and dv.product_id = packingnoteline.product_id
and dv.sizedefinition_id = packingnoteline.sizedefinition_id and dv.finishingmethod_id = packingnoteline.finishingmethod_id
and dv.origin = 1 and dv.soilcountsubtype = 3), 0)) nochargeprevrejected
, (select count(1) from scan sc where sc.transactiontype_id = 1 and sc.batchnumber = ds.batchnumber
				      and sc.product_link_id = product.product_id and sc.sizedefinition_link_id = sizedefinition.sizedefinition_id
							and sc.distributionpoint_link_id = packingnote.distributionpoint_id) Ingeleverd
, coalesce(ds.outscannodelivery, 0), ui.primaryid, w.wearernumber, w.fullname wearerfullname
, lo.bank, lo.locker
, case when ds.outscannodelivery in (3,4,7) then (select st.description from stay_desc st where ui.stay_id = st.stay_id and st.language_id = languages.language_id)
       when ds.outscannodelivery = 6 then (select rc.description from reasoncode_desc rc where ds.reasoncode_id = rc.reasoncode_id and rc.language_id = languages.language_id)
			 else '' end Reason
from   packingnoteline, product, sizedefinition, languages, packingnote
       left outer join deliveryscan ds
			      inner join uniqueitem ui on ds.uniqueitem_link_id = ui.uniqueitem_id
						inner join weareremployment we
						     inner join wearer w on we.wearer_id = w.wearer_id
								 inner join locker lo on we.locker_id = lo.locker_id
						on ds.weareremployment_link_id = we.weareremployment_id
			 on ds.packingnote_id = packingnote.packingnote_id,
			 deliverypoint del, customer cu
where  packingnoteline.packingnote_id = packingnote.packingnote_id and
       packingnoteline.product_id = product.product_id and
       packingnoteline.sizedefinition_id = sizedefinition.sizedefinition_id and
			 packingnote.deliverypoint_id = del.deliverypoint_id and del.customer_id = cu.customer_id and
			 coalesce(ds.outscannodelivery, 3) > 2 and coalesce(ds.product_link_id, product.product_id) = product.product_id and
			 ((cu.scansondeliverynote in (0,2,4,6,8,10,12,14))
			 or (cu.scansondeliverynote not in (0,2,4,6,8,10,12,14)
			    and coalesce(ds.sizedefinition_link_id, sizedefinition.sizedefinition_id) = sizedefinition.sizedefinition_id)) and
			 (select max(plpc1.codeuniquely) from productlistpercustomer plpc1, distributionpoint dp, department de
       where plpc1.customer_id = de.customer_id and de.department_id = dp.department_id and dp.distributionpoint_id = packingnote.distributionpoint_id) = 'Y'
union all
select 2 linetype, packingnote.notenumber packingnotenumber, product.code productcode,
       (select description
         from   product_desc p
         where  p.product_id = packingnoteline.product_id and p.language_id = languages.language_id)
productdescription,
       (select description
         from   productgroup_desc a
         where  a.productgroup_id = product.productgroup_id and a.language_id = languages.language_id)
productgroupdescription,
       (select pgpc.customdescritpion
         from   productgrouppercustomer pgpc, distributionpoint dp, department dep
         where  pgpc.productgroup_id = product.productgroup_id and pgpc.customer_id = dep.customer_id
                and dep.department_id = dp.department_id and dp.distributionpoint_id = packingnote.distributionpoint_id)
pgcustomdescription,
       packingnoteline.customcode, packingnoteline.customdescription, sizedefinition.code,
       (select description
         from   sizedefinition_desc s
         where  s.sizedefinition_id = packingnoteline.sizedefinition_id and
                s.language_id = languages.language_id) sizedescription,
       (select description
         from   finishingmethod_desc f
         where  f.finishingmethod_id = packingnoteline.finishingmethod_id and
                f.language_id = languages.language_id) finishingmethoddescription,
       packingnoteline.packingsequence, packingnoteline.standardamount,
       packingnoteline.variationamount, packingnoteline.deliveredamount,
       packingnoteline.tobedeliveredamount, packingnoteline.remarkforpackinginstructions,
       packingnoteline.systemuser_id, packingnoteline.timestamp, languages.code,
       product.typeofmerchandise,
       (select r.code
         from   reasoncode r
         where  r.reasoncode_id = packingnoteline.freeofchargereason_id) freeofchargereason,
       (select description
         from   reasoncode_desc rd
         where  rd.reasoncode_id = packingnoteline.freeofchargereason_id and
                rd.language_id = languages.language_id) freeofchargereason_desc,
       packingnoteline.nochargefirstissue, packingnoteline.nochargeactiveseason,
       packingnoteline.deliveredcogqty, packingnoteline.origin line_origin,
       (case when packingnoteline.price is null then 0 else packingnoteline.price end) price,
             packingnoteline.amount, packingnoteline.taxgroupcode,
       (select rg.code
         from   registrationunit rg
         where  rg.registrationunit_id = product.registrationunit_id) regunit,
       (case
          when packingnote.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 = packingnoteline.product_id and
                   pal.sizedefinition_id = packingnoteline.sizedefinition_id and
                   pal.finishingmethod_id = packingnoteline.finishingmethod_id and
                   pa.notenumber = packingnote.correctednotenumber)
        end) old_qty,
         (case when packingnoteline.pricecog is null then 0 else packingnoteline.pricecog end) pricecog,
   (select max(psz.sequencenumber) from productsize psz where psz.product_id = product.product_id and psz.sizedefinition_id = sizedefinition.sizedefinition_id) sequencenumber
  , (select code from finishingmethod f
         where  f.finishingmethod_id = packingnoteline.finishingmethod_id) finishingmethodcode
, (packingnoteline.nochargeprevshortage + coalesce((select sum (dv.amount) from deliveryvariations dv
where dv.causenote_id = packingnoteline.packingnote_id and dv.product_id = packingnoteline.product_id
and dv.sizedefinition_id = packingnoteline.sizedefinition_id and dv.finishingmethod_id = packingnoteline.finishingmethod_id
and dv.origin = 1 and dv.soilcountsubtype = 2), 0))  nochargeprevshortage
, (packingnoteline.nochargeprevrejected + coalesce((select sum (dv.amount) from deliveryvariations dv
where dv.causenote_id = packingnoteline.packingnote_id and dv.product_id = packingnoteline.product_id
and dv.sizedefinition_id = packingnoteline.sizedefinition_id and dv.finishingmethod_id = packingnoteline.finishingmethod_id
and dv.origin = 1 and dv.soilcountsubtype = 3), 0)) nochargeprevrejected
, case when (select max(plpc2.soilcountmethod) from productlistpercustomer plpc2, distributionpoint dp, department de
        where plpc2.customer_id = de.customer_id and de.department_id = dp.department_id and dp.distributionpoint_id = packingnote.distributionpoint_id) > 0
	     then (select sum(dv.amount) from deliveryvariations dv where dv.product_id = product.product_id
				     and dv.sizedefinition_id = sizedefinition.sizedefinition_id and dv.packingnote_id=packingnote.packingnote_id
						 and dv.origin = 1 and dv.amount > 0)
	else 0
  end Ingeleverd, 0 outscannodelivery, null primaryid, null wearernumber, null wearerfullname, null bank, null locker, null reason
from   packingnoteline, packingnote, product, sizedefinition, languages
where  packingnoteline.packingnote_id = packingnote.packingnote_id and
       packingnoteline.product_id = product.product_id and
       packingnoteline.sizedefinition_id = sizedefinition.sizedefinition_id and
			 (select max(plpc1.codeuniquely) from productlistpercustomer plpc1, distributionpoint dp, department de
       where plpc1.customer_id = de.customer_id and de.department_id = dp.department_id and dp.distributionpoint_id = packingnote.distributionpoint_id) <> 'Y'

/
create or replace view V_DELIVERYNOTELINE_BUB
 (PACKINGNOTENUMBER, PRODUCTCODE, PRODUCTDESCRIPTION, PRODUCTGROUPDESCRIPTION, PGCUSTOMDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, 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, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, COLOUR)
as SELECT PACKINGNOTE.NOTENUMBER PACKINGNOTENUMBER, PRODUCT.CODE PRODUCTCODE,
       (SELECT DESCRIPTION
         FROM   PRODUCT_DESC P
         WHERE  P.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
PRODUCTDESCRIPTION,
       (SELECT DESCRIPTION
         FROM   PRODUCTGROUP_DESC A
         WHERE  A.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
PRODUCTGROUPDESCRIPTION,
       (SELECT PGPC.CUSTOMDESCRITPION
         FROM   PRODUCTGROUPPERCUSTOMER PGPC, DISTRIBUTIONPOINT DP, DEPARTMENT DEP
         WHERE  PGPC.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND PGPC.CUSTOMER_ID = DEP.CUSTOMER_ID
                AND DEP.DEPARTMENT_ID = DP.DEPARTMENT_ID AND DP.DISTRIBUTIONPOINT_ID = PACKINGNOTE.DISTRIBUTIONPOINT_ID)
PGCUSTOMDESCRIPTION,
       PACKINGNOTELINE.CUSTOMCODE, PACKINGNOTELINE.CUSTOMDESCRIPTION, SIZEDEFINITION.CODE,
       (SELECT DESCRIPTION
         FROM   SIZEDEFINITION_DESC S
         WHERE  S.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND
                S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDESCRIPTION,
       (SELECT DESCRIPTION
         FROM   FINISHINGMETHOD_DESC F
         WHERE  F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID AND
                F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODDESCRIPTION,
       PACKINGNOTELINE.PACKINGSEQUENCE, PACKINGNOTELINE.STANDARDAMOUNT,
       PACKINGNOTELINE.VARIATIONAMOUNT, PACKINGNOTELINE.DELIVEREDAMOUNT,
       PACKINGNOTELINE.TOBEDELIVEREDAMOUNT, PACKINGNOTELINE.REMARKFORPACKINGINSTRUCTIONS,
       PACKINGNOTELINE.SYSTEMUSER_ID, PACKINGNOTELINE.TIMESTAMP, LANGUAGES.CODE,
       PRODUCT.TYPEOFMERCHANDISE,
       (SELECT R.CODE
         FROM   REASONCODE R
         WHERE  R.REASONCODE_ID = PACKINGNOTELINE.FREEOFCHARGEREASON_ID) FREEOFCHARGEREASON,
       (SELECT DESCRIPTION
         FROM   REASONCODE_DESC RD
         WHERE  RD.REASONCODE_ID = PACKINGNOTELINE.FREEOFCHARGEREASON_ID AND
                RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREEOFCHARGEREASON_DESC,
       PACKINGNOTELINE.NOCHARGEFIRSTISSUE, PACKINGNOTELINE.NOCHARGEACTIVESEASON,
       PACKINGNOTELINE.DELIVEREDCOGQTY, PACKINGNOTELINE.ORIGIN LINE_ORIGIN,
       (CASE WHEN PACKINGNOTELINE.PRICE IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICE END) PRICE,
             PACKINGNOTELINE.AMOUNT, PACKINGNOTELINE.TAXGROUPCODE,
       (SELECT RG.CODE
         FROM   REGISTRATIONUNIT RG
         WHERE  RG.REGISTRATIONUNIT_ID = PRODUCT.REGISTRATIONUNIT_ID) REGUNIT,
       (CASE
          WHEN PACKINGNOTE.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 = PACKINGNOTELINE.PRODUCT_ID AND
                   PAL.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND
                   PAL.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID AND
                   PA.NOTENUMBER = PACKINGNOTE.CORRECTEDNOTENUMBER)
        END) OLD_QTY,
         (CASE WHEN PACKINGNOTELINE.PRICECOG IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICECOG END) PRICECOG,
   (SELECT MAX(PSZ.SEQUENCENUMBER) FROM PRODUCTSIZE PSZ WHERE PSZ.PRODUCT_ID = PRODUCT.PRODUCT_ID AND PSZ.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID) SEQUENCENUMBER
  , (SELECT CODE FROM FINISHINGMETHOD F
         WHERE  F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID) FINISHINGMETHODCODE
, (PACKINGNOTELINE.NOCHARGEPREVSHORTAGE + COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
WHERE DV.CAUSENOTE_ID = PACKINGNOTELINE.PACKINGNOTE_ID AND DV.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
AND DV.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND DV.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
AND DV.ORIGIN = 1 AND DV.SOILCOUNTSUBTYPE = 2), 0))  NOCHARGEPREVSHORTAGE
, (PACKINGNOTELINE.NOCHARGEPREVREJECTED + COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
WHERE DV.CAUSENOTE_ID = PACKINGNOTELINE.PACKINGNOTE_ID AND DV.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
AND DV.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND DV.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
AND DV.ORIGIN = 1 AND DV.SOILCOUNTSUBTYPE = 3), 0)) NOCHARGEPREVREJECTED
, (select cod.description from color_desc cod where cod.color_id = product.color_id and cod.language_id = languages.language_id) Colour
FROM   PACKINGNOTELINE, PACKINGNOTE, PRODUCT, SIZEDEFINITION, LANGUAGES
WHERE  PACKINGNOTELINE.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID AND
       PACKINGNOTELINE.PRODUCT_ID = PRODUCT.PRODUCT_ID AND
       PACKINGNOTELINE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID

/
create or replace view V_DELIVERYNOTELINE_CBD
 (PACKINGNOTENUMBER, PRODUCTCODE, PRODUCTDESCRIPTION, PRODUCTGROUPDESCRIPTION, PGCUSTOMDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, 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, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, COSTCENTER_CODE, COSTCENTER_DESC, REGUNITDESC)
as SELECT PACKINGNOTE.NOTENUMBER PACKINGNOTENUMBER,
    PRODUCT.CODE PRODUCTCODE,
    (SELECT DESCRIPTION
    FROM PRODUCT_DESC P
    WHERE P.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
    AND P.LANGUAGE_ID  = LANGUAGES.LANGUAGE_ID
    ) PRODUCTDESCRIPTION,
    (SELECT DESCRIPTION
    FROM PRODUCTGROUP_DESC A
    WHERE A.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID
    AND A.LANGUAGE_ID       = LANGUAGES.LANGUAGE_ID
    ) PRODUCTGROUPDESCRIPTION,
    (SELECT PGPC.CUSTOMDESCRITPION
    FROM PRODUCTGROUPPERCUSTOMER PGPC,
      DISTRIBUTIONPOINT DP,
      DEPARTMENT DEP
    WHERE PGPC.PRODUCTGROUP_ID  = PRODUCT.PRODUCTGROUP_ID
    AND PGPC.CUSTOMER_ID        = DEP.CUSTOMER_ID
    AND DEP.DEPARTMENT_ID       = DP.DEPARTMENT_ID
    AND DP.DISTRIBUTIONPOINT_ID = PACKINGNOTE.DISTRIBUTIONPOINT_ID
    ) PGCUSTOMDESCRIPTION,
    PACKINGNOTELINE.CUSTOMCODE,
    PACKINGNOTELINE.CUSTOMDESCRIPTION,
    SIZEDEFINITION.CODE,
    (SELECT DESCRIPTION
    FROM SIZEDEFINITION_DESC S
    WHERE S.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID
    AND S.LANGUAGE_ID         = LANGUAGES.LANGUAGE_ID
    ) SIZEDESCRIPTION,
    (SELECT DESCRIPTION
    FROM FINISHINGMETHOD_DESC F
    WHERE F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
    AND F.LANGUAGE_ID          = LANGUAGES.LANGUAGE_ID
    ) FINISHINGMETHODDESCRIPTION,
    PACKINGNOTELINE.PACKINGSEQUENCE,
    PACKINGNOTELINE.STANDARDAMOUNT,
    PACKINGNOTELINE.VARIATIONAMOUNT,
    PACKINGNOTELINE.DELIVEREDAMOUNT,
    PACKINGNOTELINE.TOBEDELIVEREDAMOUNT,
    PACKINGNOTELINE.REMARKFORPACKINGINSTRUCTIONS,
    PACKINGNOTELINE.SYSTEMUSER_ID,
    PACKINGNOTELINE.TIMESTAMP,
    LANGUAGES.CODE,
    PRODUCT.TYPEOFMERCHANDISE,
    (SELECT R.CODE
    FROM REASONCODE R
    WHERE R.REASONCODE_ID = PACKINGNOTELINE.FREEOFCHARGEREASON_ID
    ) FREEOFCHARGEREASON,
    (SELECT DESCRIPTION
    FROM REASONCODE_DESC RD
    WHERE RD.REASONCODE_ID = PACKINGNOTELINE.FREEOFCHARGEREASON_ID
    AND RD.LANGUAGE_ID     = LANGUAGES.LANGUAGE_ID
    ) FREEOFCHARGEREASON_DESC,
    PACKINGNOTELINE.NOCHARGEFIRSTISSUE,
    PACKINGNOTELINE.NOCHARGEACTIVESEASON,
    PACKINGNOTELINE.DELIVEREDCOGQTY,
    PACKINGNOTELINE.ORIGIN LINE_ORIGIN,
    (
    CASE
      WHEN PACKINGNOTELINE.PRICE IS NULL
      THEN 0
      ELSE PACKINGNOTELINE.PRICE
    END) PRICE,
    PACKINGNOTELINE.AMOUNT,
    PACKINGNOTELINE.TAXGROUPCODE,
    (SELECT RG.CODE
    FROM REGISTRATIONUNIT RG
    WHERE RG.REGISTRATIONUNIT_ID = PRODUCT.REGISTRATIONUNIT_ID
    ) REGUNIT,
    (
    CASE
      WHEN PACKINGNOTE.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         = PACKINGNOTELINE.PRODUCT_ID
        AND PAL.SIZEDEFINITION_ID  = PACKINGNOTELINE.SIZEDEFINITION_ID
        AND PAL.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
        AND PA.NOTENUMBER          = PACKINGNOTE.CORRECTEDNOTENUMBER
        )
    END) OLD_QTY,
    (
    CASE
      WHEN PACKINGNOTELINE.PRICECOG IS NULL
      THEN 0
      ELSE PACKINGNOTELINE.PRICECOG
    END) PRICECOG,
    (SELECT MAX(PSZ.SEQUENCENUMBER)
    FROM PRODUCTSIZE PSZ
    WHERE PSZ.PRODUCT_ID      = PRODUCT.PRODUCT_ID
    AND PSZ.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
    ) SEQUENCENUMBER ,
    (SELECT CODE
    FROM FINISHINGMETHOD F
    WHERE F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
    ) FINISHINGMETHODCODE ,
    (PACKINGNOTELINE.NOCHARGEPREVSHORTAGE + COALESCE(
    (SELECT SUM (DV.AMOUNT)
    FROM DELIVERYVARIATIONS DV
    WHERE DV.CAUSENOTE_ID     = PACKINGNOTELINE.PACKINGNOTE_ID
    AND DV.PRODUCT_ID         = PACKINGNOTELINE.PRODUCT_ID
    AND DV.SIZEDEFINITION_ID  = PACKINGNOTELINE.SIZEDEFINITION_ID
    AND DV.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
    AND DV.ORIGIN             = 1
    AND DV.SOILCOUNTSUBTYPE   = 2
    ), 0)) NOCHARGEPREVSHORTAGE ,
    (PACKINGNOTELINE.NOCHARGEPREVREJECTED + COALESCE(
    (SELECT SUM (DV.AMOUNT)
    FROM DELIVERYVARIATIONS DV
    WHERE DV.CAUSENOTE_ID     = PACKINGNOTELINE.PACKINGNOTE_ID
    AND DV.PRODUCT_ID         = PACKINGNOTELINE.PRODUCT_ID
    AND DV.SIZEDEFINITION_ID  = PACKINGNOTELINE.SIZEDEFINITION_ID
    AND DV.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
    AND DV.ORIGIN             = 1
    AND DV.SOILCOUNTSUBTYPE   = 3
    ), 0)) NOCHARGEPREVREJECTED ,
    cc.code costcenter_code,
    cc.description costcenter_desc ,
    registrationunit_desc.description
  FROM PACKINGNOTELINE,
    PACKINGNOTE,
    PRODUCT,
    SIZEDEFINITION,
    LANGUAGES,
    DISTRIBUTIONPOINT,
    costcenter cc,
    registrationunit_desc
  WHERE PACKINGNOTELINE.PACKINGNOTE_ID  = PACKINGNOTE.PACKINGNOTE_ID
  AND PACKINGNOTELINE.PRODUCT_ID        = PRODUCT.PRODUCT_ID
  AND PACKINGNOTELINE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
  AND PACKINGNOTE.DISTRIBUTIONPOINT_ID  = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
  AND DISTRIBUTIONPOINT.Costcenter_Id   = cc.costcenter_id
  AND PRODUCT.registrationunit_id       = registrationunit_desc.registrationunit_id

/
create or replace view V_DELIVERYNOTELINE_DFD
 (PACKINGNOTENUMBER, PRODUCTCODE, PRODUCTDESCRIPTION, PRODUCTGROUPDESCRIPTION, PGCUSTOMDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, 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, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, PRICE_PLPC, DELIVERYNOTELAYOUT)
as SELECT PACKINGNOTE.NOTENUMBER PACKINGNOTENUMBER, PRODUCT.CODE PRODUCTCODE,
       (SELECT DESCRIPTION
         FROM   PRODUCT_DESC P
         WHERE  P.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
PRODUCTDESCRIPTION,
       (SELECT DESCRIPTION
         FROM   PRODUCTGROUP_DESC A
         WHERE  A.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
PRODUCTGROUPDESCRIPTION,
       (SELECT PGPC.CUSTOMDESCRITPION
         FROM   PRODUCTGROUPPERCUSTOMER PGPC, DISTRIBUTIONPOINT DP, DEPARTMENT DEP
         WHERE  PGPC.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND PGPC.CUSTOMER_ID = DEP.CUSTOMER_ID
                AND DEP.DEPARTMENT_ID = DP.DEPARTMENT_ID AND DP.DISTRIBUTIONPOINT_ID = PACKINGNOTE.DISTRIBUTIONPOINT_ID)
PGCUSTOMDESCRIPTION,
       PACKINGNOTELINE.CUSTOMCODE, PACKINGNOTELINE.CUSTOMDESCRIPTION, SIZEDEFINITION.CODE,
       (SELECT DESCRIPTION
         FROM   SIZEDEFINITION_DESC S
         WHERE  S.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND
                S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDESCRIPTION,
       (SELECT DESCRIPTION
         FROM   FINISHINGMETHOD_DESC F
         WHERE  F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID AND
                F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODDESCRIPTION,
       PACKINGNOTELINE.PACKINGSEQUENCE, PACKINGNOTELINE.STANDARDAMOUNT,
       PACKINGNOTELINE.VARIATIONAMOUNT, PACKINGNOTELINE.DELIVEREDAMOUNT,
       PACKINGNOTELINE.TOBEDELIVEREDAMOUNT, PACKINGNOTELINE.REMARKFORPACKINGINSTRUCTIONS,
       PACKINGNOTELINE.SYSTEMUSER_ID, PACKINGNOTELINE.TIMESTAMP, LANGUAGES.CODE,
       PRODUCT.TYPEOFMERCHANDISE,
       (SELECT R.CODE
         FROM   REASONCODE R
         WHERE  R.REASONCODE_ID = PACKINGNOTELINE.FREEOFCHARGEREASON_ID) FREEOFCHARGEREASON,
       (SELECT DESCRIPTION
         FROM   REASONCODE_DESC RD
         WHERE  RD.REASONCODE_ID = PACKINGNOTELINE.FREEOFCHARGEREASON_ID AND
                RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREEOFCHARGEREASON_DESC,
       PACKINGNOTELINE.NOCHARGEFIRSTISSUE, PACKINGNOTELINE.NOCHARGEACTIVESEASON,
       PACKINGNOTELINE.DELIVEREDCOGQTY, PACKINGNOTELINE.ORIGIN LINE_ORIGIN,
       (CASE WHEN PACKINGNOTELINE.PRICE IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICE END) PRICE,
             PACKINGNOTELINE.AMOUNT, PACKINGNOTELINE.TAXGROUPCODE,
       (SELECT RG.CODE
         FROM   REGISTRATIONUNIT RG
         WHERE  RG.REGISTRATIONUNIT_ID = PRODUCT.REGISTRATIONUNIT_ID) REGUNIT,
       (CASE
          WHEN PACKINGNOTE.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 = PACKINGNOTELINE.PRODUCT_ID AND
                   PAL.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND
                   PAL.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID AND
                   PA.NOTENUMBER = PACKINGNOTE.CORRECTEDNOTENUMBER)
        END) OLD_QTY,
         (CASE WHEN PACKINGNOTELINE.PRICECOG IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICECOG END) PRICECOG,
   (SELECT MAX(PSZ.SEQUENCENUMBER) FROM PRODUCTSIZE PSZ WHERE PSZ.PRODUCT_ID = PRODUCT.PRODUCT_ID AND PSZ.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID) SEQUENCENUMBER
  , (SELECT CODE FROM FINISHINGMETHOD F
         WHERE  F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID) FINISHINGMETHODCODE
, (PACKINGNOTELINE.NOCHARGEPREVSHORTAGE + COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
WHERE DV.CAUSENOTE_ID = PACKINGNOTELINE.PACKINGNOTE_ID AND DV.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
AND DV.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND DV.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
AND DV.ORIGIN = 1 AND DV.SOILCOUNTSUBTYPE = 2), 0))  NOCHARGEPREVSHORTAGE
, (PACKINGNOTELINE.NOCHARGEPREVREJECTED + COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
WHERE DV.CAUSENOTE_ID = PACKINGNOTELINE.PACKINGNOTE_ID AND DV.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
AND DV.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND DV.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
AND DV.ORIGIN = 1 AND DV.SOILCOUNTSUBTYPE = 3), 0)) NOCHARGEPREVREJECTED,
pack_price.Wash_Price_Display(c.customer_id,product.product_id, sizedefinition.sizedefinition_id,packingnoteline.finishingmethod_id,
(select plpc.dateactive from productlistpercustomer plpc
       where plpc.customer_id=c.customer_id
       and plpc.product_id=packingnoteline.product_id
       and plpc.sizedefinition_id=packingnoteline.sizedefinition_id
       and plpc.finishingmethod_id=packingnoteline.finishingmethod_id
       and plpc.dateactive <= packingnote.deliverydate and plpc.dateinactive > packingnote.deliverydate),0
       ) price_plpc
, (select fl.code from formlayout fl where fl.formlayout_id=c.deliverynotelayout_id) deliverynotelayout
FROM   PACKINGNOTELINE, PACKINGNOTE, PRODUCT, SIZEDEFINITION, LANGUAGES, DEPARTMENT D, DISTRIBUTIONPOINT DP, CUSTOMER C
WHERE  PACKINGNOTELINE.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID AND
       PACKINGNOTELINE.PRODUCT_ID = PRODUCT.PRODUCT_ID AND
       PACKINGNOTELINE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
       AND PACKINGNOTE.DISTRIBUTIONPOINT_ID=DP.DISTRIBUTIONPOINT_ID
       AND DP.DEPARTMENT_ID=D.DEPARTMENT_ID
       AND D.CUSTOMER_ID=C.CUSTOMER_ID

/
create or replace view V_DELIVERYNOTELINE_ELI
 (PACKINGNOTENUMBER, PRODUCTCODE, PRODUCTDESCRIPTION, PARENT_CODE, PARENT_DESC, PRODUCTGROUPDESCRIPTION, PGCUSTOMDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, 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, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, ORIGIN, WOK_QTYORDERED, SALES_INSTRUCTIONS)
as SELECT PACKINGNOTE.NOTENUMBER PACKINGNOTENUMBER, PRODUCT.CODE PRODUCTCODE,
       (SELECT pde.DESCRIPTION
         FROM   PRODUCT_DESC Pde
         WHERE  Pde.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID AND Pde.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
PRODUCTDESCRIPTION,
       (SELECT p.code
         FROM   PRODUCT  P
         WHERE  P.PRODUCT_ID = PRODUCT.Parentproduct_Id ) Parent_Code,
       (SELECT pd.DESCRIPTION
         FROM   PRODUCT_DESC PD
         WHERE  Pd.PRODUCT_ID = PRODUCT.Parentproduct_Id AND Pd.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
Parent_Desc,
       (SELECT DESCRIPTION
         FROM   PRODUCTGROUP_DESC A
         WHERE  A.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
PRODUCTGROUPDESCRIPTION,
       (SELECT PGPC.CUSTOMDESCRITPION
         FROM   PRODUCTGROUPPERCUSTOMER PGPC, DISTRIBUTIONPOINT DP, DEPARTMENT DEP
         WHERE  PGPC.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND PGPC.CUSTOMER_ID = DEP.CUSTOMER_ID
                AND DEP.DEPARTMENT_ID = DP.DEPARTMENT_ID AND DP.DISTRIBUTIONPOINT_ID = PACKINGNOTE.DISTRIBUTIONPOINT_ID)
PGCUSTOMDESCRIPTION,
       PACKINGNOTELINE.CUSTOMCODE productcustomcode, PACKINGNOTELINE.CUSTOMDESCRIPTION productcustomdescription, SIZEDEFINITION.CODE sizecode,
       (SELECT DESCRIPTION
         FROM   SIZEDEFINITION_DESC S
         WHERE  S.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND
                S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDESCRIPTION,
       (SELECT DESCRIPTION
         FROM   FINISHINGMETHOD_DESC F
         WHERE  F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID AND
                F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODDESCRIPTION,
       PACKINGNOTELINE.PACKINGSEQUENCE, PACKINGNOTELINE.STANDARDAMOUNT,
       PACKINGNOTELINE.VARIATIONAMOUNT, PACKINGNOTELINE.DELIVEREDAMOUNT,
       PACKINGNOTELINE.TOBEDELIVEREDAMOUNT, PACKINGNOTELINE.REMARKFORPACKINGINSTRUCTIONS,
       PACKINGNOTELINE.SYSTEMUSER_ID username, PACKINGNOTELINE.TIMESTAMP, LANGUAGES.CODE languagecode,
       PRODUCT.TYPEOFMERCHANDISE,
       (SELECT R.CODE
         FROM   REASONCODE R
         WHERE  R.REASONCODE_ID = PACKINGNOTELINE.FREEOFCHARGEREASON_ID) FREEOFCHARGEREASON,
       (SELECT DESCRIPTION
         FROM   REASONCODE_DESC RD
         WHERE  RD.REASONCODE_ID = PACKINGNOTELINE.FREEOFCHARGEREASON_ID AND
                RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREEOFCHARGEREASON_DESC,
       PACKINGNOTELINE.NOCHARGEFIRSTISSUE, PACKINGNOTELINE.NOCHARGEACTIVESEASON,
       PACKINGNOTELINE.DELIVEREDCOGQTY nochargenotcog, PACKINGNOTELINE.ORIGIN LINE_ORIGIN,
       (CASE WHEN PACKINGNOTELINE.PRICE IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICE END) PRICE,
             PACKINGNOTELINE.AMOUNT, PACKINGNOTELINE.TAXGROUPCODE,
       (SELECT RG.CODE
         FROM   REGISTRATIONUNIT RG
         WHERE  RG.REGISTRATIONUNIT_ID = PRODUCT.REGISTRATIONUNIT_ID) REGUNIT,
       (CASE
          WHEN PACKINGNOTE.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 = PACKINGNOTELINE.PRODUCT_ID AND
                   PAL.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND
                   PAL.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID AND
                   PA.NOTENUMBER = PACKINGNOTE.CORRECTEDNOTENUMBER)
        END) OLD_QTY,
         (CASE WHEN PACKINGNOTELINE.PRICECOG IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICECOG END) PRICECOG,
   (SELECT MAX(PSZ.SEQUENCENUMBER) FROM PRODUCTSIZE PSZ WHERE PSZ.PRODUCT_ID = PRODUCT.PRODUCT_ID AND PSZ.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID) SEQUENCENUMBER
  , (SELECT CODE FROM FINISHINGMETHOD F
         WHERE  F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID) FINISHINGMETHODCODE
, (PACKINGNOTELINE.NOCHARGEPREVSHORTAGE + COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
WHERE DV.CAUSENOTE_ID = PACKINGNOTELINE.PACKINGNOTE_ID AND DV.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
AND DV.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND DV.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
AND DV.ORIGIN = 1 AND DV.SOILCOUNTSUBTYPE = 2), 0))  NOCHARGEPREVSHORTAGE
, (PACKINGNOTELINE.NOCHARGEPREVREJECTED + COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
WHERE DV.CAUSENOTE_ID = PACKINGNOTELINE.PACKINGNOTE_ID AND DV.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
AND DV.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND DV.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
AND DV.ORIGIN = 1 AND DV.SOILCOUNTSUBTYPE = 3), 0)) NOCHARGEPREVREJECTED
, PACKINGNOTE.Origin
, (select sum(wol.quantityordered) from workorderline wol
   where wol.workorder_id = packingnote.salesnote_id
   and wol.product_link_id = packingnoteline.product_id
   and wol.sizedefinition_link_id = packingnoteline.sizedefinition_id
   and wol.finishingmethod_id = packingnoteline.finishingmethod_id) wok_qtyordered
, (select max(wkli.instructions) from workorderline wkli where wkli.workorder_id = PACKINGNOTE.Salesnote_Id and wkli.product_link_id = PRODUCT.PRODUCT_ID
          and wkli.sizedefinition_link_id = SIZEDEFINITION.SIZEDEFINITION_ID and wkli.finishingmethod_id = PACKINGNOTELINE.Finishingmethod_Id) sales_instructions
FROM   PACKINGNOTELINE, PACKINGNOTE, PRODUCT, SIZEDEFINITION, LANGUAGES
WHERE  PACKINGNOTELINE.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID AND
       PACKINGNOTELINE.PRODUCT_ID = PRODUCT.PRODUCT_ID AND
       PACKINGNOTELINE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID

/
create or replace view V_DELIVERYNOTELINE_LTS
 (PACKINGNOTENUMBER, PRODUCTCODE, PRODUCTDESCRIPTION, ACTIVITYDESCRIPTION, ACTIVITYCODE, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, PACKINGSEQUENCE, STANDARDAMOUNT, VARIATIONAMOUNT, DELIVEREDAMOUNT, TOBEDELIVEREDAMOUNT, REMARKFORPACKINGINSTRUCTIONS, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE, TYPEOFMERCHANDISE, FREEOFCHARGEREASON, FREEOFCHARGEREASON_DESC, NOCHARGEFIRSTISSUE, NOCHARGEACTIVESEASON, NOCHARGENOTCOG, LINE_ORIGIN
, PRICE, AMOUNT, TAXGROUPCODE, REGUNIT, OLD_QTY, PRICECOG, SEQUENCENUMBER, FINISHINGMETHODCODE, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED)
as SELECT PACKINGNOTE.NOTENUMBER PACKINGNOTENUMBER, PRODUCT.CODE PRODUCTCODE,
       (SELECT P.DESCRIPTION
         FROM   PRODUCT_DESC P
         WHERE  P.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
PRODUCTDESCRIPTION,
       (SELECT A.DESCRIPTION
         FROM   ACTIVITY_DESC A, PRODUCTGROUP PG
         WHERE  A.ACTIVITY_ID = PG.ACTIVITY_ID AND PG.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
ACTIVITYDESCRIPTION,
       (SELECT AC.CODE
         FROM   ACTIVITY AC, PRODUCTGROUP PG
         WHERE  AC.ACTIVITY_ID = PG.ACTIVITY_ID AND PG.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID) ACTIVITYCODE,
       PACKINGNOTELINE.CUSTOMCODE PRODUCTCUSTOMCODE, PACKINGNOTELINE.CUSTOMDESCRIPTION PRODUCTCUSTOMDESCRIPTION, SIZEDEFINITION.CODE SIZECODE,
       (SELECT S.DESCRIPTION
         FROM   SIZEDEFINITION_DESC S
         WHERE  S.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND
                S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDESCRIPTION,
       (SELECT F.DESCRIPTION
         FROM   FINISHINGMETHOD_DESC F
         WHERE  F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID AND
                F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODDESCRIPTION,
       PACKINGNOTELINE.PACKINGSEQUENCE, PACKINGNOTELINE.STANDARDAMOUNT,
       PACKINGNOTELINE.VARIATIONAMOUNT, PACKINGNOTELINE.DELIVEREDAMOUNT,
       PACKINGNOTELINE.TOBEDELIVEREDAMOUNT, PACKINGNOTELINE.REMARKFORPACKINGINSTRUCTIONS,
       PACKINGNOTELINE.SYSTEMUSER_ID, PACKINGNOTELINE.TIMESTAMP, LANGUAGES.CODE LANGUAGECODE,
       PRODUCT.TYPEOFMERCHANDISE,
       (SELECT R.CODE
         FROM   REASONCODE R
         WHERE  R.REASONCODE_ID = PACKINGNOTELINE.FREEOFCHARGEREASON_ID) FREEOFCHARGEREASON,
       (SELECT RD.DESCRIPTION
         FROM   REASONCODE_DESC RD
         WHERE  RD.REASONCODE_ID = PACKINGNOTELINE.FREEOFCHARGEREASON_ID AND
                RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREEOFCHARGEREASON_DESC,
       PACKINGNOTELINE.NOCHARGEFIRSTISSUE, PACKINGNOTELINE.NOCHARGEACTIVESEASON,
       PACKINGNOTELINE.DELIVEREDCOGQTY NOCHARGENOTCOG, PACKINGNOTELINE.ORIGIN LINE_ORIGIN,
       COALESCE(PACKINGNOTELINE.PRICE, 0) PRICE,
             PACKINGNOTELINE.AMOUNT, PACKINGNOTELINE.TAXGROUPCODE,
       (SELECT RGD.DESCRIPTION
         FROM   REGISTRATIONUNIT_DESC RGD
         WHERE  RGD.REGISTRATIONUNIT_ID = PRODUCT.REGISTRATIONUNIT_ID AND RGD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) REGUNIT,
       (CASE
          WHEN PACKINGNOTE.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 = PACKINGNOTELINE.PRODUCT_ID AND
                   PAL.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND
                   PAL.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID AND
                   PA.NOTENUMBER = PACKINGNOTE.CORRECTEDNOTENUMBER)
        END) OLD_QTY,
         COALESCE(PACKINGNOTELINE.PRICECOG, 0) PRICECOG,
   (SELECT MAX(PSZ.SEQUENCENUMBER) FROM PRODUCTSIZE PSZ WHERE PSZ.PRODUCT_ID = PRODUCT.PRODUCT_ID AND PSZ.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID) SEQUENCENUMBER
  , (SELECT F.CODE FROM FINISHINGMETHOD F
         WHERE  F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID) FINISHINGMETHODCODE
, (PACKINGNOTELINE.NOCHARGEPREVSHORTAGE + COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
WHERE DV.CAUSENOTE_ID = PACKINGNOTELINE.PACKINGNOTE_ID AND DV.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
AND DV.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND DV.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
AND DV.ORIGIN = 1 AND DV.SOILCOUNTSUBTYPE = 2), 0))  NOCHARGEPREVSHORTAGE
, (PACKINGNOTELINE.NOCHARGEPREVREJECTED + COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
WHERE DV.CAUSENOTE_ID = PACKINGNOTELINE.PACKINGNOTE_ID AND DV.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
AND DV.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND DV.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
AND DV.ORIGIN = 1 AND DV.SOILCOUNTSUBTYPE = 3), 0)) NOCHARGEPREVREJECTED
FROM   PACKINGNOTELINE, PACKINGNOTE, PRODUCT, SIZEDEFINITION, LANGUAGES
WHERE  PACKINGNOTELINE.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID AND
       PACKINGNOTELINE.PRODUCT_ID = PRODUCT.PRODUCT_ID AND
       PACKINGNOTELINE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID

/
create or replace view V_DELIVERYNOTELINE_NAF
 (PACKINGNOTENUMBER, PRODUCTCODE, PRODUCTDESCRIPTION, PRODUCTLONGDESCRIPTION, PRODUCTGROUPDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, PACKINGSEQUENCE, STANDARDAMOUNT, VARIATIONAMOUNT, DELIVEREDAMOUNT, TOBEDELIVEREDAMOUNT, REMARKFORPACKINGINSTRUCTIONS, USERNAME, TIMESTAMP, LANGUAGECODE, TYPEOFMERCHANDISE, FREEOFCHARGEREASON, FREEOFCHARGEREASON_DESC, NOCHARGEFIRSTISSUE, NOCHARGEACTIVESEASON, NOCHARGENOTCOG
, LINE_ORIGIN, PRICE, AMOUNT, TAXGROUPCODE, REGUNIT, OLD_QTY)
as SELECT  PACKINGNOTE.NOTENUMBER packingnotenumber,
  PRODUCT.CODE productcode,
  (SELECT DESCRIPTION FROM PRODUCT_DESC P WHERE P.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  productdescription,
  (SELECT LONGDESCRIPTION FROM PRODUCT_DESC P WHERE P.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  productLONGdescription,
  (SELECT DESCRIPTION FROM productgroup_desc A WHERE A.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productgroupdescription,
  packingnoteline.customcode,
  packingnoteline.customdescription,
  SIZEDEFINITION.CODE,
  (SELECT DESCRIPTION FROM SIZEDEFINITION_DESC S WHERE S.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  SIZEdescription,
  (SELECT DESCRIPTION FROM FINISHINGMETHOD_DESC F WHERE F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  FINISHINGMETHODdescription,
  PACKINGNOTELINE.PACKINGSEQUENCE, PACKINGNOTELINE.STANDARDAMOUNT, PACKINGNOTELINE.VARIATIONAMOUNT,
  PACKINGNOTELINE.DELIVEREDAMOUNT, PACKINGNOTELINE.TOBEDELIVEREDAMOUNT,
  PACKINGNOTELINE.remarkforpackinginstructions, PACKINGNOTELINE.SYSTEMUSER_ID, PACKINGNOTELINE.TIMESTAMP, LANGUAGES.CODE,
  PRODUCT.TYPEOFMERCHANDISE,
 -- '' freeOfChargeReason, '' freeOfChargeReason_Desc,
 (select r.code
         from   reasoncode r
         where  r.reasoncode_id = packingnoteline.freeofchargereason_id) freeofchargereason,
       (select description
         from   reasoncode_desc rd
         where  rd.reasoncode_id = packingnoteline.freeofchargereason_id and
                rd.language_id = languages.language_id) freeofchargereason_desc,
  PACKINGNOTELINE.Nochargefirstissue, PACKINGNOTELINE.Nochargeactiveseason, PACKINGNOTELINE.Deliveredcogqty
  , PACKINGNOTELINE.Origin line_origin
  , (case when PACKINGNOTELINE.PRICE is null then 0 else PACKINGNOTELINE.PRICE end) price
  , PACKINGNOTELINE.AMOUNT, PACKINGNOTELINE.TAXGROUPCODE
  , (SELECT rg.code from registrationunit rg where rg.registrationunit_id = PRODUCT.Registrationunit_Id) regUnit,
  (CASE WHEN PACKINGNOTE.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 = PACKINGNOTELINE.Product_Id
           and pal.sizedefinition_id = PACKINGNOTELINE.Sizedefinition_Id
           and pal.finishingmethod_id = PACKINGNOTELINE.Finishingmethod_Id
           and pa.notenumber = PACKINGNOTE.Correctednotenumber) END) old_qty
-- , PACKINGNOTELINE.PRICECOG
  FROM PACKINGNOTELINE, PACKINGNOTE,
   PRODUCT, SIZEDEFINITION, LANGUAGES
  WHERE PACKINGNOTELINE.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID
  		AND PACKINGNOTELINE.PRODUCT_ID = PRODUCT.PRODUCT_ID
      AND PACKINGNOTELINE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID

/
create or replace view V_DELIVERYNOTELINE_NHO
 (PACKINGNOTENUMBER, PRODUCTCODE, PRODUCTDESCRIPTION, PRODLONGDESC, PRODUCTGROUPDESCRIPTION, PGCUSTOMDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, 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)
as select packingnote.notenumber packingnotenumber, product.code productcode,
       (select description
         from   product_desc p
         where  p.product_id = packingnoteline.product_id and p.language_id = languages.language_id)
productdescription,
       (select longdescription
         from   product_desc p
         where  p.product_id = packingnoteline.product_id and p.language_id = languages.language_id)
productlongdesc,
       (select description
         from   productgroup_desc a
         where  a.productgroup_id = product.productgroup_id and a.language_id = languages.language_id)
productgroupdescription,
       (select pgpc.customdescritpion
         from   productgrouppercustomer pgpc, distributionpoint dp, department dep
         where  pgpc.productgroup_id = product.productgroup_id AND pgpc.customer_id = dep.customer_id
                AND dep.department_id = dp.department_id AND dp.distributionpoint_id = packingnote.distributionpoint_id)
pgcustomdescription,
       packingnoteline.customcode, packingnoteline.customdescription, sizedefinition.code,
       (select description
         from   sizedefinition_desc s
         where  s.sizedefinition_id = packingnoteline.sizedefinition_id and
                s.language_id = languages.language_id) sizedescription,
       (select description
         from   finishingmethod_desc f
         where  f.finishingmethod_id = packingnoteline.finishingmethod_id and
                f.language_id = languages.language_id) finishingmethoddescription,
       packingnoteline.packingsequence, packingnoteline.standardamount,
       packingnoteline.variationamount, packingnoteline.deliveredamount,
       packingnoteline.tobedeliveredamount, packingnoteline.remarkforpackinginstructions,
       packingnoteline.systemuser_id, packingnoteline.timestamp, languages.code,
       product.typeofmerchandise,
       (select r.code
         from   reasoncode r
         where  r.reasoncode_id = packingnoteline.freeofchargereason_id) freeofchargereason,
       (select description
         from   reasoncode_desc rd
         where  rd.reasoncode_id = packingnoteline.freeofchargereason_id and
                rd.language_id = languages.language_id) freeofchargereason_desc,
       packingnoteline.nochargefirstissue, packingnoteline.nochargeactiveseason,
       packingnoteline.deliveredcogqty, packingnoteline.origin line_origin,
       (case when packingnoteline.price is null then 0 else packingnoteline.price end) price,
             packingnoteline.amount, packingnoteline.taxgroupcode,
       (select rg.code
         from   registrationunit rg
         where  rg.registrationunit_id = product.registrationunit_id) regunit,
       (case
          when packingnote.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 = packingnoteline.product_id and
                   pal.sizedefinition_id = packingnoteline.sizedefinition_id and
                   pal.finishingmethod_id = packingnoteline.finishingmethod_id and
                   pa.notenumber = packingnote.correctednotenumber)
        end) old_qty,
         (case when packingnoteline.pricecog is null then 0 else packingnoteline.pricecog end) pricecog,
   (select max(psz.sequencenumber) from productsize psz where psz.product_id = product.product_id and psz.sizedefinition_id = sizedefinition.sizedefinition_id) sequencenumber
  , (select code from finishingmethod f
         where  f.finishingmethod_id = packingnoteline.finishingmethod_id) finishingmethodcode
from   packingnoteline, packingnote, product, sizedefinition, languages
where  packingnoteline.packingnote_id = packingnote.packingnote_id and
       packingnoteline.product_id = product.product_id and
       packingnoteline.sizedefinition_id = sizedefinition.sizedefinition_id

/
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)
as select packingnote.notenumber packingnotenumber
,      product.code productcode
,      ( select description
         from   product_desc p
         where  p.product_id = packingnoteline.product_id
            and p.language_id = languages.language_id) productdescription
,      ( select description
         from   productgroup_desc a
         where  a.productgroup_id = product.productgroup_id
            and a.language_id = languages.language_id) productgroupdescription
,      ( select pgpc.customdescritpion
         from   productgrouppercustomer pgpc, distributionpoint dp, department dep
         where  pgpc.productgroup_id = product.productgroup_id
            and pgpc.customer_id = dep.customer_id
            and dep.department_id = dp.department_id
            and dp.distributionpoint_id = packingnote.distributionpoint_id) pgcustomdescription
,      packingnoteline.customcode productcustomcode
,      packingnoteline.customdescription productcustomdescription
,      sizedefinition.code sizecode
,      ( select description
         from   sizedefinition_desc s
         where  s.sizedefinition_id = packingnoteline.sizedefinition_id
            and s.language_id = languages.language_id) sizedescription
,      ( select description
         from   finishingmethod_desc f
         where  f.finishingmethod_id = packingnoteline.finishingmethod_id
            and f.language_id = languages.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 = languages.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 = languages.language_id) Packprod_size_desc
,      ( select fd.description
         from   finishingmethod_desc fd
         where  pc.finishingmethod_id = fd.finishingmethod_id
            and fd.language_id = languages.language_id) Packprod_finmeth_desc
,      pc.remark Packprod_remark
,      pc.location Packprod_location
,      pc.amount Packprod_amount
,      packingnoteline.packingsequence packingsequence
,      packingnoteline.standardamount standardamount
,      packingnoteline.variationamount variationamount
,      packingnoteline.deliveredamount deliveredamount
,      packingnoteline.tobedeliveredamount tobedeliveredamount
,      packingnoteline.remarkforpackinginstructions remarkforpackinginstructions
,      packingnoteline.systemuser_id username
,      packingnoteline.timestamp
,      languages.code languagecode
,      product.typeofmerchandise typeofmerchandise
,      ( select r.code
         from   reasoncode r
         where  r.reasoncode_id = packingnoteline.freeofchargereason_id) freeofchargereason
,      ( select description
         from   reasoncode_desc rd
         where  rd.reasoncode_id = packingnoteline.freeofchargereason_id
            and rd.language_id = languages.language_id) freeofchargereason_desc
,      packingnoteline.nochargefirstissue nochargefirstissue
,      packingnoteline.nochargeactiveseason nochargeactiveseason
,      packingnoteline.deliveredcogqty nochargenotcog
,      packingnoteline.origin line_origin
,      packingnoteline.price price
,      packingnoteline.amount amount
,      packingnoteline.taxgroupcode taxgroupcode
,      ( select rg.code
         from   registrationunit rg
         where  rg.registrationunit_id = product.registrationunit_id) regunit
,      ( case
           when packingnote.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 = packingnoteline.product_id
                 and pal.sizedefinition_id = packingnoteline.sizedefinition_id
                 and pal.finishingmethod_id = packingnoteline.finishingmethod_id
                 and pa.notenumber = packingnote.correctednotenumber )
         end) old_qty
,      packingnoteline.pricecog pricecog
,      ( select max(psz.sequencenumber)
         from   productsize psz
          where psz.product_id = product.product_id
            and psz.sizedefinition_id = sizedefinition.sizedefinition_id) sequencenumber
,     ( select code
        from   finishingmethod f
        where  f.finishingmethod_id = packingnoteline.finishingmethod_id) finishingmethodcode
,       businessunit.code bu_code
from   packingnoteline
  left outer join packcontents pc on pc.pack_id = packingnoteline.product_id
,      packingnote
,      product
,      sizedefinition
,      languages,businessunit
where  packingnoteline.packingnote_id = packingnote.packingnote_id
   and packingnoteline.product_id = product.product_id
   and packingnoteline.sizedefinition_id = sizedefinition.sizedefinition_id
   and businessunit.businessunit_id=packingnote.processbusinessunit_id

/
create or replace view V_DELIVERYNOTELINE_PRI
 (PACKINGNOTENUMBER, PRODUCTCODE, PRODUCTDESCRIPTION, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PGCUSTOMDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, 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, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED)
as SELECT PACKINGNOTE.NOTENUMBER PACKINGNOTENUMBER, PRODUCT.CODE PRODUCTCODE,
       (SELECT DESCRIPTION
         FROM   PRODUCT_DESC P
         WHERE  P.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
PRODUCTDESCRIPTION,
       (select pg.code
        from productgroup pg
        where pg.productgroup_id = product.productgroup_id
       ) productgroupcode,
       (SELECT DESCRIPTION
         FROM   PRODUCTGROUP_DESC A
         WHERE  A.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
PRODUCTGROUPDESCRIPTION,
       (SELECT PGPC.CUSTOMDESCRITPION
         FROM   PRODUCTGROUPPERCUSTOMER PGPC, DISTRIBUTIONPOINT DP, DEPARTMENT DEP
         WHERE  PGPC.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND PGPC.CUSTOMER_ID = DEP.CUSTOMER_ID
                AND DEP.DEPARTMENT_ID = DP.DEPARTMENT_ID AND DP.DISTRIBUTIONPOINT_ID = PACKINGNOTE.DISTRIBUTIONPOINT_ID)
PGCUSTOMDESCRIPTION,
       PACKINGNOTELINE.CUSTOMCODE, PACKINGNOTELINE.CUSTOMDESCRIPTION, SIZEDEFINITION.CODE,
       (SELECT DESCRIPTION
         FROM   SIZEDEFINITION_DESC S
         WHERE  S.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND
                S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDESCRIPTION,
       (SELECT DESCRIPTION
         FROM   FINISHINGMETHOD_DESC F
         WHERE  F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID AND
                F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODDESCRIPTION,
       PACKINGNOTELINE.PACKINGSEQUENCE, PACKINGNOTELINE.STANDARDAMOUNT,
       PACKINGNOTELINE.VARIATIONAMOUNT, PACKINGNOTELINE.DELIVEREDAMOUNT,
       PACKINGNOTELINE.TOBEDELIVEREDAMOUNT, PACKINGNOTELINE.REMARKFORPACKINGINSTRUCTIONS,
       PACKINGNOTELINE.SYSTEMUSER_ID, PACKINGNOTELINE.TIMESTAMP, LANGUAGES.CODE,
       PRODUCT.TYPEOFMERCHANDISE,
       (SELECT R.CODE
         FROM   REASONCODE R
         WHERE  R.REASONCODE_ID = PACKINGNOTELINE.FREEOFCHARGEREASON_ID) FREEOFCHARGEREASON,
       (SELECT DESCRIPTION
         FROM   REASONCODE_DESC RD
         WHERE  RD.REASONCODE_ID = PACKINGNOTELINE.FREEOFCHARGEREASON_ID AND
                RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREEOFCHARGEREASON_DESC,
       PACKINGNOTELINE.NOCHARGEFIRSTISSUE, PACKINGNOTELINE.NOCHARGEACTIVESEASON,
       PACKINGNOTELINE.DELIVEREDCOGQTY, PACKINGNOTELINE.ORIGIN LINE_ORIGIN,
       (CASE WHEN PACKINGNOTELINE.PRICE IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICE END) PRICE,
             PACKINGNOTELINE.AMOUNT, PACKINGNOTELINE.TAXGROUPCODE,
       (SELECT RG.CODE
         FROM   REGISTRATIONUNIT RG
         WHERE  RG.REGISTRATIONUNIT_ID = PRODUCT.REGISTRATIONUNIT_ID) REGUNIT,
       (CASE
          WHEN PACKINGNOTE.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 = PACKINGNOTELINE.PRODUCT_ID AND
                   PAL.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND
                   PAL.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID AND
                   PA.NOTENUMBER = PACKINGNOTE.CORRECTEDNOTENUMBER)
        END) OLD_QTY,
         (CASE WHEN PACKINGNOTELINE.PRICECOG IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICECOG END) PRICECOG,
   (SELECT MAX(PSZ.SEQUENCENUMBER) FROM PRODUCTSIZE PSZ WHERE PSZ.PRODUCT_ID = PRODUCT.PRODUCT_ID AND PSZ.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID) SEQUENCENUMBER
  , (SELECT CODE FROM FINISHINGMETHOD F
         WHERE  F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID) FINISHINGMETHODCODE
, (PACKINGNOTELINE.NOCHARGEPREVSHORTAGE + COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
WHERE DV.CAUSENOTE_ID = PACKINGNOTELINE.PACKINGNOTE_ID AND DV.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
AND DV.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND DV.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
AND DV.ORIGIN = 1 AND DV.SOILCOUNTSUBTYPE = 2), 0))  NOCHARGEPREVSHORTAGE
, (PACKINGNOTELINE.NOCHARGEPREVREJECTED + COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
WHERE DV.CAUSENOTE_ID = PACKINGNOTELINE.PACKINGNOTE_ID AND DV.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
AND DV.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND DV.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
AND DV.ORIGIN = 1 AND DV.SOILCOUNTSUBTYPE = 3), 0)) NOCHARGEPREVREJECTED
FROM   PACKINGNOTELINE, PACKINGNOTE, PRODUCT, SIZEDEFINITION, LANGUAGES
WHERE  PACKINGNOTELINE.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID AND
       PACKINGNOTELINE.PRODUCT_ID = PRODUCT.PRODUCT_ID AND
       PACKINGNOTELINE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID

/
create or replace view V_DELIVERYNOTELINE_SMG
 (SELNR, PACKINGNOTE_ID, PACKINGNOTELINE_ID, PACKINGNOTENUMBER, PRODUCTCODE, PRODUCTDESCRIPTION, PACKTYPE, PRODUCTGROUPDESCRIPTION, PGCUSTOMDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, PACKINGSEQUENCE, STANDARDAMOUNT, VARIATIONAMOUNT, DELIVEREDAMOUNT, TOBEDELIVEREDAMOUNT, ASSEMBLEDQUANTITY, REMARKFORPACKINGINSTRUCTIONS, USERNAME, TIMESTAMP, LANGUAGECODE, TYPEOFMERCHANDISE, PRODGRCODE, FREEOFCHARGEREASON
, FREEOFCHARGEREASON_DESC, NOCHARGEFIRSTISSUE, NOCHARGEACTIVESEASON, NOCHARGENOTCOG, LINE_ORIGIN, PRICE, AMOUNT, TAXGROUPCODE, REGUNIT, OLD_QTY, PRICECOG, SEQUENCENUMBER, FINISHINGMETHODCODE, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, PNLBALANCE, PN_PSF, TOTLOG, TOTCOG, DNSTATUS, EXCLUDESUPPRESS, PRODUCT_ID, SIZEDEFINITION_ID, FINISHINGMETHOD_ID, REFERENCE, SELECT_NR, REASONCODE, REASONCODEDESC, ORIGIN, DV_AMOUNT, DVDELDATE, DELIVERYDATE, DVOTHERSOIL)
as SELECT --+ INDEX(SIZEDEFINITION XPKSIZEDEFINITION)
1 selnr, PACKINGNOTE.PACKINGNOTE_ID,PACKINGNOTELINE.PACKINGNOTELINE_ID,
 PACKINGNOTE.NOTENUMBER PACKINGNOTENUMBER, PRODUCT.CODE PRODUCTCODE,
       (SELECT P.DESCRIPTION  FROM   PRODUCT_DESC P
         WHERE  P.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
PRODUCTDESCRIPTION,
product.packtype,
       (SELECT A.DESCRIPTION  FROM   PRODUCTGROUP_DESC A
         WHERE  A.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
PRODUCTGROUPDESCRIPTION,
       (SELECT PGPC.CUSTOMDESCRITPION FROM   PRODUCTGROUPPERCUSTOMER PGPC, DISTRIBUTIONPOINT DP, DEPARTMENT DEP
         WHERE  PGPC.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND PGPC.CUSTOMER_ID = DEP.CUSTOMER_ID
                AND DEP.DEPARTMENT_ID = DP.DEPARTMENT_ID AND DP.DISTRIBUTIONPOINT_ID = PACKINGNOTE.DISTRIBUTIONPOINT_ID)
PGCUSTOMDESCRIPTION,
       PACKINGNOTELINE.CUSTOMCODE productcustomcode, PACKINGNOTELINE.CUSTOMDESCRIPTION productcustomdescription, SIZEDEFINITION.CODE sizecode,
       (SELECT S.DESCRIPTION FROM   SIZEDEFINITION_DESC S
         WHERE  S.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND
                S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDESCRIPTION,
       (SELECT F.DESCRIPTION  FROM   FINISHINGMETHOD_DESC F
         WHERE  F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID AND
                F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODDESCRIPTION,
       PACKINGNOTELINE.PACKINGSEQUENCE, PACKINGNOTELINE.STANDARDAMOUNT,
       PACKINGNOTELINE.VARIATIONAMOUNT, PACKINGNOTELINE.DELIVEREDAMOUNT,
       PACKINGNOTELINE.TOBEDELIVEREDAMOUNT,PACKINGNOTELINE.ASSEMBLEDQUANTITY, PACKINGNOTELINE.REMARKFORPACKINGINSTRUCTIONS,
       PACKINGNOTELINE.SYSTEMUSER_ID username, PACKINGNOTELINE.TIMESTAMP, LANGUAGES.CODE languagecode,
       PRODUCT.TYPEOFMERCHANDISE,
       ( select pg.code from productgroup pg where product.productgroup_id=pg.productgroup_id) prodgrcode,
       (SELECT R.CODE FROM   REASONCODE R
         WHERE  R.REASONCODE_ID = PACKINGNOTELINE.FREEOFCHARGEREASON_ID) FREEOFCHARGEREASON,
       (SELECT RD.DESCRIPTION FROM   REASONCODE_DESC RD
         WHERE  RD.REASONCODE_ID = PACKINGNOTELINE.FREEOFCHARGEREASON_ID AND
                RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREEOFCHARGEREASON_DESC,
       PACKINGNOTELINE.NOCHARGEFIRSTISSUE, PACKINGNOTELINE.NOCHARGEACTIVESEASON,
       PACKINGNOTELINE.DELIVEREDCOGQTY NOCHARGENOTCOG, PACKINGNOTELINE.ORIGIN LINE_ORIGIN,
       (CASE WHEN PACKINGNOTELINE.PRICE IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICE END) PRICE,
             PACKINGNOTELINE.AMOUNT, PACKINGNOTELINE.TAXGROUPCODE,
       (SELECT RG.CODE  FROM   REGISTRATIONUNIT RG
         WHERE  RG.REGISTRATIONUNIT_ID = PRODUCT.REGISTRATIONUNIT_ID) REGUNIT,
       (CASE
          WHEN PACKINGNOTE.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 = PACKINGNOTELINE.PRODUCT_ID AND
                   PAL.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND
                   PAL.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID AND
                   PA.NOTENUMBER = PACKINGNOTE.CORRECTEDNOTENUMBER)
        END) OLD_QTY,
         (CASE WHEN PACKINGNOTELINE.PRICECOG IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICECOG END) PRICECOG,
   (SELECT MAX(PSZ.SEQUENCENUMBER) FROM PRODUCTSIZE PSZ WHERE PSZ.PRODUCT_ID = PRODUCT.PRODUCT_ID AND PSZ.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID) SEQUENCENUMBER
  , (SELECT CODE FROM FINISHINGMETHOD F
         WHERE  F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID) FINISHINGMETHODCODE
, /*(PACKINGNOTELINE.NOCHARGEPREVSHORTAGE + COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
WHERE DV.CAUSENOTE_ID = PACKINGNOTELINE.PACKINGNOTE_ID AND DV.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
AND DV.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND DV.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
AND DV.ORIGIN = 1 AND DV.SOILCOUNTSUBTYPE = 2), 0))*/ 0 NOCHARGEPREVSHORTAGE
, /*(PACKINGNOTELINE.NOCHARGEPREVREJECTED + COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
WHERE DV.CAUSENOTE_ID = PACKINGNOTELINE.PACKINGNOTE_ID AND DV.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
AND DV.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND DV.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
AND DV.ORIGIN = 1 AND DV.SOILCOUNTSUBTYPE = 3), 0))*/ 0 NOCHARGEPREVREJECTED
,(PACKINGNOTELINE.Standardamount+ PACKINGNOTELINE.Variationamount-PACKINGNOTELINE.Deliveredamount) pnlbalance
,(PACKINGNOTE.packingnote_id || PACKINGNOTELINE.product_id || PACKINGNOTELINE.sizedefinition_id || PACKINGNOTELINE.finishingmethod_id) pn_psf,
(select sum(a.deliveredamount-a.deliveredcogqty) from packingnoteline a
where a.packingnote_id=PACKINGNOTE.packingnote_id and a.product_id=PRODUCT.product_id group by a.packingnote_id, PRODUCT.product_id) totLOG,
(select sum(a.deliveredcogqty) from packingnoteline a
where a.packingnote_id=PACKINGNOTE.packingnote_id and a.product_id=PRODUCT.product_id group by a.packingnote_id, PRODUCT.product_id) totCOG,
( select st.code from status st where PACKINGNOTE.Status_id=st.status_id) DNStatus
, /*coalesce((select min(dev.deliveryvariations_id) from deliveryvariations dev where dev.packingnote_id = PACKINGNOTE.Packingnote_Id and dev.amount < 0 and dev.updaterentqty = 'Y'
  and dev.product_id = PRODUCT.Product_Id and dev.sizedefinition_id = SIZEDEFINITION.sizedefinition_id and dev.finishingmethod_id = PACKINGNOTELINE.Finishingmethod_Id), 0)*/
  0 ExcludeSuppress
, PACKINGNOTELINE.product_id, PACKINGNOTELINE.sizedefinition_id, PACKINGNOTELINE.finishingmethod_id, dv.reference
, case when (PACKINGNOTELINE.packingnoteline_id is not null and (dv.productconversioncpl_id is null or (dv.productconversioncpl_id is not null and dv.updaterentqty = 'Y' and dv.amount > 0)))
    then 1
  when (PACKINGNOTELINE.packingnoteline_id is null and (dv.productconversioncpl_id is null or (dv.productconversioncpl_id is not null and dv.updaterentqty = 'Y' and dv.amount > 0)))
    then 2 else 0 end select_nr
,(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 = LANGUAGES.language_id) reasoncodedesc
, dv.origin, dv.amount dv_amount, to_char(dv.deliverydate,'DD-MON-YYYY') dvdeldate, dv.deliverydate
, case when dv.origin = 1
  then (case when exists (select -- + INDEX (dvc XSPEED2DELIVERYVARIATIONS)
                    1 from deliveryvariations dv2
              where dv2.packingnote_id = dv.packingnote_id and dv2.product_id = dv.product_id
              and dv2.sizedefinition_id = dv.sizedefinition_id and dv2.finishingmethod_id =  dv.finishingmethod_id
              and dv2.deliveryvariations_id <> dv.deliveryvariations_id and dv2.origin > 1)
       then 1 else 0 END)
  else 1 end dvothersoil
FROM   PACKINGNOTE, PACKINGNOTELINE
left outer join deliveryvariations dv on (dv.packingnote_id = PACKINGNOTELINE.Packingnote_Id and dv.product_id = PACKINGNOTELINE.product_id
    and dv.sizedefinition_id = PACKINGNOTELINE.sizedefinition_id and dv.finishingmethod_id = PACKINGNOTELINE.finishingmethod_id),
PRODUCT, SIZEDEFINITION, LANGUAGES, BUSINESSUNIT PROCESSBU, SYSTEMSETTING SS3
WHERE  PACKINGNOTELINE.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID AND
       PRODUCT.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID AND
       SIZEDEFINITION.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID
  and PROCESSBU.Businessunit_Id = PACKINGNOTE.Processbusinessunit_Id
  AND SS3.PLANT_ID = PROCESSBU.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
       and (lpad(SS3.VALUE, 1) = 'Y' or  (lpad(SS3.VALUE, 1) <> 'Y' and PACKINGNOTELINE.DELIVEREDAMOUNT <> 0))
union all
SELECT --+ INDEX(SIZEDEFINITION XPKSIZEDEFINITION)
1 selnr, PACKINGNOTE.PACKINGNOTE_ID,PACKINGNOTELINE.PACKINGNOTELINE_ID,
 PACKINGNOTE.NOTENUMBER PACKINGNOTENUMBER, PRODUCT.CODE PRODUCTCODE,
       (SELECT P.DESCRIPTION  FROM   PRODUCT_DESC P
         WHERE  P.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
PRODUCTDESCRIPTION,
product.packtype,
       (SELECT A.DESCRIPTION  FROM   PRODUCTGROUP_DESC A
         WHERE  A.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
PRODUCTGROUPDESCRIPTION,
       (SELECT PGPC.CUSTOMDESCRITPION FROM   PRODUCTGROUPPERCUSTOMER PGPC, DISTRIBUTIONPOINT DP, DEPARTMENT DEP
         WHERE  PGPC.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND PGPC.CUSTOMER_ID = DEP.CUSTOMER_ID
                AND DEP.DEPARTMENT_ID = DP.DEPARTMENT_ID AND DP.DISTRIBUTIONPOINT_ID = PACKINGNOTE.DISTRIBUTIONPOINT_ID)
PGCUSTOMDESCRIPTION,
       PACKINGNOTELINE.CUSTOMCODE productcustomcode, PACKINGNOTELINE.CUSTOMDESCRIPTION productcustomdescription, SIZEDEFINITION.CODE sizecode,
       (SELECT S.DESCRIPTION FROM   SIZEDEFINITION_DESC S
         WHERE  S.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND
                S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDESCRIPTION,
       (SELECT F.DESCRIPTION  FROM   FINISHINGMETHOD_DESC F
         WHERE  F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID AND
                F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODDESCRIPTION,
       PACKINGNOTELINE.PACKINGSEQUENCE, PACKINGNOTELINE.STANDARDAMOUNT,
       PACKINGNOTELINE.VARIATIONAMOUNT, PACKINGNOTELINE.DELIVEREDAMOUNT,
       PACKINGNOTELINE.TOBEDELIVEREDAMOUNT,PACKINGNOTELINE.ASSEMBLEDQUANTITY, PACKINGNOTELINE.REMARKFORPACKINGINSTRUCTIONS,
       PACKINGNOTELINE.SYSTEMUSER_ID username, PACKINGNOTELINE.TIMESTAMP, LANGUAGES.CODE languagecode,
       PRODUCT.TYPEOFMERCHANDISE,
       ( select pg.code from productgroup pg where product.productgroup_id=pg.productgroup_id) prodgrcode,
       (SELECT R.CODE FROM   REASONCODE R
         WHERE  R.REASONCODE_ID = PACKINGNOTELINE.FREEOFCHARGEREASON_ID) FREEOFCHARGEREASON,
       (SELECT RD.DESCRIPTION FROM   REASONCODE_DESC RD
         WHERE  RD.REASONCODE_ID = PACKINGNOTELINE.FREEOFCHARGEREASON_ID AND
                RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREEOFCHARGEREASON_DESC,
       PACKINGNOTELINE.NOCHARGEFIRSTISSUE, PACKINGNOTELINE.NOCHARGEACTIVESEASON,
       PACKINGNOTELINE.DELIVEREDCOGQTY NOCHARGENOTCOG, PACKINGNOTELINE.ORIGIN LINE_ORIGIN,
       (CASE WHEN PACKINGNOTELINE.PRICE IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICE END) PRICE,
             PACKINGNOTELINE.AMOUNT, PACKINGNOTELINE.TAXGROUPCODE,
       (SELECT RG.CODE  FROM   REGISTRATIONUNIT RG
         WHERE  RG.REGISTRATIONUNIT_ID = PRODUCT.REGISTRATIONUNIT_ID) REGUNIT,
       (CASE
          WHEN PACKINGNOTE.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 = PACKINGNOTELINE.PRODUCT_ID AND
                   PAL.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND
                   PAL.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID AND
                   PA.NOTENUMBER = PACKINGNOTE.CORRECTEDNOTENUMBER)
        END) OLD_QTY,
         (CASE WHEN PACKINGNOTELINE.PRICECOG IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICECOG END) PRICECOG,
   (SELECT MAX(PSZ.SEQUENCENUMBER) FROM PRODUCTSIZE PSZ WHERE PSZ.PRODUCT_ID = PRODUCT.PRODUCT_ID AND PSZ.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID) SEQUENCENUMBER
  , (SELECT CODE FROM FINISHINGMETHOD F
         WHERE  F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID) FINISHINGMETHODCODE
, /*(PACKINGNOTELINE.NOCHARGEPREVSHORTAGE + COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
WHERE DV.CAUSENOTE_ID = PACKINGNOTELINE.PACKINGNOTE_ID AND DV.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
AND DV.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND DV.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
AND DV.ORIGIN = 1 AND DV.SOILCOUNTSUBTYPE = 2), 0))*/ 0 NOCHARGEPREVSHORTAGE
, /*(PACKINGNOTELINE.NOCHARGEPREVREJECTED + COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
WHERE DV.CAUSENOTE_ID = PACKINGNOTELINE.PACKINGNOTE_ID AND DV.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
AND DV.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND DV.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
AND DV.ORIGIN = 1 AND DV.SOILCOUNTSUBTYPE = 3), 0))*/ 0 NOCHARGEPREVREJECTED
,(PACKINGNOTELINE.Standardamount+ PACKINGNOTELINE.Variationamount-PACKINGNOTELINE.Deliveredamount) pnlbalance
,(PACKINGNOTE.packingnote_id || PACKINGNOTELINE.product_id || PACKINGNOTELINE.sizedefinition_id || PACKINGNOTELINE.finishingmethod_id) pn_psf,
(select sum(a.deliveredamount-a.deliveredcogqty) from packingnoteline a
where a.packingnote_id=PACKINGNOTE.packingnote_id and a.product_id=PRODUCT.product_id group by a.packingnote_id, PRODUCT.product_id) totLOG,
(select sum(a.deliveredcogqty) from packingnoteline a
where a.packingnote_id=PACKINGNOTE.packingnote_id and a.product_id=PRODUCT.product_id group by a.packingnote_id, PRODUCT.product_id) totCOG,
( select st.code from status st where PACKINGNOTE.Status_id=st.status_id) DNStatus
, /*coalesce((select min(dev.deliveryvariations_id) from deliveryvariations dev where dev.packingnote_id = PACKINGNOTE.Packingnote_Id and dev.amount < 0 and dev.updaterentqty = 'Y'
  and dev.product_id = PRODUCT.Product_Id and dev.sizedefinition_id = SIZEDEFINITION.sizedefinition_id and dev.finishingmethod_id = PACKINGNOTELINE.Finishingmethod_Id), 0)*/
  0 ExcludeSuppress
, PACKINGNOTELINE.product_id, PACKINGNOTELINE.sizedefinition_id, PACKINGNOTELINE.finishingmethod_id, dvc.reference
, 3 select_nr
,(select rc.code from reasoncode rc where dvc.adjustmentreason_id = rc.reasoncode_id) reasoncode
,(select rcd.description from reasoncode_desc rcd where dvc.adjustmentreason_id = rcd.reasoncode_id and rcd.language_id = LANGUAGES.language_id) reasoncodedesc
, dvc.origin, dvc.amount dv_amount, to_char(dvc.deliverydate,'DD-MON-YYYY') dvdeldate, dvc.deliverydate
, 1 dvothersoil
FROM   PACKINGNOTE, PACKINGNOTELINE
inner join deliveryvariations dvc on (dvc.causenote_id = PACKINGNOTELINE.Packingnote_Id and dvc.product_id = PACKINGNOTELINE.product_id
    and dvc.sizedefinition_id = PACKINGNOTELINE.sizedefinition_id and dvc.finishingmethod_id = PACKINGNOTELINE.finishingmethod_id
    and dvc.amount < 0 and dvc.adjustmentreason_id is not null and dvc.origin in (4,5)),
PRODUCT, SIZEDEFINITION, LANGUAGES, BUSINESSUNIT PROCESSBU, SYSTEMSETTING SS3
WHERE  PACKINGNOTELINE.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID AND
       PRODUCT.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID AND
       SIZEDEFINITION.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID
  and PROCESSBU.Businessunit_Id = PACKINGNOTE.Processbusinessunit_Id
  AND SS3.PLANT_ID = PROCESSBU.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
       and (lpad(SS3.VALUE, 1) = 'Y' or  (lpad(SS3.VALUE, 1) <> 'Y' and PACKINGNOTELINE.DELIVEREDAMOUNT <> 0))
/*union all
SELECT  --+ INDEX(SIZEDEFINITION XPKSIZEDEFINITION)
distinct 2 selnr, PACKINGNOTE.PACKINGNOTE_ID,-1 packingnoteline_id,
 PACKINGNOTE.NOTENUMBER PACKINGNOTENUMBER, PRODUCT.CODE PRODUCTCODE,
       (SELECT P.DESCRIPTION   FROM   PRODUCT_DESC P
         WHERE  P.PRODUCT_ID = dv.PRODUCT_ID AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
PRODUCTDESCRIPTION,
product.packtype,
       (SELECT A.DESCRIPTION FROM   PRODUCTGROUP_DESC A
         WHERE  A.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
PRODUCTGROUPDESCRIPTION,
       (SELECT PGPC.CUSTOMDESCRITPION  FROM   PRODUCTGROUPPERCUSTOMER PGPC, DISTRIBUTIONPOINT DP, DEPARTMENT DEP
         WHERE  PGPC.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND PGPC.CUSTOMER_ID = DEP.CUSTOMER_ID
                AND DEP.DEPARTMENT_ID = DP.DEPARTMENT_ID AND DP.DISTRIBUTIONPOINT_ID = PACKINGNOTE.DISTRIBUTIONPOINT_ID)
PGCUSTOMDESCRIPTION,
       '' CUSTOMCODE, '' CUSTOMDESCRIPTION, SIZEDEFINITION.CODE,
       (SELECT S.DESCRIPTION     FROM   SIZEDEFINITION_DESC S
         WHERE  S.SIZEDEFINITION_ID = dv.SIZEDEFINITION_ID AND
                S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDESCRIPTION,
       (SELECT F.DESCRIPTION  FROM   FINISHINGMETHOD_DESC F
         WHERE  F.FINISHINGMETHOD_ID = dv.FINISHINGMETHOD_ID AND
                F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODDESCRIPTION,
       0 PACKINGSEQUENCE, 0 STANDARDAMOUNT,
       0 VARIATIONAMOUNT, 0 DELIVEREDAMOUNT,
       0 TOBEDELIVEREDAMOUNT,0 ASSEMBLEDQUANTITY, '' REMARKFORPACKINGINSTRUCTIONS,
       null SYSTEMUSER_ID, null TIMESTAMP, LANGUAGES.CODE,
       PRODUCT.TYPEOFMERCHANDISE,
       ( select pg.code from productgroup pg where product.productgroup_id=pg.productgroup_id)prodgrcode,
       '' FREEOFCHARGEREASON,
       '' FREEOFCHARGEREASON_DESC,
       null NOCHARGEFIRSTISSUE, null NOCHARGEACTIVESEASON,
       0 DELIVEREDCOGQTY, null LINE_ORIGIN,
       null PRICE,
       0 AMOUNT, '' TAXGROUPCODE,
       (SELECT RG.CODE FROM   REGISTRATIONUNIT RG
         WHERE  RG.REGISTRATIONUNIT_ID = PRODUCT.REGISTRATIONUNIT_ID) REGUNIT,
       0 OLD_QTY,
       null PRICECOG,
   (SELECT MAX(PSZ.SEQUENCENUMBER) FROM PRODUCTSIZE PSZ WHERE PSZ.PRODUCT_ID = PRODUCT.PRODUCT_ID AND PSZ.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID) SEQUENCENUMBER
, (SELECT F.CODE FROM FINISHINGMETHOD F WHERE  F.FINISHINGMETHOD_ID = dv.FINISHINGMETHOD_ID) FINISHINGMETHODCODE
, 0 NOCHARGEPREVSHORTAGE
, 0 NOCHARGEPREVREJECTED
, 0 pnlbalance
,( PACKINGNOTE.packingnote_id || product.product_id || SIZEDEFINITION.sizedefinition_id || DV.finishingmethod_id) pn_psf, 0 totLOg, 0 totCOG
,( select st.code from status st where st.status_id = PACKINGNOTE.Status_id) DNStatus
, coalesce((select min(dev2.deliveryvariations_id) from deliveryvariations dev2 where dev2.packingnote_id = PACKINGNOTE.Packingnote_Id and dev2.amount < 0 and dev2.updaterentqty = 'Y'
  and dev2.product_id = PRODUCT.Product_Id and dev2.sizedefinition_id = SIZEDEFINITION.sizedefinition_id and dev2.finishingmethod_id = dv.Finishingmethod_Id), 0) ExcludeSuppress
, product.product_id, SIZEDEFINITION.sizedefinition_id, DV.finishingmethod_id
FROM   PACKINGNOTE, PRODUCT, SIZEDEFINITION, LANGUAGES, DELIVERYVARIATIONS DV
WHERE  DV.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID AND
       PRODUCT.PRODUCT_ID = DV.PRODUCT_ID AND
       SIZEDEFINITION.SIZEDEFINITION_ID = DV.SIZEDEFINITION_ID
       and not exists (select 1 from packingnoteline pnl where pnl.packingnote_id = packingnote.packingnote_id and pnl.product_id = dv.product_id and pnl.sizedefinition_id = dv.sizedefinition_id and pnl.finishingmethod_id = dv.finishingmethod_id )
       -- Johanna asked to remove completely the "0 lines" which means no more delivery variations for SMG*/

/
create or replace view V_DELIVERYNOTELINE_SNG
 (PACKINGNOTENUMBER, PRODUCTCODE, PRODUCTDESCRIPTION, ACTIVITYDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, PACKINGSEQUENCE, STANDARDAMOUNT, VARIATIONAMOUNT, DELIVEREDAMOUNT, TOBEDELIVEREDAMOUNT, REMARKFORPACKINGINSTRUCTIONS, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE, TYPEOFMERCHANDISE, FREEOFCHARGEREASON, FREEOFCHARGEREASON_DESC, NOCHARGEFIRSTISSUE, NOCHARGEACTIVESEASON, NOCHARGENOTCOG, LINE_ORIGIN, PRICE
, AMOUNT, TAXGROUPCODE, REGUNIT, OLD_QTY, PRICECOG, SEQUENCENUMBER, FINISHINGMETHODCODE, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, ACTIVITYCODE)
as SELECT PACKINGNOTE.NOTENUMBER PACKINGNOTENUMBER, PRODUCT.CODE PRODUCTCODE,
       (SELECT P.DESCRIPTION
         FROM   PRODUCT_DESC P
         WHERE  P.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
PRODUCTDESCRIPTION,
       (SELECT A.DESCRIPTION
         FROM   ACTIVITY_DESC A, PRODUCTGROUP PG
         WHERE  A.ACTIVITY_ID = PG.ACTIVITY_ID AND PG.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
ACTIVITYDESCRIPTION,
       PACKINGNOTELINE.CUSTOMCODE PRODUCTCUSTOMCODE, PACKINGNOTELINE.CUSTOMDESCRIPTION PRODUCTCUSTOMDESCRIPTION, SIZEDEFINITION.CODE SIZECODE,
       (SELECT S.DESCRIPTION
         FROM   SIZEDEFINITION_DESC S
         WHERE  S.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND
                S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDESCRIPTION,
       (SELECT F.DESCRIPTION
         FROM   FINISHINGMETHOD_DESC F
         WHERE  F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID AND
                F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODDESCRIPTION,
       PACKINGNOTELINE.PACKINGSEQUENCE, PACKINGNOTELINE.STANDARDAMOUNT,
       PACKINGNOTELINE.VARIATIONAMOUNT, PACKINGNOTELINE.DELIVEREDAMOUNT,
       PACKINGNOTELINE.TOBEDELIVEREDAMOUNT, PACKINGNOTELINE.REMARKFORPACKINGINSTRUCTIONS,
       PACKINGNOTELINE.SYSTEMUSER_ID, PACKINGNOTELINE.TIMESTAMP, LANGUAGES.CODE LANGUAGECODE,
       PRODUCT.TYPEOFMERCHANDISE,
       (SELECT R.CODE
         FROM   REASONCODE R
         WHERE  R.REASONCODE_ID = PACKINGNOTELINE.FREEOFCHARGEREASON_ID) FREEOFCHARGEREASON,
       (SELECT RD.DESCRIPTION
         FROM   REASONCODE_DESC RD
         WHERE  RD.REASONCODE_ID = PACKINGNOTELINE.FREEOFCHARGEREASON_ID AND
                RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREEOFCHARGEREASON_DESC,
       PACKINGNOTELINE.NOCHARGEFIRSTISSUE, PACKINGNOTELINE.NOCHARGEACTIVESEASON,
       PACKINGNOTELINE.DELIVEREDCOGQTY NOCHARGENOTCOG, PACKINGNOTELINE.ORIGIN LINE_ORIGIN,
       COALESCE(PACKINGNOTELINE.PRICE, 0) PRICE,
             PACKINGNOTELINE.AMOUNT, PACKINGNOTELINE.TAXGROUPCODE,
       (SELECT RG.DESCRIPTION
         FROM   REGISTRATIONUNIT_DESC RG
         WHERE  RG.REGISTRATIONUNIT_ID = PRODUCT.REGISTRATIONUNIT_ID AND RG.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) REGUNIT,
       (CASE
          WHEN PACKINGNOTE.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 = PACKINGNOTELINE.PRODUCT_ID AND
                   PAL.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND
                   PAL.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID AND
                   PA.NOTENUMBER = PACKINGNOTE.CORRECTEDNOTENUMBER)
        END) OLD_QTY,
         COALESCE(PACKINGNOTELINE.PRICECOG, 0) PRICECOG,
   (SELECT MAX(PSZ.SEQUENCENUMBER) FROM PRODUCTSIZE PSZ WHERE PSZ.PRODUCT_ID = PRODUCT.PRODUCT_ID AND PSZ.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID) SEQUENCENUMBER
  , (SELECT F.CODE FROM FINISHINGMETHOD F
         WHERE  F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID) FINISHINGMETHODCODE
, (PACKINGNOTELINE.NOCHARGEPREVSHORTAGE + COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
WHERE DV.CAUSENOTE_ID = PACKINGNOTELINE.PACKINGNOTE_ID AND DV.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
AND DV.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND DV.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
AND DV.ORIGIN = 1 AND DV.SOILCOUNTSUBTYPE = 2), 0))  NOCHARGEPREVSHORTAGE
, (PACKINGNOTELINE.NOCHARGEPREVREJECTED + COALESCE((SELECT SUM (DV.AMOUNT) FROM DELIVERYVARIATIONS DV
WHERE DV.CAUSENOTE_ID = PACKINGNOTELINE.PACKINGNOTE_ID AND DV.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
AND DV.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID AND DV.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
AND DV.ORIGIN = 1 AND DV.SOILCOUNTSUBTYPE = 3), 0)) NOCHARGEPREVREJECTED
,  (SELECT A.CODE FROM   ACTIVITY A, PRODUCTGROUP PG
    WHERE  A.ACTIVITY_ID = PG.ACTIVITY_ID AND PG.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID) ACTIVITYCODE
FROM   PACKINGNOTELINE, PACKINGNOTE, PRODUCT, SIZEDEFINITION, LANGUAGES
WHERE  PACKINGNOTELINE.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID AND
       PACKINGNOTELINE.PRODUCT_ID = PRODUCT.PRODUCT_ID AND
       PACKINGNOTELINE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID

/
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 = '40')
   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)
as select pt.packingnote_id, pt.taxgroupcode, pt.taxgroupdescription, pt.taxpercentage, pt.amount
from packingnotetax pt

/
create or replace view V_DELIVERYNOTEUNIQUEITEMS_SMG
 (WEARERNUMBER, CUSTOMER_ID, WEARERFULLNAME, WEARERFIRSTNAME, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDEFINITIONCODE, PRIMARYID, FLAGSTARTDATE, LANGUAGECODE, DISTRIBUTIONPOINT_ID, BUSINESSUNIT_ID)
as select w.wearernumber, --uniqueitems with uniqueitemflag and no wearer/weareremployment flag
       d.customer_id,
       w.fullname wearerfullname,
       w.firstname wearerfirstname,
       d.departmentnumber,
       d.description departmentdescription,
       (select p.code from product p where p.product_id = ui.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 sd.code
          from sizedefinition sd
         where sd.sizedefinition_id = ui.sizedefinition_id) sizedefinitioncode,
       ui.primaryid,
       v.startdate flagstartdate,
       l.code languagecode,
       we.distributionpoint_id,
       ui.businessunit_id
  from wearer            w,
       weareremployment  we,
       wearerinventory   wi,
       department        d,
       distributionpoint dp,
       uniqueitemnonpool uinp,
       --uniqueitemflag    uif,
       languages         l,
       customer     c,
       (select max(uif.startdate) startdate, uii.uniqueitem_id
          from uniqueitemflag uif, uniqueitem uii, automaticflag af
         where uif.uniqueitem_id = uii.uniqueitem_id
                and uif.flag_id = af.flag_id
                 and af.plant_id is null
                   and af.event in
                       ('Decrease max inv. after return to stock items with this flag',
                         'End of Season',
                         'Flag for return to stock due to manual decrease of max inv',
                         'Product contract ended for customer',
                         'Quit wearer',
                         'Replacement requested using replacement button',
                         'Substitute garment',
                         'Temporary wearer inventory rent stop')
                         group by uii.uniqueitem_id) v
                  join uniqueitem ui on ui.uniqueitem_id = v.uniqueitem_id
         where we.wearer_id = w.wearer_id
   and we.distributionpoint_id = dp.distributionpoint_id
   and dp.department_id = d.department_id
   and we.weareremployment_id = wi.weareremployment_id
   and ui.product_id = wi.product_id
   and ui.sizedefinition_id = wi.sizedefinition_id
   and uinp.weareremployment_id = we.weareremployment_id
   and uinp.wearerinventory_id = wi.wearerinventory_id
   and uinp.uniqueitem_id = ui.uniqueitem_id
   and w.flag_id is null
   and we.flag_id is null
   and w.customer_id = c.customer_id
   and d.customer_id=c.customer_id
   and c.deliverynotelayout_id in
       (select fl.formlayout_id
          from formlayout fl
         where fl.formtype = 'DN'
           and fl.code in ('1', '11', '12', '13'))
  union
select w.wearernumber, --uniqueitems with wearer flag and no uniqueitemflag/weareremployment flag
       w.customer_id,
       w.fullname wearerfullname,
       w.firstname wearerfirstname,
       d.departmentnumber,
       d.description departmentdescription,
       (select p.code from product p where p.product_id = ui.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 sd.code
          from sizedefinition sd
         where sd.sizedefinition_id = ui.sizedefinition_id) sizedefinitioncode,
       ui.primaryid,
       w.flagstartdate flagstartdate,
       l.code languagecode,
       we.distributionpoint_id,
       ui.businessunit_id
  from wearer            w,
       weareremployment  we,
       wearerinventory   wi,
       department        d,
       distributionpoint dp,
       uniqueitem        ui,
       uniqueitemnonpool uinp,
       languages         l,
       businessunit      bu,
       customer      c,
       automaticflag af
 where we.wearer_id = w.wearer_id
   and we.distributionpoint_id = dp.distributionpoint_id
   and dp.department_id = d.department_id
   and we.weareremployment_id = wi.weareremployment_id
   and ui.product_id = wi.product_id
   and ui.sizedefinition_id = wi.sizedefinition_id
   and uinp.weareremployment_id = we.weareremployment_id
   and uinp.wearerinventory_id = wi.wearerinventory_id
   and uinp.uniqueitem_id = ui.uniqueitem_id
   and ui.businessunit_id = bu.businessunit_id
   and w.flag_id = af.flag_id
   AND (af.plant_id is null or af.plant_id = bu.plant_id)
   and (af.event in
               ('Decrease max inv. after return to stock items with this flag',
                 'End of Season',
                 'Flag for return to stock due to manual decrease of max inv',
                 'Product contract ended for customer',
                 'Quit wearer',
                 'Replacement requested using replacement button',
                 'Substitute garment',
                 'Temporary wearer inventory rent stop'))
   and w.flag_id is not null
   and we.flag_id is null
   and w.customer_id = c.customer_id
   and c.deliverynotelayout_id in
       (select fl.formlayout_id
          from formlayout fl
         where fl.formtype = 'DN'
           and fl.code in ('1', '11', '12', '13'))
union
select w.wearernumber, --uniqueitems with weareremployment flag and no uniqueitemflag/wearer flag
       w.customer_id,
       w.fullname wearerfullname,
       w.firstname wearerfirstname,
       d.departmentnumber,
       d.description departmentdescription,
       (select p.code from product p where p.product_id = ui.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 sd.code
          from sizedefinition sd
         where sd.sizedefinition_id = ui.sizedefinition_id) sizedefinitioncode,
       ui.primaryid,
       w.flagstartdate flagstartdate,
       l.code languagecode,
       we.distributionpoint_id,
       ui.businessunit_id
  from wearer            w,
       weareremployment  we,
       wearerinventory   wi,
       department        d,
       distributionpoint dp,
       uniqueitem        ui,
       uniqueitemnonpool uinp,
       languages         l,
       businessunit      bu,
       customer     c
       , automaticflag af
 where we.wearer_id = w.wearer_id
   and we.distributionpoint_id = dp.distributionpoint_id
   and dp.department_id = d.department_id
   and we.weareremployment_id = wi.weareremployment_id
   and ui.product_id = wi.product_id
   and ui.sizedefinition_id = wi.sizedefinition_id
   and uinp.weareremployment_id = we.weareremployment_id
   and uinp.wearerinventory_id = wi.wearerinventory_id
   and uinp.uniqueitem_id = ui.uniqueitem_id
   and ui.businessunit_id = bu.businessunit_id
   and we.flag_id = af.flag_id
   AND (af.plant_id is null or af.plant_id = bu.plant_id)
   and (af.event in
               ('Decrease max inv. after return to stock items with this flag',
                 'End of Season',
                 'Flag for return to stock due to manual decrease of max inv',
                 'Product contract ended for customer',
                 'Quit wearer',
                 'Replacement requested using replacement button',
                 'Substitute garment',
                 'Temporary wearer inventory rent stop'))
   and w.flag_id is null
   and we.flag_id is not null
   and w.customer_id = c.customer_id
   and c.deliverynotelayout_id in
       (select fl.formlayout_id
          from formlayout fl
         where fl.formtype = 'DN'
           and fl.code in ('1', '11', '12', '13'))

/
create or replace view V_DELIVERYNOTE_BDE
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTSTREET2, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTOMERHOUSENUMBER, CUSTOMERHOUSENUMBEREXT, CUSTCOUNTRY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE
, REMARK, PROCESSBUDESCRIPTION, PROCESSBUCODE, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTNAME, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, YEAR, PRICESCALCULATED, TOTALAMOUNT, TOTALAMOUNTEXCLUDINGVAT, WEIGHINGTICKET_ID, DECIMALS, INVOICEAMOUNTDECIMALS, CURRENCYCODE, USER_NAME, USER_FULLNAME, ROUTESTOP_CONTAINERNO
, DEP_PLDEP_CODE, DEP_PLDEP_DESCRIPTION, CUST_PLDEP_CODE, CUST_PLDEP_DESCRIPTION, SERVICETEAM_CODE, SERVICETEAM_DESC, COLLECTIONRESPEMPLOYEE, CONTACTPERSONNAME, DAYNUMBER, PROCESSBUSINESSUNIT_ID, INVOICEBUSINESSUNIT_ID, MAXCOMPLETENESSDAYS, PRINTDELNOTEZEROLINES, PRODUCTIONLINE, INVENTORY)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(select cn.deliverydate from PACKINGNOTE cn where PACKINGNOTE.CORRECTEDNOTENUMBER = cn.notenumber
  and PACKINGNOTE.CORRECTEDNOTENUMBER<>0) correctiondate,
PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME,
ADDRESS.street CUSTOMERSTREET, ADDRESS.street2 CUSTSTREET2 ,ADDRESS.zipcode CUSTOMERZIP, ADDRESS.city CUSTOMERCITY, ADDRESS.State CUSTOMERSTATE,
ADDRESS.HOUSENUMBER CUSTOMERHOUSENUMBER, ADDRESS.HOUSENUMBEREXT CUSTOMERHOUSENUMBEREXT,
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,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE
-- BTS - 2008-nov-11 TDRE : REMARK is included depending on processsing businessunit
, decode(processbu.code, '150', null, '360', null, '825', null, '925', null, PACKINGNOTE.REMARK) as remark
, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION, PROCESSBU.Code PROCESSBUCODE,
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.phoneno PLANTPHONENO, PLANT.faxno PLANTFAXNO,
PLANT.NAME PLANTNAME,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
 SS.VALUE WEIGHTUNIT, SS1.VALUE PRINTDELNOTEPERCONTAINER, SS2.VALUE CONTAINERRECORDINGACTIVE,
  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(255)) WEEK
,languages.code languagecode, customerlanguage.code customerlanguagecode, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN clm.customer_id = null
      THEN 'N'
      ELSE 'Y'
END)  hasLockeranagement,
clm.chargeservice, clm.chargerent, clm.uselockerobligated, clm.fixednumberbank,
packingnote.numberofgarmentsinlocker, packingnote.numberoflockers,
(select count(*) from PACKINGNOTECONTAINER pnc
   left outer join CONTAINER C on C.CONTAINER_ID = PNC.CONTAINER_ID
   left outer join CONTAINERTYPE CT on CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   left outer join WEIGHINGCATEGORY W on W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 where pnc.packingnote_id = PACKINGNOTE.Packingnote_Id) noOfContainers,
plantdepartment.code plant_dep_code, plantdepartment.description plant_dep_desc,
packingnote.freeofchargereason_id,
(select r.code from reasoncode r
        where r.reasoncode_id = packingnote.freeofchargereason_id) free_reason_code,
(select rd.description from reasoncode_desc rd
        where rd.reasoncode_id = packingnote.freeofchargereason_id
        and rd.language_id = languages.language_id) free_reason_code_desc,
(select count(*) from packingnoteline lines
        where lines.packingnote_id = packingnote.packingnote_id
              and lines.origin in (2,4)) numberOfPossibleLinesWithScans,
PACKINGNOTE.Year year
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, cu.decimals, cu.invoiceamountdecimals, cu.code CurrencyCode
, systemuser.username USER_NAME, systemuser.Fullname USER_FULLNAME
/*, (select rs.containerno from routestop rs where rs.route_id = packingnote.route_id
and rs.stopnumber = packingnote.stopnumber and rs.customer_id = customer.customer_id) routestop_containerno */
, (select st.containerno from stop st where st.stop_id = packingnote.stop_id) routestop_containerno --501928
, dep_pldep.code dep_pldep_code, dep_pldep.description dep_pldep_description
, cust_pldep.code cust_pldep_code, cust_pldep.description cust_pldep_description
, serviceteam.code serviceteam_code, serviceteam.description serviceteam_desc
, (select empl.name from customerbillinginfo cbi, employee empl
  where cbi.customer_id = customer.debtor_id
        and empl.employee_id = cbi.collectionresponsible_id) collectionRespEmployee
, (select MIN(cp.name) from contactperson cp
   where cp.customer_id = customer.customer_id
         and cp.contactpersonnumber = (select min(cpp.contactpersonnumber)
                                    from contactperson cpp where cpp.customer_id = customer.customer_id)) contactpersonname
, PACKINGNOTE.DAYNUMBER, PACKINGNOTE.PROCESSBUSINESSUNIT_ID, PACKINGNOTE.INVOICEBUSINESSUNIT_ID
, CASTVARCHARASNUMBER(SS3.VALUE) MAXCOMPLETENESSDAYS
, SS4.VALUE PRINTDELNOTEZEROLINES
-- below cols added 2008-nov-11 tdre
, pdep.code as productionline -- dk: cl linie
, (select sum(quantity)
   from rentalqtyadjustment rqa
       , productlistperdistribpoint plpd
   where rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
     and rqa.adjustmentdate <= packingnote.deliverydate
     and plpd.distributionpoint_id = packingnote.distributionpoint_id) as inventory
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)
        left outer join plantdepartment cust_pldep on (cust_pldep.plantdepartment_id = customer.plantdepartment_id)
        left outer join serviceteam on (customer.serviceteam_id = serviceteam.serviceteam_id)
        left outer join plantdepartment pdep on (customer.plantdepartment_id = pdep.plantdepartment_id)
        , ADDRESS,
        DEPARTMENT left outer join plantdepartment dep_pldep on dep_pldep.plantdepartment_id = department.plantdepartment_id,
        DISTRIBUTIONPOINT, PLANT, ADDRESS PLANTADDRESS,
        BUSINESSUNIT PROCESSBU, DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1, SYSTEMSETTING SS2, SYSTEMSETTING SS3, SYSTEMSETTING SS4,
        STATUS, COUNTRY C1, COUNTRY C2, plantdepartment, currency cu,
        PACKINGNOTE
          LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
        left outer join route on (packingnote.route_id = route.route_id), systemuser,
        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 STATUS.statustype = 'PN' AND (STATUS.code = 30 OR STATUS.code = 20 or (packingnote.origin = 14 and status.code = 40))
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.address_id = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'MAXCOMPLETENESSDAYS'
  AND SS4.PLANT_ID = PLANT.PLANT_ID
  AND SS4.NAME = 'PRINTDELNOTEZEROLINES'
  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 cu.currency_id = customer.currency_id
  and PACKINGNOTE.SYSTEMUSER_ID = systemuser.systemuser_id

/
create or replace view V_DELIVERYNOTE_BLY
 (NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, DELIVERYDATE, REMARK, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTPHONENO, PRINTDELNOTEZEROLINES, ROUTENUMBER, STOPNUMBER, PACKINGNOTE_ID, DELIVERYLAYOUTCODE, LANGUAGECODE, SCANSONDELIVERYNOTE, NOOFCONTAINERS, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, DELIVERYNOTEREMARKDESC, CONTRACTCODE)
as SELECT PACKINGNOTE.NOTENUMBER,
       CUSTOMER.CUSTOMERNUMBER,
       CUSTOMER.NAME CUSTOMERNAME,
       ADDRESS.STREET CUSTOMERSTREET,
       ADDRESS.ZIPCODE CUSTOMERZIP,
       ADDRESS.CITY CUSTOMERCITY,
       PACKINGNOTE.DELIVERYDATE,
       PACKINGNOTE.REMARK,
       PLANT.CODE PLANTCODE,
       PLANT.NAME PLANTNAME,
       PLANTADDRESS.STREET PLANTSTREET,
       PLANTADDRESS.ZIPCODE PLANTZIPCODE,
       PLANTADDRESS.CITY PLANTCITY,
       PLANT.PHONENO PLANTPHONENO,
       cast(ss.VALUE as varchar2(1)) PRINTDELNOTEZEROLINES,
       ROUTE.ROUTENUMBER,
       PACKINGNOTE.STOPNUMBER,
       PACKINGNOTE.PACKINGNOTE_ID,
       FORMLAYOUT.CODE DELIVERYLAYOUTCODE,
       LANGUAGES.CODE LANGUAGECODE,
       CUSTOMER.SCANSONDELIVERYNOTE,
       coalesce((SELECT min(PNC.PACKINGNOTE_ID)
                  FROM PACKINGNOTECONTAINER PNC
                  LEFT OUTER JOIN CONTAINER C
                    ON C.CONTAINER_ID = PNC.CONTAINER_ID
                  LEFT OUTER JOIN CONTAINERTYPE CT
                    ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
                  LEFT OUTER JOIN WEIGHINGCATEGORY W
                    ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
                 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID),
                0) NOOFCONTAINERS,
       PACKINGNOTE.FREEOFCHARGEREASON_ID,
       (SELECT R.CODE FROM REASONCODE R WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
       (SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
                                                   AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC,
       (select dnrd.description from deliverynoteremark_desc dnrd where dnrd.deliverynoteremark_id = packingnote.deliverynoteremark_id
                                                   and dnrd.language_id = customer.language_id) deliverynoteremarkdesc,
       (SELECT CPC.CODE FROM CONTRACTSPERCUSTOMER CPC
         WHERE CUSTOMER.CUSTOMER_ID = CPC.CUSTOMER_ID
           AND CPC.DATEACTIVE <= PACKINGNOTE.DELIVERYDATE
           AND CPC.DATEINACTIVE > PACKINGNOTE.DELIVERYDATE) CONTRACTCODE
  FROM CUSTOMER
  LEFT OUTER JOIN FORMLAYOUT
    ON CUSTOMER.DELIVERYNOTELAYOUT_ID = FORMLAYOUT.FORMLAYOUT_ID, ADDRESS,
 DEPARTMENT, DISTRIBUTIONPOINT, PLANT, ADDRESS PLANTADDRESS,
 BUSINESSUNIT PROCESSBU, DELIVERYPOINT, SYSTEMSETTING ss, STATUS,
 PLANTDEPARTMENT, PACKINGNOTE
  LEFT OUTER JOIN ROUTE
    ON (PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID)
  LEFT OUTER JOIN STOP
    ON (PACKINGNOTE.STOP_ID = STOP.STOP_ID)
  left outer join deliverysignature dsig
    on (dsig.stop_id = packingnote.stop_id and
       dsig.stop_id = packingnote.deliverysignature_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 STATUS.STATUSTYPE = 'PN'
   AND (STATUS.CODE = 30 OR STATUS.CODE = 20 or
       (packingnote.origin = 14 and status.code = 40))
   AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
   AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
   AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
   AND ss.PLANT_ID = PLANT.PLANT_ID
   AND ss.NAME = 'PRINTDELNOTEZEROLINES'
   AND CUSTOMER.LANGUAGE_ID = CUSTOMERLANGUAGE.LANGUAGE_ID
   AND PACKINGNOTE.PLANTDEPARTMENT_ID = PLANTDEPARTMENT.PLANTDEPARTMENT_ID

/
create or replace view V_DELIVERYNOTE_BNL
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTOMERHOUSENUMBER, CUSTOMERHOUSENUMBEREXT, CUSTCOUNTRY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, NRLINES, NRPNCONT, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE
, REMARK, PROCESSBUDESCRIPTION, PROCESSBUCODE, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTNAME, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, YEAR, PRICESCALCULATED, TOTALAMOUNT, TOTALAMOUNTEXCLUDINGVAT, WEIGHINGTICKET_ID, DECIMALS, INVOICEAMOUNTDECIMALS, CURRENCYCODE, USER_NAME, USER_FULLNAME, ROUTESTOP_CONTAINERNO
, DEP_PLDEP_CODE, DEP_PLDEP_DESCRIPTION, CUST_PLDEP_CODE, CUST_PLDEP_DESCRIPTION, SERVICETEAM_CODE, SERVICETEAM_DESC, COLLECTIONRESPEMPLOYEE, CONTACTPERSONNAME, DAYNUMBER, PROCESSBUSINESSUNIT_ID, INVOICEBUSINESSUNIT_ID, MAXCOMPLETENESSDAYS, SIGNATUREREQUIRED, PERSONIDENTIFICATION, SIGNATURE, SIGNATUREDATE)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(select cn.deliverydate from PACKINGNOTE cn where PACKINGNOTE.CORRECTEDNOTENUMBER = cn.notenumber
  and PACKINGNOTE.CORRECTEDNOTENUMBER<>0) correctiondate,
PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME,
ADDRESS.street CUSTOMERSTREET, ADDRESS.zipcode CUSTOMERZIP, ADDRESS.city CUSTOMERCITY, ADDRESS.State CUSTOMERSTATE,
ADDRESS.HOUSENUMBER CUSTOMERHOUSENUMBER, ADDRESS.HOUSENUMBEREXT CUSTOMERHOUSENUMBEREXT,
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,
(SELECT coalesce(max(pnl.packingnoteline_id),0) FROM PACKINGNOTELINE PNL WHERE PNL.PACKINGNOTE_ID=PACKINGNOTE.PACKINGNOTE_ID) nrlines,
(SELECT coalesce(max(pnc.packingnote_id),0) FROM packingnotecontainer pnc WHERE pnc.PACKINGNOTE_ID=PACKINGNOTE.Packingnote_Id) nrpncont,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION, PROCESSBU.Code PROCESSBUCODE,
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.phoneno PLANTPHONENO, PLANT.faxno PLANTFAXNO,
PLANT.NAME PLANTNAME,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
 SS.VALUE WEIGHTUNIT, SS1.VALUE PRINTDELNOTEPERCONTAINER, SS2.VALUE CONTAINERRECORDINGACTIVE,
  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(255)) WEEK
,languages.code languagecode, customerlanguage.code customerlanguagecode, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN clm.customer_id = null
      THEN 'N'
      ELSE 'Y'
END)  hasLockeranagement,
clm.chargeservice, clm.chargerent, clm.uselockerobligated, clm.fixednumberbank,
packingnote.numberofgarmentsinlocker, packingnote.numberoflockers,
(select count(*) from PACKINGNOTECONTAINER pnc
   left outer join CONTAINER C on C.CONTAINER_ID = PNC.CONTAINER_ID
   left outer join CONTAINERTYPE CT on CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   left outer join WEIGHINGCATEGORY W on W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 where pnc.packingnote_id = PACKINGNOTE.Packingnote_Id) noOfContainers,
plantdepartment.code plant_dep_code, plantdepartment.description plant_dep_desc,
packingnote.freeofchargereason_id,
(select r.code from reasoncode r
        where r.reasoncode_id = packingnote.freeofchargereason_id) free_reason_code,
(select rd.description from reasoncode_desc rd
        where rd.reasoncode_id = packingnote.freeofchargereason_id
        and rd.language_id = languages.language_id) free_reason_code_desc,
(select count(*) from packingnoteline lines
        where lines.packingnote_id = packingnote.packingnote_id
              and lines.origin in (2,4)) numberOfPossibleLinesWithScans,
PACKINGNOTE.Year year
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, cu.decimals, cu.invoiceamountdecimals, cu.code CurrencyCode
, systemuser.username USER_NAME, systemuser.Fullname USER_FULLNAME
/*, (select rs.containerno from routestop rs where rs.route_id = packingnote.route_id
and rs.stopnumber = packingnote.stopnumber and rs.customer_id = customer.customer_id) routestop_containerno */
, coalesce((select rst1.containerno from routestop rst1 where rst1.stopnumber = packingnote.stopnumber and rst1.customer_id = customer.customer_id
         and rst1.route_id = packingnote.route_id and rst1.dateactive in (select max(rst2.dateactive) from routestop rst2
             where rst2.stopnumber = packingnote.stopnumber and rst2.customer_id = CUSTOMER.customer_id and rst2.route_id = packingnote.route_id))
    , (select st.containerno from stop st where st.stop_id = packingnote.stop_id)
  ) routestop_containerno
, dep_pldep.code dep_pldep_code, dep_pldep.description dep_pldep_description
, cust_pldep.code cust_pldep_code, cust_pldep.description cust_pldep_description
, serviceteam.code serviceteam_code, serviceteam.description serviceteam_desc
, (select empl.name from customerbillinginfo cbi, employee empl
  where cbi.customer_id = customer.debtor_id
        and empl.employee_id = cbi.collectionresponsible_id) collectionRespEmployee
, (select MIN(cp.name) from contactperson cp
   where cp.customer_id = customer.customer_id
         and cp.contactpersonnumber = (select min(cpp.contactpersonnumber)
                                    from contactperson cpp where cpp.customer_id = customer.customer_id)) contactpersonname
, PACKINGNOTE.DAYNUMBER, PACKINGNOTE.PROCESSBUSINESSUNIT_ID, PACKINGNOTE.INVOICEBUSINESSUNIT_ID
, CASTVARCHARASNUMBER(SS3.VALUE) MAXCOMPLETENESSDAYS
, CUSTOMER.SIGNATUREREQUIRED
, deliverysignature.personidentification personidentification
, deliverysignature.signature signature
, (select rc.drivingdate from routecontrol rc where rc.routecontrol_id = stop.routecontrol_id) signaturedate
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)
        left outer join plantdepartment cust_pldep on (cust_pldep.plantdepartment_id = customer.plantdepartment_id)
        left outer join serviceteam on (customer.serviceteam_id = serviceteam.serviceteam_id),
        ADDRESS,
        DEPARTMENT left outer join plantdepartment dep_pldep on dep_pldep.plantdepartment_id = department.plantdepartment_id,
        DISTRIBUTIONPOINT, PLANT, ADDRESS PLANTADDRESS,
        BUSINESSUNIT PROCESSBU, DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1, SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, plantdepartment, currency cu,
        PACKINGNOTE
          LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
        left outer join route on (packingnote.route_id = route.route_id)
        LEFT OUTER JOIN STOP ON (PACKINGNOTE.STOP_ID = STOP.STOP_ID)
        left outer join deliverysignature on (deliverysignature.stop_id = packingnote.stop_id and deliverysignature.stop_id=packingnote.deliverysignature_id),
        systemuser,
        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 STATUS.statustype = 'PN' AND (STATUS.code = 30 OR STATUS.code = 20 or (packingnote.origin = 14 and status.code = 40))
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.address_id = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'MAXCOMPLETENESSDAYS'
  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 cu.currency_id = customer.currency_id
  and PACKINGNOTE.Creationsystemuser_Id = systemuser.systemuser_id

/
create or replace view V_DELIVERYNOTE_BUT
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION, PLANTCODE, PLANTNAME
, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, YEAR, PRICESCALCULATED, TOTALAMOUNT, TOTALAMOUNTEXCLUDINGVAT, WEIGHINGTICKET_ID, DECIMALS, INVOICEAMOUNTDECIMALS, CURRENCYCODE, VATNUMBER, REFERENCENUMBER, INTERNALVATNUMBER
, SEARCHNAME, PROCESSBUCODE, PUTUPREPORTPERCUSTOMER, REFERENCENUMBER_DV)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
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,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL, --ORDER 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
SS.VALUE WEIGHTUNIT, SS1.VALUE PRINTDELNOTEPERCONTAINER
, SS2.VALUE CONTAINERRECORDINGACTIVE, SS3.VALUE PRINTDELNOTEZEROLINES
, 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(255)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
	    ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
(SELECT COUNT(*) FROM PACKINGNOTECONTAINER PNC
   LEFT OUTER JOIN CONTAINER C ON C.CONTAINER_ID = PNC.CONTAINER_ID
   LEFT OUTER JOIN CONTAINERTYPE CT ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   LEFT OUTER JOIN WEIGHINGCATEGORY W ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC,
(SELECT COUNT(*) FROM PACKINGNOTELINE LINES
        WHERE LINES.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID
              AND LINES.ORIGIN IN (2,4)) NUMBEROFPOSSIBLELINESWITHSCANS
, PACKINGNOTE.YEAR YEAR
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.REFERENCENUMBER
, INVOICEBU.INTERNALVATNUMBER
, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE
, ROUTE.PUTUPREPORTPERCUSTOMER
, (SELECT MAX(DV.REFERENCE) FROM DELIVERYVARIATIONS DV WHERE DV.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID)	REFERENCENUMBER_DV
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,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        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 STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20 or (packingnote.origin = 14 and status.code = 40))
	AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID

/
create or replace view V_DELIVERYNOTE_CBD
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERSTREET2, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION, PLANTCODE
, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, 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, EMPLOYEEPHONENO, EMPLOYEEMOBILENO, EMPLOYEEFAXNO, EMPLOYEEEMAIL, DEBTOR_NUMBER)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME,
ADDRESS.STREET CUSTOMERSTREET, ADDRESS.STREET2 CUSTOMERSTREET2, 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,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL,
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
lpad(SS.VALUE, 3) WEIGHTUNIT, lpad(SS1.VALUE, 1) PRINTDELNOTEPERCONTAINER
, lpad(SS2.VALUE, 1) CONTAINERRECORDINGACTIVE, lpad(SS3.VALUE, 1) PRINTDELNOTEZEROLINES
, 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(20)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
      ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
coalesce((SELECT min(PNC.PACKINGNOTE_ID) FROM PACKINGNOTECONTAINER PNC
   LEFT OUTER JOIN CONTAINER C ON C.CONTAINER_ID = PNC.CONTAINER_ID
   LEFT OUTER JOIN CONTAINERTYPE CT ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   LEFT OUTER JOIN WEIGHINGCATEGORY W ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID),0) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC
, coalesce((select max(ds.packingnote_id)
                 from   deliveryscan ds
                 where  ds.packingnote_id = packingnote.packingnote_id),
                 (select max(o.packingnote_id)
                   from   outofcirculationhistory o
                   where  o.packingnote_id = packingnote.packingnote_id), 0) numberofpossiblelineswithscans
, PACKINGNOTE.YEAR YEAR
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.REFERENCENUMBER
, INVOICEBU.INTERNALVATNUMBER
, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE
, ROUTE.PUTUPREPORTPERCUSTOMER
, customer.signaturerequired
, dsig.personidentification personidentification
, dsig.signature signature
, (select rc.drivingdate from routecontrol rc where rc.routecontrol_id = stop.routecontrol_id) signaturedate
, to_char(stop.departuretime,'fmhhfm:MI:AM') signaturetime
, to_char(stop.departuretime,'fmhh24fm:MI') signaturetime24
, packingnote.distributionpoint_id
, packingnote.processbusinessunit_id
, EMPLOYEE.PHONENO EMPLOYEEPHONENO, EMPLOYEE.MOBILENO EMPLOYEEMOBILENO, EMPLOYEE.FAXNO EMPLOYEEFAXNO, EMPLOYEE.EMAIL EMPLOYEEEMAIL
, (select deb.customernumber from customer deb where deb.customer_id = customer.debtor_id) debtor_number
FROM  CUSTOMER
        LEFT OUTER JOIN EMPLOYEE ON (CUSTOMER.SERVICEEMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
        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,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        PACKINGNOTE
          LEFT OUTER JOIN ROUTE ON (PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID)
          LEFT OUTER JOIN STOP ON (PACKINGNOTE.STOP_ID = STOP.STOP_ID)
          left outer join deliverysignature dsig on dsig.stop_id = packingnote.stop_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 STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20)
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID

/
create or replace view V_DELIVERYNOTE_CIW
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERSTREET2, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, COUNTY, CUSTCOUNTRY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION
, PLANTCOMPANYPHONE, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, 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)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME,
ADDRESS.STREET CUSTOMERSTREET,ADDRESS.STREET2 CUSTOMERSTREET2, ADDRESS.ZIPCODE CUSTOMERZIP, ADDRESS.CITY CUSTOMERCITY, ADDRESS.STATE CUSTOMERSTATE,
ADDRESS.COUNTY,
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,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
(select pc.phone from plantcompany pc where pc.code = (select min(pc.code) from plantcompany pc where pc.plant_id = plant.plant_id) and pc.plant_id = plant.plant_id) plantcompanyphone,
PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL, --ORDER 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANTADDRESS.COUNTY PLANTCOUNTY, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
SS.VALUE WEIGHTUNIT, SS1.VALUE PRINTDELNOTEPERCONTAINER
, SS2.VALUE CONTAINERRECORDINGACTIVE, SS3.VALUE PRINTDELNOTEZEROLINES
, 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(255)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
      ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
(SELECT COUNT(*) FROM PACKINGNOTECONTAINER PNC
   LEFT OUTER JOIN CONTAINER C ON C.CONTAINER_ID = PNC.CONTAINER_ID
   LEFT OUTER JOIN CONTAINERTYPE CT ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   LEFT OUTER JOIN WEIGHINGCATEGORY W ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC,
(SELECT COUNT(*) FROM PACKINGNOTELINE LINES
        WHERE LINES.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID
              AND LINES.ORIGIN IN (2,4)) NUMBEROFPOSSIBLELINESWITHSCANS
, PACKINGNOTE.YEAR YEAR
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.REFERENCENUMBER
--, 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
, INVOICEBU.INTERNALVATNUMBER
, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE
, ROUTE.PUTUPREPORTPERCUSTOMER
, customer.signaturerequired
, dsig.personidentification personidentification
, dsig.signature signature
, (select rc.drivingdate from routecontrol rc where rc.routecontrol_id = stop.routecontrol_id) signaturedate
, to_char(stop.departuretime,'fmhhfm:MI:AM') signaturetime
, to_char(stop.departuretime,'fmhh24fm:MI') signaturetime24
, packingnote.distributionpoint_id
, packingnote.processbusinessunit_id
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,
--       LEFT OUTER JOIN CUSTOMERBILLINGINFO CBI
--             LEFT OUTER JOIN BANKINSTITUTION LBANK
--             ON CBI.LAUNDRYBANKINSTITUTION_ID = LBANK.BANKINSTITUTION_ID
--        ON CUSTOMER.DEBTOR_ID = CBI.CUSTOMER_ID,
        ADDRESS, DEPARTMENT, DISTRIBUTIONPOINT, PLANT, ADDRESS PLANTADDRESS,
        BUSINESSUNIT PROCESSBU,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        PACKINGNOTE
          LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
          LEFT OUTER JOIN ROUTE ON (PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID)
          LEFT OUTER JOIN STOP ON (PACKINGNOTE.STOP_ID = STOP.STOP_ID)
          left outer join deliverysignature dsig on (dsig.stop_id = packingnote.stop_id and dsig.stop_id=packingnote.deliverysignature_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 STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20 or (packingnote.origin = 14 and status.code = 40))
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID

/
create or replace view V_DELIVERYNOTE_ECL
 (CORRECTEDNOTENUMBER, SPECIALSTREET, SPECIALZIPCODE, SPECIALCITY, SPECIALSTREET2, SPECIACUSTOMERNAME, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERSTREET2, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, CUSTOMERCOUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION
, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, 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, WOREFNUMBER, DELIVERYNOTEREMARKDESC)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER, (select max(ih.street) from invoiceheader ih
join packingnoteline pnl on pnl.invoiceheader_id = ih.invoiceheader_id
where pnl.packingnote_id=packingnote.packingnote_id) specialstreet,
(select max(ih.zipcode) from invoiceheader ih
join packingnoteline pnl on pnl.invoiceheader_id = ih.invoiceheader_id
where pnl.packingnote_id=packingnote.packingnote_id) specialzipcode,
(select max(ih.city) from invoiceheader ih
join packingnoteline pnl on pnl.invoiceheader_id = ih.invoiceheader_id
where pnl.packingnote_id=packingnote.packingnote_id) specialcity,
(select max(ih.street2) from invoiceheader ih
join packingnoteline pnl on pnl.invoiceheader_id = ih.invoiceheader_id
where pnl.packingnote_id=packingnote.packingnote_id) specialstreet2,
(select max(ih.deltocustomername) from invoiceheader ih
join packingnoteline pnl on pnl.invoiceheader_id = ih.invoiceheader_id
where pnl.packingnote_id=packingnote.packingnote_id) speciacustomername,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME,
ADDRESS.STREET CUSTOMERSTREET, ADDRESS.STREET2 CUSTOMERSTREET2,  ADDRESS.ZIPCODE CUSTOMERZIP, ADDRESS.CITY CUSTOMERCITY, ADDRESS.STATE CUSTOMERSTATE,
C1.CODE CUSTCOUNTRY, C1.DESCRIPTION CUSTCOUNTRY_DESC, ADDRESS.COUNTY CUSTOMERCOUNTY,
DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
PACKINGNOTE.SEQUENCENUMBER,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, --CAST(
PACKINGNOTE.REMARK --AS VARCHAR2(60) ) REMARK
, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL, --ORDER 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
cast (SS.VALUE as varchar2(60)) WEIGHTUNIT,
cast (SS1.VALUE as varchar2(1)) PRINTDELNOTEPERCONTAINER,
cast (SS2.VALUE as varchar2(1)) CONTAINERRECORDINGACTIVE,
cast (SS3.VALUE as varchar2(1)) PRINTDELNOTEZEROLINES,
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(60)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
      ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
coalesce((SELECT min(PNC.PACKINGNOTE_ID) FROM PACKINGNOTECONTAINER PNC
   LEFT OUTER JOIN CONTAINER C ON C.CONTAINER_ID = PNC.CONTAINER_ID
   LEFT OUTER JOIN CONTAINERTYPE CT ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   LEFT OUTER JOIN WEIGHINGCATEGORY W ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID),0) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC
, coalesce((select max(ds.packingnote_id)
                 from   deliveryscan ds
                 where  ds.packingnote_id = packingnote.packingnote_id),
                 (select max(o.packingnote_id)
                   from   outofcirculationhistory o
                   where  o.packingnote_id = packingnote.packingnote_id), 0) numberofpossiblelineswithscans
, PACKINGNOTE.YEAR YEAR
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.REFERENCENUMBER
, INVOICEBU.INTERNALVATNUMBER
, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE
, ROUTE.PUTUPREPORTPERCUSTOMER
, customer.signaturerequired
, dsig.personidentification personidentification
, dsig.signature signature
, (select rc.drivingdate from routecontrol rc where rc.routecontrol_id = stop.routecontrol_id) signaturedate
, to_char(stop.departuretime,'fmhhfm:MI:AM') signaturetime
, to_char(stop.departuretime,'fmhh24fm:MI') signaturetime24
, packingnote.distributionpoint_id
, packingnote.processbusinessunit_id
, DELIVERYPOINT. SIGNATUREBARCODE
, cast ((SELECT SS.VALUE FROM SYSTEMSETTING SS WHERE SS.PLANT_ID=PLANT.PLANT_ID AND SS.NAME ='CONTAINERTYPEUNQBRCLABEL')  as varchar2(60)) containertypedescription
, (select max(wo.referencenumber) from deliveryscan ds, issuehistory ih, workorder wo
where ds.uniqueitem_link_id = ih.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 ih.workorder_id = wo.workorder_id
and ds.packingnote_id = packingnote.packingnote_id
and wo.deliverfrom=2
) worefnumber,
(select dnrd.description from deliverynoteremark_desc dnrd where dnrd.deliverynoteremark_id = packingnote.deliverynoteremark_id
        and dnrd.language_id = customer.language_id) deliverynoteremarkdesc
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,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        PACKINGNOTE
          LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
          LEFT OUTER JOIN ROUTE ON (PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID)
          LEFT OUTER JOIN STOP ON (PACKINGNOTE.STOP_ID = STOP.STOP_ID)
          left outer join deliverysignature dsig on (dsig.stop_id = packingnote.stop_id and dsig.stop_id=packingnote.deliverysignature_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 STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20 or (packingnote.origin = 14 and status.code = 40))
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID

/
create or replace view V_DELIVERYNOTE_EDW
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION, PLANTCODE, PLANTNAME
, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, YEAR, PRICESCALCULATED, TOTALAMOUNT, TOTALAMOUNTEXCLUDINGVAT, WEIGHINGTICKET_ID, DECIMALS, INVOICEAMOUNTDECIMALS, CURRENCYCODE, VATNUMBER, REFERENCENUMBER, INTERNALVATNUMBER
, SEARCHNAME, PROCESSBUCODE, SERVEMPL)
as SELECT PACKINGNOTE.CORRECTEDNOTENUMBER,
(select cn.deliverydate from PACKINGNOTE cn where PACKINGNOTE.CORRECTEDNOTENUMBER = cn.notenumber
  and PACKINGNOTE.CORRECTEDNOTENUMBER<>0) correctiondate,
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,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.Name PLANTName, PLANT.WEBSITE PLANTWEBSITE, PLANT.Email PLANTEmail, --order 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.phoneno PLANTPHONENO, PLANT.faxno PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
SS.VALUE WEIGHTUNIT, SS1.VALUE PRINTDELNOTEPERCONTAINER
, SS2.VALUE CONTAINERRECORDINGACTIVE, SS3.VALUE PRINTDELNOTEZEROLINES
, 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(255)) WEEK
,languages.code languagecode, customerlanguage.code customerlanguagecode, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN clm.customer_id = null
      THEN 'N'
      ELSE 'Y'
END)  hasLockeranagement,
clm.chargeservice, clm.chargerent, clm.uselockerobligated, clm.fixednumberbank,
packingnote.numberofgarmentsinlocker, packingnote.numberoflockers,
(select count(*) from PACKINGNOTECONTAINER pnc
   left outer join CONTAINER C on C.CONTAINER_ID = PNC.CONTAINER_ID
   left outer join CONTAINERTYPE CT on CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   left outer join WEIGHINGCATEGORY W on W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 where pnc.packingnote_id = PACKINGNOTE.Packingnote_Id) noOfContainers,
plantdepartment.code plant_dep_code, plantdepartment.description plant_dep_desc,
packingnote.freeofchargereason_id,
(select r.code from reasoncode r
        where r.reasoncode_id = packingnote.freeofchargereason_id) free_reason_code,
(select rd.description from reasoncode_desc rd
        where rd.reasoncode_id = packingnote.freeofchargereason_id
        and rd.language_id = languages.language_id) free_reason_code_desc,
(select count(*) from packingnoteline lines
        where lines.packingnote_id = packingnote.packingnote_id
              and lines.origin in (2,4)) numberOfPossibleLinesWithScans
, PACKINGNOTE.Year year
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, cu.decimals, cu.invoiceamountdecimals, cu.code CurrencyCode,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.Referencenumber
--, 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
, INVOICEBU.Internalvatnumber
, CUSTOMER.Searchname, PROCESSBU.Code PROCESSBUCODE
, ( select se.name
    from employee se
    where se.employee_id = customer.serviceemployee_id) SERVEMPL
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,
--       left outer join customerbillinginfo cbi
--             LEFT OUTER JOIN bankinstitution Lbank
--             ON cbi.laundrybankinstitution_id = Lbank.bankinstitution_id
--        on CUSTOMER.Debtor_Id = cbi.customer_id,
        ADDRESS, DEPARTMENT, DISTRIBUTIONPOINT, PLANT, ADDRESS PLANTADDRESS,
        BUSINESSUNIT PROCESSBU,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, plantdepartment, currency cu,
        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 STATUS.statustype = 'PN' AND (STATUS.code = 30 OR STATUS.code = 20 or (packingnote.origin = 14 and status.code = 40))
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.address_id = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 cu.currency_id = customer.currency_id
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID

/
create or replace view V_DELIVERYNOTE_ELI
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERSTREET2, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, CUSTOMERCOUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION
, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, YEAR, PRICESCALCULATED, TOTALAMOUNT, TOTALAMOUNTEXCLUDINGVAT, WEIGHINGTICKET_ID, DECIMALS, INVOICEAMOUNTDECIMALS, CURRENCYCODE, VATNUMBER, REFERENCENUMBER
, INTERNALVATNUMBER, SEARCHNAME, PROCESSBUCODE, PUTUPREPORTPERCUSTOMER, PACKINGDEADLINE, SIGNATUREREQUIRED, PERSONIDENTIFICATION, SIGNATURE, SIGNATUREDATE, SIGNATURETIME, SIGNATURETIME24, DISTRIBUTIONPOINT_ID, PROCESSBUSINESSUNIT_ID, SIGNATUREBARCODE, CONTAINERTYPEDESCRIPTION, WOREFNUMBER, DELIVERYNOTEREMARKDESC, EMPLOYEENAME1, EMPLOYEENUMBER1, EMPLOYESEARCHNAME1, EMPLOYEEPHONE1, EMPLOYEENAME2, EMPLOYEENUMBER2, EMPLOYESEARCHNAME2, EMPLOYEEPHONE2, BILLTO_NR
, VCDE, SALES_REMARK, SALES_EXTERNALREMARK, WORKORDERNUMBER, SALES_REFERENCENUMBER, EMPLOYEENAME3, EMPLOYEENUMBER3, EMPLOYESEARCHNAME3, EMPLOYEEPHONE3, EMPLOYEENAME4, EMPLOYEENUMBER4, EMPLOYESEARCHNAME4, EMPLOYEEPHONE4, CONTRACT_PONUMBERS, SALES_PONUMBERS)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME,
ADDRESS.STREET CUSTOMERSTREET, ADDRESS.STREET2 CUSTOMERSTREET2,  ADDRESS.ZIPCODE CUSTOMERZIP, ADDRESS.CITY CUSTOMERCITY, ADDRESS.STATE CUSTOMERSTATE,
C1.CODE CUSTCOUNTRY, C1.DESCRIPTION CUSTCOUNTRY_DESC, ADDRESS.COUNTY CUSTOMERCOUNTY,
DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
PACKINGNOTE.SEQUENCENUMBER,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, --CAST(
PACKINGNOTE.REMARK --AS VARCHAR2(60) ) REMARK
, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL, --ORDER 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
cast (SS.VALUE as varchar2(60)) WEIGHTUNIT,
cast (SS1.VALUE as varchar2(1)) PRINTDELNOTEPERCONTAINER,
cast (SS2.VALUE as varchar2(1)) CONTAINERRECORDINGACTIVE,
cast (SS3.VALUE as varchar2(1)) PRINTDELNOTEZEROLINES,
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(60)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
      ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
coalesce((SELECT min(PNC.PACKINGNOTE_ID) FROM PACKINGNOTECONTAINER PNC
   LEFT OUTER JOIN CONTAINER C ON C.CONTAINER_ID = PNC.CONTAINER_ID
   LEFT OUTER JOIN CONTAINERTYPE CT ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   LEFT OUTER JOIN WEIGHINGCATEGORY W ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID),0) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC
, coalesce((select max(ds.packingnote_id)
                 from   deliveryscan ds
                 where  ds.packingnote_id = packingnote.packingnote_id),
                 (select max(o.packingnote_id)
                   from   outofcirculationhistory o
                   where  o.packingnote_id = packingnote.packingnote_id), 0) numberofpossiblelineswithscans
, PACKINGNOTE.YEAR YEAR
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.REFERENCENUMBER
, INVOICEBU.INTERNALVATNUMBER
, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE
, ROUTE.PUTUPREPORTPERCUSTOMER, ROUTE.PACKINGDEADLINE
, customer.signaturerequired
, dsig.personidentification personidentification
, dsig.signature signature
, (select rc.drivingdate from routecontrol rc where rc.routecontrol_id = stop.routecontrol_id) signaturedate
, to_char(stop.departuretime,'fmhhfm:MI:AM') signaturetime
, to_char(stop.departuretime,'fmhh24fm:MI') signaturetime24
, packingnote.distributionpoint_id
, packingnote.processbusinessunit_id
, DELIVERYPOINT. SIGNATUREBARCODE
, cast ((SELECT SS.VALUE FROM SYSTEMSETTING SS WHERE SS.PLANT_ID=PLANT.PLANT_ID AND SS.NAME ='CONTAINERTYPEUNQBRCLABEL')  as varchar2(60)) containertypedescription
, (select max(wo.referencenumber) from deliveryscan ds, issuehistory ih, workorder wo
where ds.uniqueitem_link_id = ih.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 ih.workorder_id = wo.workorder_id
and ds.packingnote_id = packingnote.packingnote_id
and wo.deliverfrom = 2
) worefnumber,
(select dnrd.description from deliverynoteremark_desc dnrd where dnrd.deliverynoteremark_id = packingnote.deliverynoteremark_id
        and dnrd.language_id = customer.language_id) deliverynoteremarkdesc
, EMPLOYEE1.NAME EMPLOYEENAME1, EMPLOYEE1.EMPLOYEENUMBER EMPLOYEENUMBER1, EMPLOYEE1.Searchname EMPLOYESearchname1, EMPLOYEE1.Phoneno EMPLOYEEPhone1
, EMPLOYEE2.NAME EMPLOYEENAME2, EMPLOYEE2.EMPLOYEENUMBER EMPLOYEENUMBER2, EMPLOYEE2.Searchname EMPLOYESearchname2, EMPLOYEE2.Phoneno EMPLOYEEPhone2
, (select deb.customernumber from customer deb where deb.customer_id = CUSTOMER.Debtor_Id) BillTo_NR
, (select cc.ponumber from costcenter cc where cc.costcenter_id = DISTRIBUTIONPOINT.Costcenter_Id )  VCDE
, sn.remark sales_remark, sn.externalremark sales_externalremark, sn.workordernumber, sn.referencenumber sales_referencenumber
, EMPLOYEE3.NAME EMPLOYEENAME3, EMPLOYEE3.EMPLOYEENUMBER EMPLOYEENUMBER3, EMPLOYEE3.Searchname EMPLOYESearchname3, EMPLOYEE3.Phoneno EMPLOYEEPhone3
, EMPLOYEE4.NAME EMPLOYEENAME4, EMPLOYEE4.EMPLOYEENUMBER EMPLOYEENUMBER4, EMPLOYEE4.Searchname EMPLOYESearchname4, EMPLOYEE4.Phoneno EMPLOYEEPhone4
, (select LISTAGG(contractspercustomer.purchaseorder, ', ') within group (order by contractspercustomer.purchaseorder)
 from contractspercustomer Where contractspercustomer.customer_id = CUSTOMER.Customer_Id) Contract_POnumbers
, (select LISTAGG(poh.purchaseordernumber, ', ') within group (order by poh.purchaseordernumber)
 from workorderline wkli, purchaseorderline pol, purchaseorderheader poh Where wkli.workorder_id = sn.workorder_id and pol.purchaseorderline_id = wkli.purchaseorderline_id
      and poh.purchaseorderheader_id = pol.purchaseorderheader_id) Sales_POnumbers
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
        LEFT OUTER JOIN EMPLOYEE EMPLOYEE1 ON (EMPLOYEE1.EMPLOYEE_ID = CUSTOMER.Salesemployee1_Id)
        LEFT OUTER JOIN EMPLOYEE EMPLOYEE2 ON (EMPLOYEE2.EMPLOYEE_ID = CUSTOMER.Serviceemployee_Id),
        ADDRESS, DEPARTMENT, DISTRIBUTIONPOINT, PLANT, ADDRESS PLANTADDRESS,
        BUSINESSUNIT PROCESSBU,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        PACKINGNOTE--          LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
          LEFT OUTER JOIN ROUTE ON (PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID)
          LEFT OUTER JOIN STOP ON (PACKINGNOTE.STOP_ID = STOP.STOP_ID)
          left outer join deliverysignature dsig on (dsig.stop_id = packingnote.stop_id and dsig.stop_id=packingnote.deliverysignature_id)
          LEFT OUTER JOIN WORKORDER sn
              LEFT OUTER JOIN EMPLOYEE EMPLOYEE3 ON (EMPLOYEE3.EMPLOYEE_ID = sn.salesemployee1_id)
              LEFT OUTER JOIN EMPLOYEE EMPLOYEE4 ON (EMPLOYEE3.EMPLOYEE_ID = sn.salesemployee2_id)
          ON (PACKINGNOTE.Salesnote_Id = sn.workorder_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 STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20 or (packingnote.origin = 14 and status.code = 40))
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID

/
create or replace view V_DELIVERYNOTE_FLAGGED_ELI
 (PLANNEDOUTDATE, LANGUAGE_CODE, PRIMARYID, FLAG_CODE, PRODUCT_CODE, PRODUCT_DESC, FLAG_DESC, COLOR, WEARERNAME, DISTRIBUTIONPOINT_ID, PREVSTAY_ID)
as select ur.plannedoutdate, lan.code language_Code, u.primaryid, f.code flag_code, p.code product_code,
(select prd.description from product_desc prd where prd.product_id = p.parentproduct_id and prd.language_id = lan.language_id) product_desc,
(select fd.description from flag_desc fd where fd.flag_id = f.flag_id and fd.language_id = lan.language_id) flag_desc,
(select cod.description from color_desc cod where cod.color_id = p.color_id and cod.language_id = lan.language_id) color,
(select w.fullname from uniqueitemnonpool uinp, weareremployment we, wearer w where uinp.uniqueitem_id = ui.uniqueitem_id
                   and we.weareremployment_id = uinp.weareremployment_id and w.wearer_id = we.wearer_id) wearername,
nvl(u.distributionpoint_id,
    (select we.distributionpoint_id from uniqueitemnonpool uinp, weareremployment we where uinp.uniqueitem_id = ui.uniqueitem_id
     and we.weareremployment_id = uinp.weareremployment_id)) distributionpoint_id,
u.prevstay_id
from product p, uniqueitem u, uniqueitemflag ui, uniqueitemroute ur, flag f, languages lan
where p.product_id = u.product_id and u.uniqueitem_id = ui.uniqueitem_id
      and ur.uniqueitem_id = u.uniqueitem_id
      and ui.flag_id = f.flag_id and f.code in ('1', '2', '4', '5', '8', '9')

/
create or replace view V_DELIVERYNOTE_HOW
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION, PLANTCODE, PLANTNAME
, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, YEAR, PRICESCALCULATED, TOTALAMOUNT, TOTALAMOUNTEXCLUDINGVAT, WEIGHINGTICKET_ID, DECIMALS, INVOICEAMOUNTDECIMALS, CURRENCYCODE, VATNUMBER, REFERENCENUMBER, INTERNALVATNUMBER
, SEARCHNAME, PROCESSBUCODE, PUTUPREPORTPERCUSTOMER, SIGNATURE, PERSONIDENTIFICATION, REASONCODE, REASONCODEDESC, DRIVERNUMBER, PNSTATUS)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
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,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL, --ORDER 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
SS.VALUE WEIGHTUNIT, SS1.VALUE PRINTDELNOTEPERCONTAINER
, SS2.VALUE CONTAINERRECORDINGACTIVE, SS3.VALUE PRINTDELNOTEZEROLINES
, 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(255)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
      ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
(SELECT COUNT(*) FROM PACKINGNOTECONTAINER PNC
   LEFT OUTER JOIN CONTAINER C ON C.CONTAINER_ID = PNC.CONTAINER_ID
   LEFT OUTER JOIN CONTAINERTYPE CT ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   LEFT OUTER JOIN WEIGHINGCATEGORY W ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC,
(SELECT COUNT(*) FROM PACKINGNOTELINE LINES
        WHERE LINES.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID
              AND LINES.ORIGIN IN (2,4)) NUMBEROFPOSSIBLELINESWITHSCANS
, PACKINGNOTE.YEAR YEAR
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.REFERENCENUMBER
--, 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
, INVOICEBU.INTERNALVATNUMBER
, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE
, ROUTE.PUTUPREPORTPERCUSTOMER,
DS.SIGNATURE,DS.PERSONIDENTIFICATION,
RC.Code REASONCODE, RCD.DESCRIPTION REASONCODEDESC
--,EMP.NAME DRIVERNAME
, rctl.drivernumber
, status.code PNStatus
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,
--       LEFT OUTER JOIN CUSTOMERBILLINGINFO CBI
--             LEFT OUTER JOIN BANKINSTITUTION LBANK
--             ON CBI.LAUNDRYBANKINSTITUTION_ID = LBANK.BANKINSTITUTION_ID
--        ON CUSTOMER.DEBTOR_ID = CBI.CUSTOMER_ID,
        ADDRESS, DEPARTMENT, DISTRIBUTIONPOINT, PLANT, ADDRESS PLANTADDRESS,
        BUSINESSUNIT PROCESSBU,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        PACKINGNOTE
          LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
        LEFT OUTER JOIN ROUTE ON (PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID)
        LEFT OUTER JOIN DELIVERYSIGNATURE DS ON (PACKINGNOTE.STOP_ID=DS.STOP_ID )
        LEFT OUTER JOIN STOP on packingnote.stop_id= stop.stop_id
        LEFT OUTER JOIN REASONCODE rc on rc.reasoncode_id=stop.reasoncode_id
        LEFT OUTER JOIN REASONCODE_DESC rcd on rcd.reasoncode_id=rc.reasoncode_id
        LEFT OUTER JOIN ROUTECONTROL rctl on rctl.routecontrol_id=STOP.ROUTECONTROL_ID
        --LEFT OUTER JOIN EMPLOYEE emp on emp.employeenumber=rctl.drivernumber
        ,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 STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20 or (packingnote.origin = 14 and status.code = 40))
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID

/
create or replace view V_DELIVERYNOTE_HRB
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, EMPLOYEEREMARK, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION, INTOCMIT
, CNP, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, YEAR, PRICESCALCULATED, TOTALAMOUNT, TOTALAMOUNTEXCLUDINGVAT, WEIGHINGTICKET_ID, DECIMALS, INVOICEAMOUNTDECIMALS, CURRENCYCODE, VATNUMBER, REFERENCENUMBER
, INTERNALVATNUMBER, REGCOM, CUI, EXTRANAME1, ADDRESSLINE1, SEARCHNAME, PROCESSBUCODE, COUNTY, BANKINSTITUTION, IBAN, PUTUPREPORTPERCUSTOMER, INVOICEBUCODE, INVOICEBUDESC, DIVISIONDESC, REGIONDESC, DRIVERNAME, IDSERIES, IDNUMBER, IDISSUER, LICENSEPLATENUMBER, PONUMBER)
as select
packingnote.correctednotenumber,
(select cn.deliverydate from packingnote cn where packingnote.correctednotenumber = cn.notenumber
  and packingnote.correctednotenumber<>0) correctiondate,
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,
(select description from transportarticle_desc  a
        where a.transportarticle_id = packingnote.transportarticle_id
              and a.language_id = languages.language_id ) transportarticledescription,
packingnote.occupancy, employee.name employeename, employee.remark employeeremark, packingnote.deliverydate DELIVERYDATE,
packingnote.originaldeliverydate, packingnote.remark, processbu.description processbudescription
,(select SYSTEMUSER.FULLNAME from SYSTEMUSER where SYSTEMUSER.SYSTEMUSER_ID = PACKINGNOTE.CREATIONSYSTEMUSER_ID ) Intocmit
,(select substr(EMPLOYEE.REMARK, 1, 13)
  from EMPLOYEE, SYSTEMUSER
 where EMPLOYEE.Employee_Id = SYSTEMUSER.Employee_Id
   and SYSTEMUSER.SYSTEMUSER_ID = PACKINGNOTE.CREATIONSYSTEMUSER_ID) CNP
,plant.code plantcode, plant.name plantname, plant.website plantwebsite, plant.email plantemail, --order 501604
plantaddress.street plantstreet, plantaddress.zipcode plantzipcode,
plantaddress.city plantcity, plantaddress.state plantstate, plant.phoneno plantphoneno, plant.faxno plantfaxno,
c2.code plantcountry_code, c2.description plantcountry_desc,
ss.value weightunit, ss1.value printdelnotepercontainer
, ss2.value containerrecordingactive, ss3.value printdelnotezerolines
, 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(255)) week
,languages.code languagecode, customerlanguage.code customerlanguagecode, packingnote.productiondate productiondate,
customer.scansondeliverynote,
(case when clm.customer_id = null
      then 'N'
      else 'Y'
end)  haslockeranagement,
clm.chargeservice, clm.chargerent, clm.uselockerobligated, clm.fixednumberbank,
packingnote.numberofgarmentsinlocker, packingnote.numberoflockers,
(select count(1) from packingnotecontainer pnc
   left outer join container c on c.container_id = pnc.container_id
   left outer join containertype ct on ct.containertype_id = pnc.containertype_id
   left outer join weighingcategory w on w.weighingcategory_id = pnc.weighingcategory_id
 where pnc.packingnote_id = packingnote.packingnote_id) noofcontainers,
plantdepartment.code plant_dep_code, plantdepartment.description plant_dep_desc,
packingnote.freeofchargereason_id,
(select r.code from reasoncode r
        where r.reasoncode_id = packingnote.freeofchargereason_id) free_reason_code,
(select rd.description from reasoncode_desc rd
        where rd.reasoncode_id = packingnote.freeofchargereason_id
        and rd.language_id = languages.language_id) free_reason_code_desc,
(select count(1) from packingnoteline lines
        where lines.packingnote_id = packingnote.packingnote_id
              and lines.origin in (2,4)) numberofpossiblelineswithscans
, packingnote.year year
, packingnote.pricescalculated, packingnote.totalamount, packingnote.totalamountexcludingvat
, packingnote.weighingticket_id, cu.decimals, cu.invoiceamountdecimals, cu.code currencycode,
invoicebu.vatnumber vatnumber
, packingnote.referencenumber
, invoicebu.internalvatnumber
, CUSTOMER.Cocnumber REGCOM
, CUSTOMER.Vatnumber CUI
, CUSTOMER.EXTRANAME1 ExtraName1
, (select ads.street from ADDRESS ads where ads.address_id = CUSTOMER.Invoiceaddress_Id) AddressLine1
/*, (select con.purchaseorder from contractspercustomer con where con.customer_id = CUSTOMER.CUSTOMER_ID) POnumber*/
, customer.searchname, processbu.code processbucode
, /*(select SALESAREA_DESC.DESCRIPTION from SALESAREA_DESC, SALESAREA WHERE SALESAREA_DESC.SALESAREA_ID = SALESAREA.SALESAREA_ID and SALESAREA.SALESAREA_ID = CUSTOMER.SALESAREA_ID and LANGUAGES.LANGUAGE_ID = SALESAREA_DESC.LANGUAGE_ID)*/
 (select bill_adr.city from address bill_adr where bill_adr.address_id = customer.invoiceaddress_id) County
, (select BANKINSTITUTION.DESCRIPTION from CUSTOMERBILLINGINFO, BANKINSTITUTION where CUSTOMERBILLINGINFO.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID AND BANKINSTITUTION.BANKINSTITUTION_ID = CUSTOMERBILLINGINFO.Bankinstitution_Id ) BankInstitution
, (select CUSTOMERBILLINGINFO.IBANNO from CUSTOMERBILLINGINFO where CUSTOMERBILLINGINFO.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID) IBAN
, route.putupreportpercustomer, invoicebu.code invoicebucode, invoicebu.description invoicebudesc
, (select dd.description from division_desc dd where invoicebu.division_id = dd.division_id and dd.language_id = languages.language_id) divisiondesc
, (select rd.description from region_desc rd where invoicebu.region_id = rd.region_id and rd.language_id = languages.language_id) regiondesc
, (select e.name from routecontrol rc, employee e where packingnote.routecontrol_id = rc.routecontrol_id and rc.drivernumber = e.employeenumber and e.plant_id = rc.plant_id) drivername
, (select substr(e.REMARK, 14, 2)from employee e, routecontrol rc where packingnote.routecontrol_id = rc.routecontrol_id and rc.drivernumber = e.employeenumber and e.plant_id = rc.plant_id) IDseries
, (select substr(e.REMARK, 16, 6)from employee e, routecontrol rc where packingnote.routecontrol_id = rc.routecontrol_id and rc.drivernumber = e.employeenumber and e.plant_id = rc.plant_id) IDnumber
, (select substr(e.REMARK, 22)from employee e, routecontrol rc where packingnote.routecontrol_id = rc.routecontrol_id and rc.drivernumber = e.employeenumber and e.plant_id = rc.plant_id) IDissuer
, (select t.description from truck t where route.truck_id = t.truck_id) LicensePlateNumber
, (select LISTAGG(contractspercustomer.purchaseorder, ', ') within group (order by contractspercustomer.purchaseorder)
 from contractspercustomer Where contractspercustomer.customer_id = CUSTOMER.Customer_Id)POnumber
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,
        businessunit invoicebu,
        deliverypoint, systemsetting ss, systemsetting ss1,
        systemsetting ss2, systemsetting ss3,
        status, country c1, country c2, plantdepartment, currency cu,
        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 status.statustype = 'PN' and (status.code = 30 or status.code = 20 or (packingnote.origin = 14 and status.code = 40))
  and packingnote.processbusinessunit_id = processbu.businessunit_id
  and processbu.plant_id = plant.plant_id
  and plant.address_id = plantaddress.address_id
  and ss.plant_id = plant.plant_id
  and ss.name = 'WEIGHTUNIT'
  and ss1.plant_id = plant.plant_id
  and ss1.name = 'PRINTDELNOTEPERCONTAINER'
  and ss2.plant_id = plant.plant_id
  and ss2.name = 'CONTAINERRECORDINGACTIVE'
  and ss3.plant_id = plant.plant_id
  and ss3.name = 'PRINTDELNOTEZEROLINES'
  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 cu.currency_id = customer.currency_id
  and packingnote.invoicebusinessunit_id = invoicebu.businessunit_id

/
create or replace view V_DELIVERYNOTE_JWR
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION, PLANTCODE, PLANTNAME
, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, YEAR, PRICESCALCULATED, TOTALAMOUNT, TOTALAMOUNTEXCLUDINGVAT, WEIGHINGTICKET_ID, DECIMALS, INVOICEAMOUNTDECIMALS, CURRENCYCODE, VATNUMBER, REFERENCENUMBER, INTERNALVATNUMBER
, SEARCHNAME, PROCESSBUCODE)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(select cn.deliverydate from PACKINGNOTE cn where PACKINGNOTE.CORRECTEDNOTENUMBER = cn.notenumber
  and PACKINGNOTE.CORRECTEDNOTENUMBER<>0) correctiondate,
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,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.Name PLANTName, PLANT.WEBSITE PLANTWEBSITE, PLANT.Email PLANTEmail, --order 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.phoneno PLANTPHONENO, PLANT.faxno PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
SS.VALUE WEIGHTUNIT, SS1.VALUE PRINTDELNOTEPERCONTAINER
, SS2.VALUE CONTAINERRECORDINGACTIVE, SS3.VALUE PRINTDELNOTEZEROLINES
, 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(255)) WEEK
,languages.code languagecode, customerlanguage.code customerlanguagecode, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN clm.customer_id = null
      THEN 'N'
	    ELSE 'Y'
END)  hasLockeranagement,
clm.chargeservice, clm.chargerent, clm.uselockerobligated, clm.fixednumberbank,
packingnote.numberofgarmentsinlocker, packingnote.numberoflockers,
(select count(*) from PACKINGNOTECONTAINER pnc
   left outer join CONTAINER C on C.CONTAINER_ID = PNC.CONTAINER_ID
   left outer join CONTAINERTYPE CT on CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   left outer join WEIGHINGCATEGORY W on W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 where pnc.packingnote_id = PACKINGNOTE.Packingnote_Id) noOfContainers,
plantdepartment.code plant_dep_code, plantdepartment.description plant_dep_desc,
packingnote.freeofchargereason_id,
(select r.code from reasoncode r
        where r.reasoncode_id = packingnote.freeofchargereason_id) free_reason_code,
(select rd.description from reasoncode_desc rd
        where rd.reasoncode_id = packingnote.freeofchargereason_id
        and rd.language_id = languages.language_id) free_reason_code_desc,
(select count(*) from packingnoteline lines
        where lines.packingnote_id = packingnote.packingnote_id
              and lines.origin in (2,4)) numberOfPossibleLinesWithScans
, PACKINGNOTE.Year year
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, cu.decimals, cu.invoiceamountdecimals, cu.code CurrencyCode,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.Referencenumber
--, 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
, INVOICEBU.Internalvatnumber
, CUSTOMER.Searchname, PROCESSBU.Code PROCESSBUCODE
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,
--       left outer join customerbillinginfo cbi
--             LEFT OUTER JOIN bankinstitution Lbank
--             ON cbi.laundrybankinstitution_id = Lbank.bankinstitution_id
--        on CUSTOMER.Debtor_Id = cbi.customer_id,
        ADDRESS, DEPARTMENT, DISTRIBUTIONPOINT, PLANT, ADDRESS PLANTADDRESS,
        BUSINESSUNIT PROCESSBU,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, plantdepartment, currency cu,
        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 STATUS.statustype = 'PN' AND (STATUS.code = 30 OR STATUS.code = 20)
	AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.address_id = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 cu.currency_id = customer.currency_id
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID

/
create or replace view V_DELIVERYNOTE_KNT_ANG
 (PACKINGNOTE_ID, SEQUENCENUMBER, TAREWEIGHT, GROSSWEIGHT, SOILPORTION, WEIGHTDECIMALS, WEIGHINGSEQUENCENR, WEIGHINGTIMESTAMP, CONTAINER_PRIMARYID, CONTAINERTYPE_CODE, CONTAINERTYPE_DEFAULTTARAW, CONTAINERTYPE_ACTIVE, DISINFECTBEFOREDELIVERY, WEIGHCAT_CODE, WEIGHCAT_LEGACYCODE, WEIGHINGCATEGORYDESC, CONTAINERTYPE_DESC, PRICE, AMOUNT, TAXGROUPCODE, LANGUAGECODE, LANGUAGE_ID)
as select pnc.packingnote_id, pnc.sequencenumber, pnc.tareweight, pnc.grossweight,
       pnc.soilportion, pnc.weightdecimals, pnc.weighingsequencenr, pnc.weighingtimestamp,
       c.primaryid CONTAINER_PRIMARYID,
       ct.code CONTAINERTYPE_CODE, ct.defaulttaraweight CONTAINERTYPE_DEFAULTTARAW,
       ct.active CONTAINERTYPE_ACTIVE, ct.disinfectbeforedelivery,
       w.code WEIGHCAT_CODE, w.legacyweighingcategorycode WEIGHCAT_LEGACYCODE,
       (select wd.description from weighingcategory_desc wd
        where wd.weighingcategory_id = w.weighingcategory_id and wd.language_id = LANGUAGES.LANGUAGE_ID) weighingcategorydesc,
       (select CTD.DESCRIPTION from CONTAINERTYPE_DESC CTD
        where CTD.CONTAINERTYPE_ID = CT.CONTAINERTYPE_ID and CTD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) CONTAINERTYPE_DESC,
       pnc.price, pnc.amount, pnc.taxgroupcode,
       LANGUAGES.Code LANGUAGECODE, languages.language_id
from PACKINGNOTECONTAINER pnc
        left outer join CONTAINER C on C.CONTAINER_ID = PNC.CONTAINER_ID
        left outer join CONTAINERTYPE CT on CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
        left outer join WEIGHINGCATEGORY W on W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID,
     LANGUAGES

/
create or replace view V_DELIVERYNOTE_KNT_BLY
 (PACKINGNOTE_ID, CONTAINER_PRIMARYID, CONTAINER_SECONDARYID, CONTAINERTYPE_CODE, CONTAINERTYPE_DESC, LANGUAGECODE, LANGUAGE_ID)
as select pnc.packingnote_id,
       c.primaryid container_primaryid,
       sc.secondaryid container_secondaryid,
       ct.code containertype_code,
       (select ctd.description
          from containertype_desc ctd
         where ctd.containertype_id = ct.containertype_id
           and ctd.language_id = languages.language_id) containertype_desc,
       languages.code languagecode,
       languages.language_id
  from packingnotecontainer pnc
  left outer join container c
    on c.container_id = pnc.container_id
  left outer join secondarycontainer sc
    on sc.container_id = pnc.container_id
  left outer join containertype ct
    on ct.containertype_id = pnc.containertype_id,
 languages

/
create or replace view V_DELIVERYNOTE_KNT_SMG
 (NOTONSITE, PACKINGNOTE_ID, SEQUENCENUMBER, CONTAINER_PRIMARYID, CONTAINERTYPE_CODE, CONTAINERTYPE_DEFAULTTARAW, CONTAINERTYPE_ACTIVE, DISINFECTBEFOREDELIVERY, CONTAINERTYPE_DESC, CONTAINER_ALL_PRIMARYIDS, LANGUAGECODE)
as select --+index(pnc XAK1PACKINGNOTECONTAINER) index(CT XPKCONTAINERTYPE)
       1 NotOnSite, pnc.packingnote_id, pnc.sequencenumber,
       (select c.primaryid
       from container c
       where c.container_id = pnc.container_id) CONTAINER_PRIMARYID,
       ct.code CONTAINERTYPE_CODE, ct.defaulttaraweight CONTAINERTYPE_DEFAULTTARAW,
       ct.active CONTAINERTYPE_ACTIVE, ct.disinfectbeforedelivery,
       (select CTD.DESCRIPTION from CONTAINERTYPE_DESC CTD
        where CTD.CONTAINERTYPE_ID = CT.CONTAINERTYPE_ID and CTD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) CONTAINERTYPE_DESC
       , (select count(co.primaryid) qty from container co, packingnote pn
          where pn.packingnote_id = pnc.packingnote_id and co.containertype_id = ct.containertype_id
                and co.distributionpoint_id = pn.distributionpoint_id and trunc(co.lastoutscandate) <= trunc(pn.deliverydate)
         ) CONTAINER_ALL_PRIMARYIDs,
       LANGUAGES.Code LANGUAGECODE
from PACKINGNOTECONTAINER pnc, CONTAINERTYPE CT, LANGUAGES
where CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
union all --containers on site at customer
select 0 NotOnSite, pn.packingnote_id, 0 sequencenumber,
       c.primaryid CONTAINER_PRIMARYID,
       ct.code CONTAINERTYPE_CODE, ct.defaulttaraweight CONTAINERTYPE_DEFAULTTARAW,
       ct.active CONTAINERTYPE_ACTIVE, ct.disinfectbeforedelivery,
       (select CTD.DESCRIPTION from CONTAINERTYPE_DESC CTD
        where CTD.CONTAINERTYPE_ID = CT.CONTAINERTYPE_ID and CTD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) CONTAINERTYPE_DESC
       , (select count(co.primaryid) qty from container co where co.containertype_id = ct.containertype_id
                and co.distributionpoint_id = pn.distributionpoint_id and trunc(co.lastoutscandate) <= trunc(pn.deliverydate)
         ) CONTAINER_ALL_PRIMARYIDs,
       LANGUAGES.Code LANGUAGECODE
from packingnote pn, CONTAINERTYPE CT, container c, stay st, LANGUAGES
where ct.containertype_id = c.containertype_id and c.distributionpoint_id = pn.distributionpoint_id
      and c.stay_id = st.stay_id and st.staytype = 2 and st.staynr in (20, 21) --on-site at customer
      and not exists (select 1 from packingnotecontainer pnc
              where pnc.packingnote_id = pn.packingnote_id and pnc.containertype_id = ct.containertype_id)

/
create or replace view V_DELIVERYNOTE_LTB
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION, PLANTCODE, PLANTNAME
, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, 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)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
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,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL, --ORDER 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
SS.VALUE WEIGHTUNIT, SS1.VALUE PRINTDELNOTEPERCONTAINER
, SS2.VALUE CONTAINERRECORDINGACTIVE, SS3.VALUE PRINTDELNOTEZEROLINES
, 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(255)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
      ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
coalesce((SELECT min(PNC.PACKINGNOTE_ID) FROM PACKINGNOTECONTAINER PNC
   LEFT OUTER JOIN CONTAINER C ON C.CONTAINER_ID = PNC.CONTAINER_ID
   LEFT OUTER JOIN CONTAINERTYPE CT ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   LEFT OUTER JOIN WEIGHINGCATEGORY W ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID),0) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC
, coalesce((select max(ds.packingnote_id)
                 from   deliveryscan ds
                 where  ds.packingnote_id = packingnote.packingnote_id),
                 (select max(o.packingnote_id)
                   from   outofcirculationhistory o
                   where  o.packingnote_id = packingnote.packingnote_id), 0) numberofpossiblelineswithscans
, PACKINGNOTE.YEAR YEAR
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.REFERENCENUMBER
, INVOICEBU.INTERNALVATNUMBER
, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE
, ROUTE.PUTUPREPORTPERCUSTOMER
, customer.signaturerequired
, dsig.personidentification personidentification
, dsig.signature signature
, (select rc.drivingdate from routecontrol rc where rc.routecontrol_id = stop.routecontrol_id) signaturedate
, to_char(stop.departuretime,'fmhhfm:MI:AM') signaturetime
, to_char(stop.departuretime,'fmhh24fm:MI') signaturetime24
, packingnote.distributionpoint_id
, packingnote.processbusinessunit_id
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,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        PACKINGNOTE
          LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
          LEFT OUTER JOIN ROUTE ON (PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID)
          LEFT OUTER JOIN STOP ON (PACKINGNOTE.STOP_ID = STOP.STOP_ID)
          left outer join deliverysignature dsig on (dsig.stop_id = packingnote.stop_id and dsig.stop_id=packingnote.deliverysignature_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 CUSTOMER.VISITADDRESS_ID=ADDRESS.ADDRESS_ID
  AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  AND PACKINGNOTE.STATUS_ID = STATUS.STATUS_ID
  AND STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20 or (packingnote.origin = 14 and status.code = 40))
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID

/
create or replace view V_DELIVERYNOTE_LTS
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION, PLANTCODE, PLANTNAME
, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, QTYBOXES, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, YEAR, PRICESCALCULATED, TOTALAMOUNT, TOTALAMOUNTEXCLUDINGVAT, WEIGHINGTICKET_ID, DECIMALS, INVOICEAMOUNTDECIMALS, CURRENCYCODE, VATNUMBER, REFERENCENUMBER
, INTERNALVATNUMBER, SEARCHNAME, PROCESSBUCODE, PUTUPREPORTPERCUSTOMER, LABELCOLOR, INTERNALREMARKFORTRANSPLABEL, TRANSPLABINTERNALREMARKENDDATE, EXTERNALREMARKFORTRANSPLABEL, TRANSPLABEXTERNALREMARKENDDATE, NOOFTRANSPORTLABELS, USAGEDAYNUMBER, USAGEDAYDESC, PURCHASEORDERNO, PRD500AMNT, DRIVINGDAY_DESC, DN_LAYOUTCODE, PLANTLOGO)
as select
packingnote.correctednotenumber,
(select cn.deliverydate from packingnote cn where packingnote.correctednotenumber = cn.notenumber
  and packingnote.correctednotenumber<>0) correctiondate,
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,
(select description from transportarticle_desc  a
        where a.transportarticle_id = packingnote.transportarticle_id
              and a.language_id = customerlanguage.language_id ) transportarticledescription,
packingnote.occupancy, employee.name employeename, packingnote.deliverydate,
packingnote.originaldeliverydate, packingnote.remark, processbu.description processbudescription,
plant.code plantcode, plant.name plantname, plant.website plantwebsite, plant.email plantemail, --order 501604
plantaddress.street plantstreet, plantaddress.zipcode plantzipcode,
plantaddress.city plantcity, plantaddress.state plantstate, plant.phoneno plantphoneno, plant.faxno plantfaxno,
c2.code plantcountry_code, c2.description plantcountry_desc,
ss.value weightunit, ss1.value printdelnotepercontainer
, ss2.value containerrecordingactive, ss3.value printdelnotezerolines
, 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 upper(dd.description) from day_desc dd
         where dd.language_id = customerlanguage.language_id
         and dd.day_id = packingnote.daynumber) daydescription
, cast(packingnote.week as varchar2(255)) week
,languages.code languagecode, customerlanguage.code customerlanguagecode, packingnote.productiondate productiondate,
customer.scansondeliverynote,
(case when clm.customer_id = null
      then 'n'
      else 'y'
end)  haslockeranagement,
clm.chargeservice, clm.chargerent, clm.uselockerobligated, clm.fixednumberbank,
packingnote.numberofgarmentsinlocker, packingnote.numberoflockers,
(select count(*) from packingnotecontainer pnc
   left outer join container c on c.container_id = pnc.container_id
   left outer join containertype ct on ct.containertype_id = pnc.containertype_id
   left outer join weighingcategory w on w.weighingcategory_id = pnc.weighingcategory_id
 where pnc.packingnote_id = packingnote.packingnote_id) noofcontainers,
 (select count(pbx.boxnumber) from packingnotebox pbx
   where pbx.packingnote_id = packingnote.packingnote_id
   ) QtyBoxes,
plantdepartment.code plant_dep_code, plantdepartment.description plant_dep_desc,
packingnote.freeofchargereason_id,
(select r.code from reasoncode r
        where r.reasoncode_id = packingnote.freeofchargereason_id) free_reason_code,
(select rd.description from reasoncode_desc rd
        where rd.reasoncode_id = packingnote.freeofchargereason_id
        and rd.language_id = customerlanguage.language_id) free_reason_code_desc,
(select count(*) from packingnoteline lines
        where lines.packingnote_id = packingnote.packingnote_id
              and lines.origin in (2,4)) numberofpossiblelineswithscans
, packingnote.year year
, packingnote.pricescalculated, packingnote.totalamount, packingnote.totalamountexcludingvat
, packingnote.weighingticket_id, cu.decimals, cu.invoiceamountdecimals, cu.code currencycode,
invoicebu.vatnumber vatnumber
, packingnote.referencenumber
, invoicebu.internalvatnumber
, customer.searchname, processbu.code processbucode
, route.putupreportpercustomer
--, (select pca.state from plantcompany pc, address pca where pc.plant_id = plant.plant_id and pc.address_id = pca.address_id) kvk
, distributionpoint.labelcolor, distributionpoint.internalremarkfortransplabel
, distributionpoint.transplabinternalremarkenddate, distributionpoint.externalremarkfortransplabel
, distributionpoint.transplabexternalremarkenddate, distributionpoint.nooftransportlabels
, (select dud.usageday_id from departmentusageday dud where dud.department_id = department.department_id and dud.day_id = route.drivingday_id) usagedaynumber
, (select dd.description from departmentusageday dud, day_desc dd where dud.department_id = department.department_id and dud.usageday_id = dd.day_id and dud.day_id = route.drivingday_id and dd.language_id = customerlanguage.language_id) usagedaydesc
, (select max(cpc.purchaseorder) from contractspercustomer cpc, purchaseorderheader poh where cpc.customer_id = customer.customer_id) purchaseorderno
, (select sum(pnl.deliveredamount) from packingnoteline pnl where pnl.packingnote_id = packingnote.packingnote_id and pnl.product_id = (select p.product_id from product p where p.code = '000500')) prd500amnt
, (select dd.description from day_desc dd where dd.day_id = route.drivingday_id and dd.language_id = customerlanguage.language_id) drivingday_desc
, (select fl.code from formlayout fl where fl.formlayout_id = customer.deliverynotelayout_id) dn_layoutcode
, plant.logo PLANTLOGO
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,
        businessunit invoicebu,
        deliverypoint, systemsetting ss, systemsetting ss1,
        systemsetting ss2, systemsetting ss3,
        status, country c1, country c2, plantdepartment, currency cu,
        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 status.statustype = 'PN' and (status.code = 30 or status.code = 20 or (packingnote.origin = 14 and status.code = 40))
  and packingnote.processbusinessunit_id = processbu.businessunit_id
  and processbu.plant_id = plant.plant_id
  and plant.address_id = plantaddress.address_id
  and ss.plant_id = plant.plant_id
  and ss.name = 'WEIGHTUNIT'
  and ss1.plant_id = plant.plant_id
  and ss1.name = 'PRINTDELNOTEPERCONTAINER'
  and ss2.plant_id = plant.plant_id
  and ss2.name = 'CONTAINERRECORDINGACTIVE'
  and ss3.plant_id = plant.plant_id
  and ss3.name = 'PRINTDELNOTEZEROLINES'
  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 cu.currency_id = customer.currency_id
  and packingnote.invoicebusinessunit_id = invoicebu.businessunit_id

/
create or replace view V_DELIVERYNOTE_MFM
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERLEGALNAME, CUSTOMERSTREET, CUSTOMERSTREET2, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, CUSTOMERCOUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK
, PROCESSBUDESCRIPTION, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTSREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, DEFPLANTDEPART, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, 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, LNDRY_BANK_DESC, LNDR_BANK_IBANNO, LNDR_BANK_ACCOUNT, CONTACTPERSONNAME)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME,CUSTOMER.LEGALNAME CUSTOMERLEGALNAME,
ADDRESS.STREET CUSTOMERSTREET, ADDRESS.STREET2 CUSTOMERSTREET2,  ADDRESS.ZIPCODE CUSTOMERZIP, ADDRESS.CITY CUSTOMERCITY, ADDRESS.STATE CUSTOMERSTATE,
C1.CODE CUSTCOUNTRY, C1.DESCRIPTION CUSTCOUNTRY_DESC, ADDRESS.COUNTY CUSTOMERCOUNTY,
DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
PACKINGNOTE.SEQUENCENUMBER,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, --CAST(
PACKINGNOTE.REMARK /*AS VARCHAR2(60) )*/ REMARK
, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL, --ORDER 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.STREET2 PLANTSREET2, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
cast (SS.VALUE as varchar2(60)) WEIGHTUNIT,
cast (SS1.VALUE as varchar2(1)) PRINTDELNOTEPERCONTAINER,
cast (SS2.VALUE as varchar2(1)) CONTAINERRECORDINGACTIVE,
cast (SS3.VALUE as varchar2(1)) PRINTDELNOTEZEROLINES,
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(60)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
      ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
coalesce((SELECT min(PNC.PACKINGNOTE_ID) FROM PACKINGNOTECONTAINER PNC
   LEFT OUTER JOIN CONTAINER C ON C.CONTAINER_ID = PNC.CONTAINER_ID
   LEFT OUTER JOIN CONTAINERTYPE CT ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   LEFT OUTER JOIN WEIGHINGCATEGORY W ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID),0) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
(SELECT pd.description from plantdepartment pd where pd.plant_id = plant.plant_id and pd.defaultplantdepartment = 'Y') defplantdepart,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC
, coalesce((select max(ds.packingnote_id)
                 from   deliveryscan ds
                 where  ds.packingnote_id = packingnote.packingnote_id),
                 (select max(o.packingnote_id)
                   from   outofcirculationhistory o
                   where  o.packingnote_id = packingnote.packingnote_id), 0) numberofpossiblelineswithscans
, PACKINGNOTE.YEAR YEAR
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.REFERENCENUMBER
, INVOICEBU.INTERNALVATNUMBER
, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE
, ROUTE.PUTUPREPORTPERCUSTOMER
, customer.signaturerequired
, dsig.personidentification personidentification
, dsig.signature signature
, (select rc.drivingdate from routecontrol rc where rc.routecontrol_id = stop.routecontrol_id) signaturedate
, to_char(stop.departuretime,'fmhhfm:MI:AM') signaturetime
, to_char(stop.departuretime,'fmhh24fm:MI') signaturetime24
, packingnote.distributionpoint_id
, packingnote.processbusinessunit_id
,(SELECT lbank.description  FROM customerbillinginfo cbilinfo, bankinstitution lbank
                            WHERE cbilinfo.customer_id=customer.customer_id and lbank.bankinstitution_id=cbilinfo.bankinstitution_id) lndry_bank_desc
 ,(SELECT lbank.ibanno FROM customerbillinginfo cbilinfo, bankinstitution lbank
                            WHERE cbilinfo.customer_id=customer.customer_id and lbank.bankinstitution_id=cbilinfo.bankinstitution_id) lndr_bank_ibanno
 ,(SELECT lbank.laundrybankaccount FROM customerbillinginfo cbilinfo, bankinstitution lbank
                            WHERE cbilinfo.customer_id=customer.customer_id and lbank.bankinstitution_id=cbilinfo.bankinstitution_id) lndr_bank_account
 ,(select cp.name from contactperson cp where cp.contactpersonnumber =
(select min(cp2.contactpersonnumber) from contactperson cp2 where cp2.customer_id =customer.customer_id)
and cp.customer_id = customer.customer_id  )contactpersonname
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,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        PACKINGNOTE
          LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
          LEFT OUTER JOIN ROUTE ON (PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID)
          LEFT OUTER JOIN STOP ON (PACKINGNOTE.STOP_ID = STOP.STOP_ID)
          left outer join deliverysignature dsig on (dsig.stop_id = packingnote.stop_id and dsig.stop_id=packingnote.deliverysignature_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 STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20 or (packingnote.origin = 14 and status.code = 40))
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID

/
create or replace view V_DELIVERYNOTE_NAF
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERSTREET2, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, CUSTOMERCOUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION
, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, 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)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME,
ADDRESS.STREET CUSTOMERSTREET, ADDRESS.STREET2 CUSTOMERSTREET2,  ADDRESS.ZIPCODE CUSTOMERZIP, ADDRESS.CITY CUSTOMERCITY, ADDRESS.STATE CUSTOMERSTATE,
C1.CODE CUSTCOUNTRY, C1.DESCRIPTION CUSTCOUNTRY_DESC, ADDRESS.COUNTY CUSTOMERCOUNTY,
DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
PACKINGNOTE.SEQUENCENUMBER,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, CAST(
PACKINGNOTE.REMARK AS VARCHAR2(60) ) REMARK
, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL, --ORDER 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
cast (SS.VALUE as varchar2(60)) WEIGHTUNIT,
cast (SS1.VALUE as varchar2(1)) PRINTDELNOTEPERCONTAINER,
cast (SS2.VALUE as varchar2(1)) CONTAINERRECORDINGACTIVE,
cast (SS3.VALUE as varchar2(1)) PRINTDELNOTEZEROLINES,
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(60)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
      ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
coalesce((SELECT min(PNC.PACKINGNOTE_ID) FROM PACKINGNOTECONTAINER PNC
   LEFT OUTER JOIN CONTAINER C ON C.CONTAINER_ID = PNC.CONTAINER_ID
   LEFT OUTER JOIN CONTAINERTYPE CT ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   LEFT OUTER JOIN WEIGHINGCATEGORY W ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID),0) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC
, coalesce((select max(ds.packingnote_id)
                 from   deliveryscan ds
                 where  ds.packingnote_id = packingnote.packingnote_id),
                 (select max(o.packingnote_id)
                   from   outofcirculationhistory o
                   where  o.packingnote_id = packingnote.packingnote_id), 0) numberofpossiblelineswithscans
, PACKINGNOTE.YEAR YEAR
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.REFERENCENUMBER
, INVOICEBU.INTERNALVATNUMBER
, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE
, ROUTE.PUTUPREPORTPERCUSTOMER
, customer.signaturerequired
, dsig.personidentification personidentification
, dsig.signature signature
, (select rc.drivingdate from routecontrol rc where rc.routecontrol_id = stop.routecontrol_id) signaturedate
, to_char(stop.departuretime,'fmhhfm:MI:AM') signaturetime
, to_char(stop.departuretime,'fmhh24fm:MI') signaturetime24
, packingnote.distributionpoint_id
, packingnote.processbusinessunit_id
, DELIVERYPOINT. SIGNATUREBARCODE
, cast ((SELECT SS.VALUE FROM SYSTEMSETTING SS WHERE SS.PLANT_ID=PLANT.PLANT_ID AND SS.NAME ='CONTAINERTYPEUNQBRCLABEL')  as varchar2(60)) containertypedescription
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,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        PACKINGNOTE
          LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
          LEFT OUTER JOIN ROUTE ON (PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID)
          LEFT OUTER JOIN STOP ON (PACKINGNOTE.STOP_ID = STOP.STOP_ID)
          left outer join deliverysignature dsig on (dsig.stop_id = packingnote.stop_id and dsig.stop_id=packingnote.deliverysignature_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 STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20 or (packingnote.origin = 14 and status.code = 40))
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID

/
create or replace view V_DELIVERYNOTE_NLI
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION, PLANTCODE, PLANTNAME
, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, 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, NOOFBOXES)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
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,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL, --ORDER 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
cast (SS.VALUE as varchar2(60)) WEIGHTUNIT,
cast (SS1.VALUE as varchar2(1)) PRINTDELNOTEPERCONTAINER,
cast (SS2.VALUE as varchar2(1)) CONTAINERRECORDINGACTIVE,
cast (SS3.VALUE as varchar2(1)) PRINTDELNOTEZEROLINES,
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(60)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
      ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
coalesce((SELECT min(PNC.PACKINGNOTE_ID) FROM PACKINGNOTECONTAINER PNC
   LEFT OUTER JOIN CONTAINER C ON C.CONTAINER_ID = PNC.CONTAINER_ID
   LEFT OUTER JOIN CONTAINERTYPE CT ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   LEFT OUTER JOIN WEIGHINGCATEGORY W ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID),0) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC
, coalesce((select max(ds.packingnote_id)
                 from   deliveryscan ds
                 where  ds.packingnote_id = packingnote.packingnote_id),
                 (select max(o.packingnote_id)
                   from   outofcirculationhistory o
                   where  o.packingnote_id = packingnote.packingnote_id), 0) numberofpossiblelineswithscans
, PACKINGNOTE.YEAR YEAR
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.REFERENCENUMBER
, INVOICEBU.INTERNALVATNUMBER
, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE
, ROUTE.PUTUPREPORTPERCUSTOMER
, customer.signaturerequired
, dsig.personidentification personidentification
, dsig.signature signature
, (select rc.drivingdate from routecontrol rc where rc.routecontrol_id = stop.routecontrol_id) signaturedate
, to_char(stop.departuretime,'fmhhfm:MI:AM') signaturetime
, to_char(stop.departuretime,'fmhh24fm:MI') signaturetime24
, packingnote.distributionpoint_id
, packingnote.processbusinessunit_id,
(select count(1) from packingnotebox pnb where pnb.packingnote_id = PACKINGNOTE.PACKINGNOTE_ID) noofboxes
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,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        PACKINGNOTE
          LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
          LEFT OUTER JOIN ROUTE ON (PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID)
          LEFT OUTER JOIN STOP ON (PACKINGNOTE.STOP_ID = STOP.STOP_ID)
          left outer join deliverysignature dsig on (dsig.stop_id = packingnote.stop_id and dsig.stop_id=packingnote.deliverysignature_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 STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20 or (packingnote.origin = 14 and status.code = 40))
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID

/
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_PHS
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERSTREET2, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, CUSTOMERCOUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION
, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, 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, WOREFNUMBER, SALESNOTEREFNR)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME,
ADDRESS.STREET CUSTOMERSTREET, ADDRESS.STREET2 CUSTOMERSTREET2,  ADDRESS.ZIPCODE CUSTOMERZIP, ADDRESS.CITY CUSTOMERCITY, ADDRESS.STATE CUSTOMERSTATE,
C1.CODE CUSTCOUNTRY, C1.DESCRIPTION CUSTCOUNTRY_DESC, ADDRESS.COUNTY CUSTOMERCOUNTY,
DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
PACKINGNOTE.SEQUENCENUMBER,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, --CAST(
PACKINGNOTE.REMARK --AS VARCHAR2(60) ) REMARK
, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL, --ORDER 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
cast (SS.VALUE as varchar2(60)) WEIGHTUNIT,
cast (SS1.VALUE as varchar2(1)) PRINTDELNOTEPERCONTAINER,
cast (SS2.VALUE as varchar2(1)) CONTAINERRECORDINGACTIVE,
cast (SS3.VALUE as varchar2(1)) PRINTDELNOTEZEROLINES,
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(60)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
      ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
coalesce((SELECT min(PNC.PACKINGNOTE_ID) FROM PACKINGNOTECONTAINER PNC
   LEFT OUTER JOIN CONTAINER C ON C.CONTAINER_ID = PNC.CONTAINER_ID
   LEFT OUTER JOIN CONTAINERTYPE CT ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   LEFT OUTER JOIN WEIGHINGCATEGORY W ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID),0) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC
, coalesce((select max(ds.packingnote_id)
                 from   deliveryscan ds
                 where  ds.packingnote_id = packingnote.packingnote_id),
                 (select max(o.packingnote_id)
                   from   outofcirculationhistory o
                   where  o.packingnote_id = packingnote.packingnote_id), 0) numberofpossiblelineswithscans
, PACKINGNOTE.YEAR YEAR
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.REFERENCENUMBER
, INVOICEBU.INTERNALVATNUMBER
, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE
, ROUTE.PUTUPREPORTPERCUSTOMER
, customer.signaturerequired
, dsig.personidentification personidentification
, dsig.signature signature
, (select rc.drivingdate from routecontrol rc where rc.routecontrol_id = stop.routecontrol_id) signaturedate
, to_char(stop.departuretime,'fmhhfm:MI:AM') signaturetime
, to_char(stop.departuretime,'fmhh24fm:MI') signaturetime24
, packingnote.distributionpoint_id
, packingnote.processbusinessunit_id
, (select max(wo.referencenumber) from deliveryscan ds, issuehistory ih, workorder wo
where ds.uniqueitem_link_id = ih.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 ih.workorder_id = wo.workorder_id
and ds.packingnote_id = packingnote.packingnote_id
and wo.deliverfrom=2
) worefnumber
,(select max(wo.referencenumber) from workorder wo where wo.workorder_id = packingnote.salesnote_id) SalesNoteRefNr
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,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        PACKINGNOTE
          LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
          LEFT OUTER JOIN ROUTE ON (PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID)
          LEFT OUTER JOIN STOP ON (PACKINGNOTE.STOP_ID = STOP.STOP_ID)
          left outer join deliverysignature dsig on dsig.stop_id = packingnote.stop_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 STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20 or (packingnote.origin = 14 and status.code = 40))
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_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_DELIVERYNOTE_POS
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERSTREET2, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, CUSTOMERCOUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION
, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, 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, WOREFNUMBER, PURCHASEORDERNUMBER)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME,
ADDRESS.STREET CUSTOMERSTREET, ADDRESS.STREET2 CUSTOMERSTREET2,  ADDRESS.ZIPCODE CUSTOMERZIP, ADDRESS.CITY CUSTOMERCITY, ADDRESS.STATE CUSTOMERSTATE,
C1.CODE CUSTCOUNTRY, C1.DESCRIPTION CUSTCOUNTRY_DESC, ADDRESS.COUNTY CUSTOMERCOUNTY,
DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
PACKINGNOTE.SEQUENCENUMBER,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, --CAST(
PACKINGNOTE.REMARK --AS VARCHAR2(60) ) REMARK
, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL, --ORDER 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
cast (SS.VALUE as varchar2(60)) WEIGHTUNIT,
cast (SS1.VALUE as varchar2(1)) PRINTDELNOTEPERCONTAINER,
cast (SS2.VALUE as varchar2(1)) CONTAINERRECORDINGACTIVE,
cast (SS3.VALUE as varchar2(1)) PRINTDELNOTEZEROLINES,
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(60)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
      ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
coalesce((SELECT min(PNC.PACKINGNOTE_ID) FROM PACKINGNOTECONTAINER PNC
   LEFT OUTER JOIN CONTAINER C ON C.CONTAINER_ID = PNC.CONTAINER_ID
   LEFT OUTER JOIN CONTAINERTYPE CT ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   LEFT OUTER JOIN WEIGHINGCATEGORY W ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID),0) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC
, coalesce((select max(ds.packingnote_id)
                 from   deliveryscan ds
                 where  ds.packingnote_id = packingnote.packingnote_id),
                 (select max(o.packingnote_id)
                   from   outofcirculationhistory o
                   where  o.packingnote_id = packingnote.packingnote_id), 0) numberofpossiblelineswithscans
, PACKINGNOTE.YEAR YEAR
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.REFERENCENUMBER
, INVOICEBU.INTERNALVATNUMBER
, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE
, ROUTE.PUTUPREPORTPERCUSTOMER
, customer.signaturerequired
, dsig.personidentification personidentification
, dsig.signature signature
, (select rc.drivingdate from routecontrol rc where rc.routecontrol_id = stop.routecontrol_id) signaturedate
, to_char(stop.departuretime,'fmhhfm:MI:AM') signaturetime
, to_char(stop.departuretime,'fmhh24fm:MI') signaturetime24
, packingnote.distributionpoint_id
, packingnote.processbusinessunit_id
, DELIVERYPOINT. SIGNATUREBARCODE
, cast ((SELECT SS.VALUE FROM SYSTEMSETTING SS WHERE SS.PLANT_ID=PLANT.PLANT_ID AND SS.NAME ='CONTAINERTYPEUNQBRCLABEL')  as varchar2(60)) containertypedescription
, (select max(wo.referencenumber) from deliveryscan ds, issuehistory ih, workorder wo
where ds.uniqueitem_link_id = ih.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 ih.workorder_id = wo.workorder_id
and ds.packingnote_id = packingnote.packingnote_id
and wo.deliverfrom=2
) worefnumber
, (select max(cpc.purchaseorder) from contractspercustomer cpc where cpc.customer_id = CUSTOMER.Customer_Id and
  cpc.dateactive <= PACKINGNOTE.Productiondate and cpc.dateinactive >= PACKINGNOTE.Productiondate) purchaseordernumber
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,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        PACKINGNOTE
          LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
          LEFT OUTER JOIN ROUTE ON (PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID)
          LEFT OUTER JOIN STOP ON (PACKINGNOTE.STOP_ID = STOP.STOP_ID)
          left outer join deliverysignature dsig on (dsig.stop_id = packingnote.stop_id and dsig.stop_id=packingnote.deliverysignature_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 STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20 or (packingnote.origin = 14 and status.code = 40))
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID

/
create or replace view V_DELIVERYNOTE_PRI
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION, PLANTCODE, PLANTNAME
, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, 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, REMARKPACKINGNOTE, COUNT_REF)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
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,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL, --ORDER 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
SS.VALUE WEIGHTUNIT, SS1.VALUE PRINTDELNOTEPERCONTAINER
, SS2.VALUE CONTAINERRECORDINGACTIVE, SS3.VALUE PRINTDELNOTEZEROLINES
, 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(255)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
      ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
coalesce((SELECT min(PNC.PACKINGNOTE_ID) FROM PACKINGNOTECONTAINER PNC
   LEFT OUTER JOIN CONTAINER C ON C.CONTAINER_ID = PNC.CONTAINER_ID
   LEFT OUTER JOIN CONTAINERTYPE CT ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   LEFT OUTER JOIN WEIGHINGCATEGORY W ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID),0) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC
, coalesce((select max(ds.packingnote_id)
                 from   deliveryscan ds
                 where  ds.packingnote_id = packingnote.packingnote_id),
                 (select max(o.packingnote_id)
                   from   outofcirculationhistory o
                   where  o.packingnote_id = packingnote.packingnote_id), 0) numberofpossiblelineswithscans
, PACKINGNOTE.YEAR YEAR
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.REFERENCENUMBER
, INVOICEBU.INTERNALVATNUMBER
, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE
, ROUTE.PUTUPREPORTPERCUSTOMER
, customer.signaturerequired
, dsig.personidentification personidentification
, dsig.signature signature
, (select rc.drivingdate from routecontrol rc where rc.routecontrol_id = stop.routecontrol_id) signaturedate
, to_char(stop.departuretime,'fmhhfm:MI:AM') signaturetime
, to_char(stop.departuretime,'fmhh24fm:MI') signaturetime24
, packingnote.distributionpoint_id
, packingnote.processbusinessunit_id
, (select dp.remarkonpackingnote from distributionpoint dp where dp.distributionpoint_id = packingnote.distributionpoint_id) remarkpackingnote
, (select count(1) from deliveryvariations dv where dv.packingnote_id = packingnote.packingnote_id and dv.reference is not null) count_ref
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,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        PACKINGNOTE
          LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
          LEFT OUTER JOIN ROUTE ON (PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID)
          LEFT OUTER JOIN STOP ON (PACKINGNOTE.STOP_ID = STOP.STOP_ID)
          left outer join deliverysignature dsig on (dsig.stop_id = packingnote.stop_id and dsig.stop_id=packingnote.deliverysignature_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 STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20 or (packingnote.origin = 14 and status.code = 40))
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID

/
create or replace view V_DELIVERYNOTE_REI
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION, PLANTCODE, PLANTNAME
, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, YEAR, PRICESCALCULATED, TOTALAMOUNT, TOTALAMOUNTEXCLUDINGVAT, WEIGHINGTICKET_ID, DECIMALS, INVOICEAMOUNTDECIMALS, CURRENCYCODE, VATNUMBER, REFERENCENUMBER, INTERNALVATNUMBER
, SEARCHNAME, PROCESSBUCODE, PUTUPREPORTPERCUSTOMER, WEIGHEDBY, MULTIPLEITEMS)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
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,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL, --ORDER 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
SS.VALUE WEIGHTUNIT, SS1.VALUE PRINTDELNOTEPERCONTAINER
, SS2.VALUE CONTAINERRECORDINGACTIVE, SS3.VALUE PRINTDELNOTEZEROLINES
, 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 DAY_DESC.DESCRIPTION FROM DAY_DESC, day
         WHERE DAY_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID
         AND DAY_DESC.DAY_ID = day.day_id and day.daynumber = PACKINGNOTE.DAYNUMBER) DAYDESCRIPTION
, CAST(PACKINGNOTE.WEEK AS VARCHAR2(255)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
	    ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
(SELECT COUNT(*) FROM PACKINGNOTECONTAINER PNC
   LEFT OUTER JOIN CONTAINER C ON C.CONTAINER_ID = PNC.CONTAINER_ID
   LEFT OUTER JOIN CONTAINERTYPE CT ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   LEFT OUTER JOIN WEIGHINGCATEGORY W ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC,
(SELECT COUNT(*) FROM PACKINGNOTELINE LINES
        WHERE LINES.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID
              AND LINES.ORIGIN IN (2,4)) NUMBEROFPOSSIBLELINESWITHSCANS
, PACKINGNOTE.YEAR YEAR
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.REFERENCENUMBER
--, 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
, INVOICEBU.INTERNALVATNUMBER
, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE
, ROUTE.PUTUPREPORTPERCUSTOMER
, (select max(su.fullname) from systemuser su, packingnotecontainer pac where PACKINGNOTE.Packingnote_Id = pac.packingnote_id and pac.systemuser_id =su.systemuser_id) WeighedBy
, (select max(1) from weighingcategory wc, packingnotecontainer pac where PACKINGNOTE.Packingnote_Id = pac.packingnote_id and
pac.weighingcategory_id = wc.weighingcategory_id and lpad(wc.code, 1) = '5') MultipleItems
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,
--       LEFT OUTER JOIN CUSTOMERBILLINGINFO CBI
--             LEFT OUTER JOIN BANKINSTITUTION LBANK
--             ON CBI.LAUNDRYBANKINSTITUTION_ID = LBANK.BANKINSTITUTION_ID
--        ON CUSTOMER.DEBTOR_ID = CBI.CUSTOMER_ID,
        ADDRESS, DEPARTMENT, DISTRIBUTIONPOINT, PLANT, ADDRESS PLANTADDRESS,
        BUSINESSUNIT PROCESSBU,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        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 STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20 or (packingnote.origin = 14 and status.code = 40))
	AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID

/
create or replace view V_DELIVERYNOTE_REO
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION, PLANTCODE, PLANTNAME
, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, YEAR, PRICESCALCULATED, TOTALAMOUNT, TOTALAMOUNTEXCLUDINGVAT, WEIGHINGTICKET_ID, DECIMALS, INVOICEAMOUNTDECIMALS, CURRENCYCODE, VATNUMBER, REFERENCENUMBER, INTERNALVATNUMBER
)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(select cn.deliverydate from PACKINGNOTE cn where PACKINGNOTE.CORRECTEDNOTENUMBER = cn.notenumber
  and PACKINGNOTE.CORRECTEDNOTENUMBER<>0) correctiondate,
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,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.Name PLANTName, PLANT.WEBSITE PLANTWEBSITE, PLANT.Email PLANTEmail, --order 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.phoneno PLANTPHONENO, PLANT.faxno PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
SS.VALUE WEIGHTUNIT, SS1.VALUE PRINTDELNOTEPERCONTAINER
, SS2.VALUE CONTAINERRECORDINGACTIVE, SS3.VALUE PRINTDELNOTEZEROLINES
, 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(255)) WEEK
,languages.code languagecode, customerlanguage.code customerlanguagecode, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN clm.customer_id = null
      THEN 'N'
	    ELSE 'Y'
END)  hasLockeranagement,
clm.chargeservice, clm.chargerent, clm.uselockerobligated, clm.fixednumberbank,
packingnote.numberofgarmentsinlocker, packingnote.numberoflockers,
(select count(*) from PACKINGNOTECONTAINER pnc
   left outer join CONTAINER C on C.CONTAINER_ID = PNC.CONTAINER_ID
   left outer join CONTAINERTYPE CT on CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   left outer join WEIGHINGCATEGORY W on W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 where pnc.packingnote_id = PACKINGNOTE.Packingnote_Id) noOfContainers,
plantdepartment.code plant_dep_code, plantdepartment.description plant_dep_desc,
packingnote.freeofchargereason_id,
(select r.code from reasoncode r
        where r.reasoncode_id = packingnote.freeofchargereason_id) free_reason_code,
(select rd.description from reasoncode_desc rd
        where rd.reasoncode_id = packingnote.freeofchargereason_id
        and rd.language_id = languages.language_id) free_reason_code_desc,
(select count(*) from packingnoteline lines
        where lines.packingnote_id = packingnote.packingnote_id
              and lines.origin in (2,4)) numberOfPossibleLinesWithScans
, PACKINGNOTE.Year year
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, cu.decimals, cu.invoiceamountdecimals, cu.code CurrencyCode,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.Referencenumber
/*, 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*/
, INVOICEBU.Internalvatnumber
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
/*        left outer join customerbillinginfo cbi
             LEFT OUTER JOIN bankinstitution Lbank
             ON cbi.laundrybankinstitution_id = Lbank.bankinstitution_id
        on CUSTOMER.Debtor_Id = cbi.customer_id*/,
        ADDRESS, DEPARTMENT, DISTRIBUTIONPOINT, PLANT, ADDRESS PLANTADDRESS,
        BUSINESSUNIT PROCESSBU,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, plantdepartment, currency cu,
        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 STATUS.statustype = 'PN' AND (STATUS.code = 30 OR STATUS.code = 20 or (packingnote.origin = 14 and status.code = 40))
	AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.address_id = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 cu.currency_id = customer.currency_id
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID

/
create or replace view V_DELIVERYNOTE_REV
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION, PLANTCODE, PLANTNAME
, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, YEAR, PRICESCALCULATED, TOTALAMOUNT, TOTALAMOUNTEXCLUDINGVAT, WEIGHINGTICKET_ID, DECIMALS, INVOICEAMOUNTDECIMALS, CURRENCYCODE, VATNUMBER, REFERENCENUMBER, INTERNALVATNUMBER
, SEARCHNAME, PROCESSBUCODE, PUTUPREPORTPERCUSTOMER, INVOICEBUCODE, INVOICEBUDESC, DIVISIONDESC, REGIONDESC)
as select
packingnote.correctednotenumber,
(select cn.deliverydate from packingnote cn where packingnote.correctednotenumber = cn.notenumber
  and packingnote.correctednotenumber<>0) correctiondate,
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,
(select description from transportarticle_desc  a
        where a.transportarticle_id = packingnote.transportarticle_id
              and a.language_id = languages.language_id ) transportarticledescription,
packingnote.occupancy, employee.name employeename, packingnote.deliverydate,
packingnote.originaldeliverydate, packingnote.remark, processbu.description processbudescription,
plant.code plantcode, plant.name plantname, plant.website plantwebsite, plant.email plantemail, --order 501604
plantaddress.street plantstreet, plantaddress.zipcode plantzipcode,
plantaddress.city plantcity, plantaddress.state plantstate, plant.phoneno plantphoneno, plant.faxno plantfaxno,
c2.code plantcountry_code, c2.description plantcountry_desc,
ss.value weightunit, ss1.value printdelnotepercontainer
, ss2.value containerrecordingactive, ss3.value printdelnotezerolines
, 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(255)) week
,languages.code languagecode, customerlanguage.code customerlanguagecode, packingnote.productiondate productiondate,
customer.scansondeliverynote,
(case when clm.customer_id = null
      then 'N'
	    else 'Y'
end)  haslockeranagement,
clm.chargeservice, clm.chargerent, clm.uselockerobligated, clm.fixednumberbank,
packingnote.numberofgarmentsinlocker, packingnote.numberoflockers,
(select count(*) from packingnotecontainer pnc
   left outer join container c on c.container_id = pnc.container_id
   left outer join containertype ct on ct.containertype_id = pnc.containertype_id
   left outer join weighingcategory w on w.weighingcategory_id = pnc.weighingcategory_id
 where pnc.packingnote_id = packingnote.packingnote_id) noofcontainers,
plantdepartment.code plant_dep_code, plantdepartment.description plant_dep_desc,
packingnote.freeofchargereason_id,
(select r.code from reasoncode r
        where r.reasoncode_id = packingnote.freeofchargereason_id) free_reason_code,
(select rd.description from reasoncode_desc rd
        where rd.reasoncode_id = packingnote.freeofchargereason_id
        and rd.language_id = languages.language_id) free_reason_code_desc,
(select count(*) from packingnoteline lines
        where lines.packingnote_id = packingnote.packingnote_id
              and lines.origin in (2,4)) numberofpossiblelineswithscans
, packingnote.year year
, packingnote.pricescalculated, packingnote.totalamount, packingnote.totalamountexcludingvat
, packingnote.weighingticket_id, cu.decimals, cu.invoiceamountdecimals, cu.code currencycode,
invoicebu.vatnumber vatnumber
, packingnote.referencenumber
, invoicebu.internalvatnumber
, customer.searchname, processbu.code processbucode
, route.putupreportpercustomer, invoicebu.code invoicebucode, invoicebu.description invoicebudesc
, (select dd.description from division_desc dd where invoicebu.division_id = dd.division_id and dd.language_id = languages.language_id) divisiondesc
, (select rd.description from region_desc rd where invoicebu.region_id = rd.region_id and rd.language_id = languages.language_id) regiondesc
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,
        businessunit invoicebu,
        deliverypoint, systemsetting ss, systemsetting ss1,
        systemsetting ss2, systemsetting ss3,
        status, country c1, country c2, plantdepartment, currency cu,
        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 status.statustype = 'PN' and (status.code = 30 or status.code = 20 or (packingnote.origin = 14 and status.code = 40))
	and packingnote.processbusinessunit_id = processbu.businessunit_id
  and processbu.plant_id = plant.plant_id
  and plant.address_id = plantaddress.address_id
  and ss.plant_id = plant.plant_id
  and ss.name = 'WEIGHTUNIT'
  and ss1.plant_id = plant.plant_id
  and ss1.name = 'PRINTDELNOTEPERCONTAINER'
  and ss2.plant_id = plant.plant_id
  and ss2.name = 'CONTAINERRECORDINGACTIVE'
  and ss3.plant_id = plant.plant_id
  and ss3.name = 'PRINTDELNOTEZEROLINES'
  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 cu.currency_id = customer.currency_id
  and packingnote.invoicebusinessunit_id = invoicebu.businessunit_id

/
create or replace view V_DELIVERYNOTE_RMI
 (LINETYPE, CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERSTREET2, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, CUSTOMERCOUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE
, REMARK, PROCESSBUDESCRIPTION, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, 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, WOREFNUMBER, PNREMARK, DELIVERYNOTEREMARKDESC)
as SELECT 1 linetype, PACKINGNOTE.CORRECTEDNOTENUMBER,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME,
ADDRESS.STREET CUSTOMERSTREET, ADDRESS.STREET2 CUSTOMERSTREET2,  ADDRESS.ZIPCODE CUSTOMERZIP, ADDRESS.CITY CUSTOMERCITY, ADDRESS.STATE CUSTOMERSTATE,
C1.CODE CUSTCOUNTRY, C1.DESCRIPTION CUSTCOUNTRY_DESC, ADDRESS.COUNTY CUSTOMERCOUNTY,
DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
PACKINGNOTE.SEQUENCENUMBER,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, --CAST(
PACKINGNOTE.REMARK --AS VARCHAR2(60) ) REMARK
, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL, --ORDER 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
cast (SS.VALUE as varchar2(60)) WEIGHTUNIT,
cast (SS1.VALUE as varchar2(1)) PRINTDELNOTEPERCONTAINER,
cast (SS2.VALUE as varchar2(1)) CONTAINERRECORDINGACTIVE,
cast (SS3.VALUE as varchar2(1)) PRINTDELNOTEZEROLINES,
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(60)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
      ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
coalesce((SELECT min(PNC.PACKINGNOTE_ID) FROM PACKINGNOTECONTAINER PNC
   LEFT OUTER JOIN CONTAINER C ON C.CONTAINER_ID = PNC.CONTAINER_ID
   LEFT OUTER JOIN CONTAINERTYPE CT ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   LEFT OUTER JOIN WEIGHINGCATEGORY W ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID),0) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC
, coalesce((select max(ds.packingnote_id)
                 from   deliveryscan ds
                 where  ds.packingnote_id = packingnote.packingnote_id),
                 (select max(o.packingnote_id)
                   from   outofcirculationhistory o
                   where  o.packingnote_id = packingnote.packingnote_id), 0) numberofpossiblelineswithscans
, PACKINGNOTE.YEAR YEAR, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE, INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.REFERENCENUMBER, INVOICEBU.INTERNALVATNUMBER, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE, ROUTE.PUTUPREPORTPERCUSTOMER
, customer.signaturerequired, dsig.personidentification personidentification, dsig.signature signature
, (select rc.drivingdate from routecontrol rc where rc.routecontrol_id = stop.routecontrol_id) signaturedate
, to_char(stop.departuretime,'fmhhfm:MI:AM') signaturetime
, to_char(stop.departuretime,'fmhh24fm:MI') signaturetime24
, packingnote.distributionpoint_id
, packingnote.processbusinessunit_id
, DELIVERYPOINT. SIGNATUREBARCODE
, cast ((SELECT SS.VALUE FROM SYSTEMSETTING SS WHERE SS.PLANT_ID=PLANT.PLANT_ID AND SS.NAME ='CONTAINERTYPEUNQBRCLABEL')  as varchar2(60)) containertypedescription
, (select max(wo.referencenumber) from deliveryscan ds, issuehistory ih, workorder wo
where ds.uniqueitem_link_id = ih.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 ih.workorder_id = wo.workorder_id
and ds.packingnote_id = packingnote.packingnote_id
and wo.deliverfrom = 2
) worefnumber, packingnote.pnremark,
(select dnrd.description from deliverynoteremark_desc dnrd where dnrd.deliverynoteremark_id = packingnote.deliverynoteremark_id
        and dnrd.language_id = customer.language_id) deliverynoteremarkdesc
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,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        PACKINGNOTE
          LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
          LEFT OUTER JOIN ROUTE ON (PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID)
          LEFT OUTER JOIN STOP ON (PACKINGNOTE.STOP_ID = STOP.STOP_ID)
          left outer join deliverysignature dsig on (dsig.stop_id = packingnote.stop_id and dsig.stop_id=packingnote.deliverysignature_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 STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20 or (packingnote.origin = 14 and status.code = 40))
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
union all --duplicate data when layout is DNM
SELECT 2 linetype, PACKINGNOTE.CORRECTEDNOTENUMBER,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME,
ADDRESS.STREET CUSTOMERSTREET, ADDRESS.STREET2 CUSTOMERSTREET2,  ADDRESS.ZIPCODE CUSTOMERZIP, ADDRESS.CITY CUSTOMERCITY, ADDRESS.STATE CUSTOMERSTATE,
C1.CODE CUSTCOUNTRY, C1.DESCRIPTION CUSTCOUNTRY_DESC, ADDRESS.COUNTY CUSTOMERCOUNTY,
DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
PACKINGNOTE.SEQUENCENUMBER,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, --CAST(
PACKINGNOTE.REMARK --AS VARCHAR2(60) ) REMARK
, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL, --ORDER 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
cast (SS.VALUE as varchar2(60)) WEIGHTUNIT,
cast (SS1.VALUE as varchar2(1)) PRINTDELNOTEPERCONTAINER,
cast (SS2.VALUE as varchar2(1)) CONTAINERRECORDINGACTIVE,
cast (SS3.VALUE as varchar2(1)) PRINTDELNOTEZEROLINES,
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(60)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
      ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
coalesce((SELECT min(PNC.PACKINGNOTE_ID) FROM PACKINGNOTECONTAINER PNC
   LEFT OUTER JOIN CONTAINER C ON C.CONTAINER_ID = PNC.CONTAINER_ID
   LEFT OUTER JOIN CONTAINERTYPE CT ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   LEFT OUTER JOIN WEIGHINGCATEGORY W ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID),0) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC
, coalesce((select max(ds.packingnote_id)
                 from   deliveryscan ds
                 where  ds.packingnote_id = packingnote.packingnote_id),
                 (select max(o.packingnote_id)
                   from   outofcirculationhistory o
                   where  o.packingnote_id = packingnote.packingnote_id), 0) numberofpossiblelineswithscans
, PACKINGNOTE.YEAR YEAR, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE, INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.REFERENCENUMBER, INVOICEBU.INTERNALVATNUMBER, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE, ROUTE.PUTUPREPORTPERCUSTOMER
, customer.signaturerequired, dsig.personidentification personidentification, dsig.signature signature
, (select rc.drivingdate from routecontrol rc where rc.routecontrol_id = stop.routecontrol_id) signaturedate
, to_char(stop.departuretime,'fmhhfm:MI:AM') signaturetime
, to_char(stop.departuretime,'fmhh24fm:MI') signaturetime24
, packingnote.distributionpoint_id
, packingnote.processbusinessunit_id
, DELIVERYPOINT. SIGNATUREBARCODE
, cast ((SELECT SS.VALUE FROM SYSTEMSETTING SS WHERE SS.PLANT_ID=PLANT.PLANT_ID AND SS.NAME ='CONTAINERTYPEUNQBRCLABEL')  as varchar2(60)) containertypedescription
, (select max(wo.referencenumber) from deliveryscan ds, issuehistory ih, workorder wo
where ds.uniqueitem_link_id = ih.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 ih.workorder_id = wo.workorder_id
and ds.packingnote_id = packingnote.packingnote_id
and wo.deliverfrom = 2
) worefnumber, packingnote.pnremark,
(select dnrd.description from deliverynoteremark_desc dnrd where dnrd.deliverynoteremark_id = packingnote.deliverynoteremark_id
        and dnrd.language_id = customer.language_id) deliverynoteremarkdesc
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,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        PACKINGNOTE
          LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
          LEFT OUTER JOIN ROUTE ON (PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID)
          LEFT OUTER JOIN STOP ON (PACKINGNOTE.STOP_ID = STOP.STOP_ID)
          left outer join deliverysignature dsig on (dsig.stop_id = packingnote.stop_id and dsig.stop_id=packingnote.deliverysignature_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 STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20 or (packingnote.origin = 14 and status.code = 40))
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  and FORMLAYOUT.Code = 'DNM'--only for this code print the note again

/
create or replace view V_DELIVERYNOTE_SMG
 (NOTENUMBER, WOREFERENCENUMBER, CUSTOMERNUMBER, CUSTNR, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO
, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, ROUTENUMBER, ROUTEDESCRIPTION, STOPNUMBER, PACKINGNOTE_ID, ENDDATEFORUSE, ORIGIN, DELIVERYLAYOUTCODE, DAYDESCRIPTION, DAYNUMBER, WEEK, LANGUAGECODE, CUSTOMERLANGUAGECODE, SCANSONDELIVERYNOTE, HASLOCKERANAGEMENT, CHARGESERVICE, CHARGERENT, USELOCKEROBLIGATED, FIXEDNUMBERBANK, NUMBEROFGARMENTSINLOCKER, NUMBEROFLOCKERS, NOOFCONTAINERS, PLANT_DEP_CODE
, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, YEAR, PRICESCALCULATED, TOTALAMOUNT, TOTALAMOUNTEXCLUDINGVAT, WEIGHINGTICKET_ID, DECIMALS, INVOICEAMOUNTDECIMALS, CURRENCYCODE, REFERENCENUMBER, SEARCHNAME, PROCESSBUCODE, PUTUPREPORTPERCUSTOMER, SIGNATUREREQUIRED, DISTRIBUTIONPOINT_ID, MAXCOMPLETENESSDAYS, PROCESSBUSINESSUNIT_ID, CONTRPONR, PERSONIDENTIFICATION, SIGNATURE, HASSIGNATURE, STOP_ID, SIGNATUREDATE, SIGNATURETIME
, SIGNATURETIME24, BARCODE, BARCODEDATE, BARCODETIME24, CORRECTEDNOTENUMBER, CORRECTIONDATE, CORRECTDNORIGIN, DRIVERNAME, RESIDENTIALCORRECTION, INTERNALBU_CODE, COSTCENTERCODE, COSTCENTERDESCRIPTION, PONUMBER, SUPPRESSCOLDELNOTELINEN, STATUSCODE, SALESNOTENO, CUSTOMER_ID, LEGALENTITY_ID, LEGALENTITY_LEGALNAME, LEGALENTITY_STREET, LEGALENTITY_ZIP, LEGALENTITY_CITY, COMPANYSTAMPS_DELNOTE, PLANTNAME_PART2)
as SELECT
PACKINGNOTE.NOTENUMBER, (SELECT WO.REFERENCENUMBER FROM WORKORDER WO WHERE WO.WORKORDER_ID=PACKINGNOTE.SALESNOTE_ID AND PACKINGNOTE.ORIGIN=11) WOREFERENCENUMBER, CUSTOMER.CUSTOMERNUMBER,insertspace_after_x_characters(to_char(CUSTOMER.CUSTOMERNUMBER),3) custnr, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME,
ADDRESS.STREET CUSTOMERSTREET, ADDRESS.ZIPCODE CUSTOMERZIP, ADDRESS.CITY CUSTOMERCITY, C1.DESCRIPTION CUSTCOUNTRY_DESC,
DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
 EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PL.CODE PLANTCODE, PL.NAME PLANTNAME, PL.WEBSITE PLANTWEBSITE, PL.EMAIL PLANTEMAIL, --ORDER 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PL.PHONENO PLANTPHONENO, PL.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
lpad(SS.VALUE, 3) WEIGHTUNIT, lpad(SS1.VALUE, 1) PRINTDELNOTEPERCONTAINER
, lpad(SS2.VALUE, 1) CONTAINERRECORDINGACTIVE
, ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION ROUTEDESCRIPTION,
PACKINGNOTE.STOPNUMBER,
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 = GETABSDAYNUMBER(PACKINGNOTE.Deliverydate)) DAYDESCRIPTION
, PACKINGNOTE.DAYNUMBER
, CAST(PACKINGNOTE.WEEK AS VARCHAR2(255)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
      ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
 coalesce((SELECT sum(1) FROM PACKINGNOTECONTAINER PNC
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID),0) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC
, PACKINGNOTE.YEAR YEAR
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE
, PACKINGNOTE.REFERENCENUMBER
, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE
, ROUTE.PUTUPREPORTPERCUSTOMER
, customer.signaturerequired
, packingnote.distributionpoint_id
, CASTVARCHARASNUMBER(SS4.VALUE) MAXCOMPLETENESSDAYS
, packingnote.processbusinessunit_id,
(select ca.purchaseorder from contractspercustomer ca where ca.contractspercustomer_id=(select  min(cc.contractspercustomer_id)
 from contractspercustomer cc  where cc.customer_id=CUSTOMER.customer_id
  and cc.dateactive<=PACKINGNOTE.DELIVERYDATE
 and cc.dateinactive>=PACKINGNOTE.DELIVERYDATE)) ContrPONR
, dsig.personidentification personidentification
, dsig.signature signature,
(case when length(dsig.signature) > 0 then 1
  else 0 end) hassignature,
 dsig.stop_id,
 --(select rc.drivingdate from routecontrol rc where rc.routecontrol_id = stop.routecontrol_id)
  (case when (dsig.scantimestamp is not null and  year(dsig.scantimestamp)<>1970) then  dsig.scantimestamp
      when (dsig.timestamp is not null and  year(dsig.timestamp)<>1970) then  dsig.timestamp
      else stop.departuretime end)signaturedate,
(case when (dsig.scantimestamp is not null and  year(dsig.scantimestamp)<>1970) then  to_char(dsig.scantimestamp,'fmhhfm.MI.AM' )
      when (dsig.timestamp is not null and  year(dsig.timestamp)<>1970) then  to_char(dsig.timestamp,'fmhhfm.MI.AM' )
      else to_char(stop.departuretime,'fmhhfm.MI.AM') end)signaturetime,
(case when (dsig.scantimestamp is not null and  year(dsig.scantimestamp)<>1970) then  to_char(dsig.scantimestamp,'fmhh24fm.MI' )
      when (dsig.timestamp is not null and  year(dsig.timestamp)<>1970) then  to_char(dsig.timestamp,'fmhh24fm.MI' )
      else to_char(stop.departuretime,'fmhh24fm.MI') end)signaturetime24,
 dsig.barcode
, dsig.scantimestamp Barcodedate
, to_char(dsig.scantimestamp,'fmhh24fm.MI') Barcodetime24
,PACKINGNOTE.CORRECTEDNOTENUMBER,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
  (SELECT a.origin FROM PACKINGNOTE a WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = a.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTDNORIGIN,
 ( select --+ INDEX(rc XPKROUTECONTROL)
 empl.name from routecontrol rc, employee empl where rc.routecontrol_id = stop.routecontrol_id
 and empl.employeenumber = rc.drivernumber and empl.plant_id = pl.plant_id) drivername,
 ( case when  PACKINGNOTE.Origin <> 13 then 0 else
  (select coalesce((min(cdn.clientdeliverynote_id)),0) from clientdeliverynote cdn
        where cdn.packingnote_id=PACKINGNOTE.PACKINGNOTE_ID
        and cdn.correctionclientdelnote_id is not null) END) Residentialcorrection
, (select ibu.code from businessunit ibu where ibu.businessunit_id = PACKINGNOTE.Internalprocessingbu_Id) InternalBU_code
, COC.CODE COSTCENTERCODE, COC.Description COSTCENTERDESCRIPTION, coc.ponumber, CUSTOMER.Suppresscoldelnotelinen
, STATUS.Code Statuscode
, (select sn.workordernumber from workorder sn where sn.workorder_id = packingnote.salesnote_id) SalesNoteNo
, CUSTOMER.Customer_Id, INVBU.Legalentity_Id, le.legalname LegalEntity_LegalName
, leadd.street LegalEntity_Street, leadd.zipcode LegalEntity_Zip, leadd.city LegalEntity_City
, (select im3.image from image im3 where im3.image_id = le.csdeliverynoteimage_id) CompanyStamps_DelNote
, case when pl.CODE = 'ARNO' then substr(pl.NAME, 25)
       when PL.CODE = 'CHEM' then substr(PL.NAME, 35)
       when PL.CODE = 'GRAZ' then substr(PL.NAME, 25)
       when PL.CODE = 'INZ' then substr(PL.NAME, 25)
       when PL.CODE = 'KRAM' then PROCESSBU.Description--substr(PL.NAME, 25)
       when PL.CODE = 'LEOG' then substr(PL.NAME, 25)
       when PL.CODE = 'MATT' then substr(PL.NAME, 25)
       when PL.CODE = 'ORAD' then substr(PL.NAME, 27)
       when PL.CODE = 'PWSK' then substr(PL.NAME, 25)
       when PL.CODE = 'ROGA' then substr(PL.NAME, 36)
       when PL.CODE = 'SA14' then PROCESSBU.Description--substr(PL.NAME, 25)
       when PL.CODE = 'SA22' then substr(PL.NAME, 25)
       when PL.CODE = 'SAWR' then substr(PL.NAME, 25)
       when PL.CODE = 'SCHI' then substr(PL.NAME, 25)
       when PL.CODE = 'SMA' then substr(PL.NAME, 25)
       when PL.CODE = 'SMB' then substr(PL.NAME, 20)
       when PL.CODE = 'SMHR' then substr(PL.NAME, 33)
       when PL.CODE = 'SMP' then substr(PL.NAME, 35)
       when PL.CODE = 'SMPL' then substr(PL.NAME, 31)
       when PL.CODE = 'SMRO' then substr(PL.NAME, 27)
       when PL.CODE = 'SMRS' then substr(PL.NAME, 31)
       when PL.CODE = 'SMS' then substr(PL.NAME, 25)
       when PL.CODE = 'SMSK' then substr(PL.NAME, 29)
       when PL.CODE = 'SMSL' then substr(PL.NAME, 36)
       when PL.CODE = 'SMTY' then substr(PL.NAME, 31)
       when PL.CODE = 'SMZL' then substr(PL.NAME, 25)
       when PL.CODE = 'SZOM' then substr(PL.NAME, 20)
else PL.NAME end PLANTNAME_PART2
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 PL, ADDRESS PLANTADDRESS,
        BUSINESSUNIT PROCESSBU ,
        BUSINESSUNIT INVBU
         left outer join legalentity le
              inner join address leadd on leadd.address_id = le.address_id
         on le.legalentity_id = INVBU.legalentity_id,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS4,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        PACKINGNOTE
          LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
          LEFT OUTER JOIN ROUTE ON (PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID)
          LEFT OUTER JOIN STOP ON (PACKINGNOTE.STOP_ID = STOP.STOP_ID)
          left outer join deliverysignature dsig on (dsig.stop_id = packingnote.stop_id and dsig.stop_id=packingnote.deliverysignature_id),
        LANGUAGES CUSTOMERLANGUAGE, LANGUAGES, COSTCENTER COC
  WHERE PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
  AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
  AND DISTRIBUTIONPOINT.COSTCENTER_ID = COC.COSTCENTER_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 STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20 or (packingnote.origin = 14 and status.code = 40))
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PL.PLANT_ID
  AND PL.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PL.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PL.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PL.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS4.PLANT_ID = PL.PLANT_ID
  AND SS4.NAME = 'MAXCOMPLETENESSDAYS'
  AND CUSTOMER.COUNTRY_ID = C1.COUNTRY_ID
  AND PL.COUNTRY_ID = C2.COUNTRY_ID
  AND CUSTOMER.LANGUAGE_ID = CUSTOMERLANGUAGE.LANGUAGE_ID
  AND PACKINGNOTE.PLANTDEPARTMENT_ID = PLANTDEPARTMENT.PLANTDEPARTMENT_ID
  AND CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID

/
create or replace view V_DELIVERYNOTE_STK
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, CUSTCOUNTRY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION, PLANTSTREET, PLANTZIPCODE, PLANTCITY
, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, 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, NOOFCONTAINERS, SUM_DELIVERED_QTY, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, DELNOTETOEMAIL)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(select cn.deliverydate from PACKINGNOTE cn where PACKINGNOTE.CORRECTEDNOTENUMBER = cn.notenumber
  and PACKINGNOTE.CORRECTEDNOTENUMBER<>0) correctiondate,
PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME,
ADDRESS.street CUSTOMERSTREET, ADDRESS.zipcode CUSTOMERZIP, ADDRESS.city CUSTOMERCITY,
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,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
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,
 SS.VALUE WEIGHTUNIT, SS1.VALUE PRINTDELNOTEPERCONTAINER, SS2.VALUE CONTAINERRECORDINGACTIVE,
  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(255)) 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,
(select count(*) from PACKINGNOTECONTAINER pnc
   left outer join CONTAINER C on C.CONTAINER_ID = PNC.CONTAINER_ID
   left outer join CONTAINERTYPE CT on CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   left outer join WEIGHINGCATEGORY W on W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 where pnc.packingnote_id = PACKINGNOTE.Packingnote_Id) noOfContainers
 , (select sum(l.deliveredamount)
           from packingnoteline l
           where l.packingnote_id = PACKINGNOTE.packingnote_id) SUM_DELIVERED_QTY
 , plantdepartment.code plant_dep_code, plantdepartment.description plant_dep_desc
 , packingnote.freeofchargereason_id
 , (select r.code from reasoncode r
        where r.reasoncode_id = packingnote.freeofchargereason_id) free_reason_code
 , (select rd.description from reasoncode_desc rd
        where rd.reasoncode_id = packingnote.freeofchargereason_id
        and rd.language_id = languages.language_id) free_reason_code_desc
 , (select count(*) from packingnoteline lines
        where lines.packingnote_id = packingnote.packingnote_id
              and lines.origin in (2,4)) numberOfPossibleLinesWithScans
              , department.delnotetoemail
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, SYSTEMSETTING SS, SYSTEMSETTING SS1, SYSTEMSETTING SS2,
        STATUS, COUNTRY C1, COUNTRY C2, plantdepartment,
        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 STATUS.statustype = 'PN' AND (STATUS.code = 30 OR STATUS.code = 20 or (packingnote.origin = 14 and status.code = 40))
	AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.address_id = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  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

/
create or replace view V_DELIVERYNOTE_STX
 (NOTENUMBER, DELIVERYDATE, NUMBEROFCOLLI, BATCHNUMBER, DEPARTMENTNUMBER, DEPARTMENT_DESC, CUSTOMERNAME, PRODUCTCODE, PRODUCT_DESC, PRODUCTGGROUPCODE, CUSTOMERLANGUAGECODE, PG_DESC, SIZECODE, SIZE_DESC, FMCODE, DELIVEREDAMOUNT, PACKINGSEQUENCE, CREATIONDATE)
as select pn.notenumber,
       pn.deliverydate,
       pn.numberofcolli,
       (select max(ui.batchnumber)
          from uniqueitem ui
          join deliveryscan ds
            on ui.uniqueitem_id = ds.uniqueitem_link_id
         where ds.packingnote_id = pn.packingnote_id
         and ui.lastoutscandate<=pn.deliverydate
         ) batchnumber,
       dep.departmentnumber,
       dep.description department_desc,
       c.name customername,
       p.code productcode,
       pnl.customdescription product_desc,
       pg.code productggroupcode,
       languages.code customerlanguagecode,
       (select pgd.description
          from productgroup_desc pgd
         where pgd.productgroup_id = pg.productgroup_id
           and pgd.language_id = languages.language_id) pg_desc,
       sz.code sizecode,
       (select sdd.description
          from sizedefinition_desc sdd
         where sdd.sizedefinition_id = sz.sizedefinition_id
           and sdd.language_id = languages.language_id) size_desc,
       fm.code fmcode,
       pnl.deliveredamount,
       pnl.packingsequence,
       trunc(pn.creationtimestamp) creationdate
  from packingnote pn
 inner join packingnoteline pnl
    on pn.packingnote_id = pnl.packingnote_id
 inner join distributionpoint dp
    on pn.distributionpoint_id = dp.distributionpoint_id
 inner join department dep
    on dp.department_id = dep.department_id
 inner join customer c
    on dep.customer_id = c.customer_id
 inner join languages
    on c.language_id = languages.language_id
 inner join product p
    on pnl.product_id = p.product_id
 inner join productgroup pg
    on pg.productgroup_id = p.productgroup_id
 inner join sizedefinition sz
    on pnl.sizedefinition_id = sz.sizedefinition_id
 inner join finishingmethod fm
    on pnl.finishingmethod_id = fm.finishingmethod_id
 group by pn.notenumber,
          pn.deliverydate,
          pn.numberofcolli,
          dep.departmentnumber,
          dep.description,
          c.name,
          p.code,
          pg.code,
          languages.code,
          sz.code,
           fm.code ,
       pnl.deliveredamount,
       pnl.packingsequence,
       pn.creationtimestamp,
       pn.packingnote_id, p.product_id, languages.language_id,pg.productgroup_id,  sz.sizedefinition_id,  pnl.customdescription

/
create or replace view V_DELIVERYNOTE_TEK
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION, PLANTCODE, PLANTNAME
, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, YEAR, PRICESCALCULATED, TOTALAMOUNT, TOTALAMOUNTEXCLUDINGVAT, WEIGHINGTICKET_ID, DECIMALS, INVOICEAMOUNTDECIMALS, CURRENCYCODE, VATNUMBER, REFERENCENUMBER, INTERNALVATNUMBER
, SEARCHNAME, PROCESSBUCODE, PUTUPREPORTPERCUSTOMER, CUSTOMERSTREET2, PURCHASEORDER)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
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,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL,
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
SS.VALUE WEIGHTUNIT, SS1.VALUE PRINTDELNOTEPERCONTAINER
, SS2.VALUE CONTAINERRECORDINGACTIVE, SS3.VALUE PRINTDELNOTEZEROLINES
, 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(10)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
	    ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
(SELECT COUNT(*) FROM PACKINGNOTECONTAINER PNC
   LEFT OUTER JOIN CONTAINER C ON C.CONTAINER_ID = PNC.CONTAINER_ID
   LEFT OUTER JOIN CONTAINERTYPE CT ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   LEFT OUTER JOIN WEIGHINGCATEGORY W ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC,
(SELECT COUNT(*) FROM PACKINGNOTELINE LINES
        WHERE LINES.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID
              AND LINES.ORIGIN IN (2,4)) NUMBEROFPOSSIBLELINESWITHSCANS
, PACKINGNOTE.YEAR YEAR
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.REFERENCENUMBER
, INVOICEBU.INTERNALVATNUMBER
, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE
, ROUTE.PUTUPREPORTPERCUSTOMER
, ADDRESS.STREET2 CUSTOMERSTREET2
, (select max(cpc.purchaseorder) from contractspercustomer cpc where customer.customer_id = cpc.customer_id
and cpc.dateactive in (select max(cpc2.dateactive) from contractspercustomer cpc2 where customer.customer_id = cpc2.customer_id
                   and cpc2.dateactive <= PACKINGNOTE.Deliverydate)) PurchaseOrder
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,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        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 STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20 or (packingnote.origin = 14 and status.code = 40))
	AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID

/
create or replace view V_DELIVERYNOTE_TVN
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERSTREET2, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, LEGACYDEPARTMENTCODE, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, ORIGINALDELIVERYDATE, REMARK, PROCESSBUDESCRIPTION
, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, YEAR, PRICESCALCULATED, TOTALAMOUNT, TOTALAMOUNTEXCLUDINGVAT, WEIGHINGTICKET_ID, DECIMALS, INVOICEAMOUNTDECIMALS, CURRENCYCODE, VATNUMBER, REFERENCENUMBER
, INTERNALVATNUMBER, PLANTINVOICEREMARK, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(select cn.deliverydate from PACKINGNOTE cn where PACKINGNOTE.CORRECTEDNOTENUMBER = cn.notenumber
  and PACKINGNOTE.CORRECTEDNOTENUMBER<>0) correctiondate,
PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME,
ADDRESS.street CUSTOMERSTREET, ADDRESS.street2 CUSTOMERSTREET2, ADDRESS.zipcode CUSTOMERZIP, ADDRESS.city CUSTOMERCITY, ADDRESS.State CUSTOMERSTATE,
C1.CODE CUSTCOUNTRY, C1.DESCRIPTION CUSTCOUNTRY_DESC,
DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION, DEPARTMENT.Legacydepartmentcode,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
PACKINGNOTE.SEQUENCENUMBER,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.ORIGINALDELIVERYDATE, PACKINGNOTE.REMARK, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.Name PLANTName, PLANT.WEBSITE PLANTWEBSITE, PLANT.Email PLANTEmail, --order 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.phoneno PLANTPHONENO, PLANT.faxno PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
SS.VALUE WEIGHTUNIT, SS1.VALUE PRINTDELNOTEPERCONTAINER
, SS2.VALUE CONTAINERRECORDINGACTIVE, SS3.VALUE PRINTDELNOTEZEROLINES
, 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(255)) WEEK
,languages.code languagecode, customerlanguage.code customerlanguagecode, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN clm.customer_id = null
      THEN 'N'
	    ELSE 'Y'
END)  hasLockeranagement,
clm.chargeservice, clm.chargerent, clm.uselockerobligated, clm.fixednumberbank,
packingnote.numberofgarmentsinlocker, packingnote.numberoflockers,
(select count(*) from PACKINGNOTECONTAINER pnc
   left outer join CONTAINER C on C.CONTAINER_ID = PNC.CONTAINER_ID
   left outer join CONTAINERTYPE CT on CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   left outer join WEIGHINGCATEGORY W on W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 where pnc.packingnote_id = PACKINGNOTE.Packingnote_Id) noOfContainers,
plantdepartment.code plant_dep_code, plantdepartment.description plant_dep_desc,
packingnote.freeofchargereason_id,
(select r.code from reasoncode r
        where r.reasoncode_id = packingnote.freeofchargereason_id) free_reason_code,
(select rd.description from reasoncode_desc rd
        where rd.reasoncode_id = packingnote.freeofchargereason_id
        and rd.language_id = languages.language_id) free_reason_code_desc,
(select count(*) from packingnoteline lines
        where lines.packingnote_id = packingnote.packingnote_id
              and lines.origin in (2,4)) numberOfPossibleLinesWithScans
, PACKINGNOTE.Year year
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, cu.decimals, cu.invoiceamountdecimals, cu.code CurrencyCode,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.Referencenumber
/*, 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*/
, INVOICEBU.Internalvatnumber
, CAST((SELECT pldesc.invoiceremark FROM plantinvoiceremark_desc pldesc
          where pldesc.plant_id = plant.plant_id and pldesc.language_id = LANGUAGES.LANGUAGE_ID) AS VARCHAR2(254)) plantinvoiceremark
, plant.invoiceremarkstartdate, plant.invoiceremarkenddate
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
/*        left outer join customerbillinginfo cbi
             LEFT OUTER JOIN bankinstitution Lbank
             ON cbi.laundrybankinstitution_id = Lbank.bankinstitution_id
        on CUSTOMER.Debtor_Id = cbi.customer_id*/,
        ADDRESS, DEPARTMENT, DISTRIBUTIONPOINT, PLANT, ADDRESS PLANTADDRESS,
        BUSINESSUNIT PROCESSBU,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, plantdepartment, currency cu,
        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 STATUS.statustype = 'PN' AND (STATUS.code = 30 OR STATUS.code = 20 or (packingnote.origin = 14 and status.code = 40))
	AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.address_id = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 cu.currency_id = customer.currency_id
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
-- DeliveryNote.TVN.rpt, DeliveryNote.MID.rpt

/
create or replace view V_DELIVERYNOTE_VOS
 (CORRECTEDNOTENUMBER, CORRECTIONDATE, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, CUSTOMERSTREET, CUSTOMERSTREET2, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTCOUNTRY, CUSTCOUNTRY_DESC, CUSTOMERCOUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENAME, DELIVERYDATE, PROCESSEDTIMESTAMP, ORIGINALDELIVERYDATE
, REMARK, PROCESSBUDESCRIPTION, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, WEIGHTUNIT, PRINTDELNOTEPERCONTAINER, CONTAINERRECORDINGACTIVE, PRINTDELNOTEZEROLINES, 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, NOOFCONTAINERS, PLANT_DEP_CODE, PLANT_DEP_DESC, FREEOFCHARGEREASON_ID, FREE_REASON_CODE, FREE_REASON_CODE_DESC, NUMBEROFPOSSIBLELINESWITHSCANS, 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, WOREFNUMBER)
as SELECT
PACKINGNOTE.CORRECTEDNOTENUMBER,
(SELECT CN.DELIVERYDATE FROM PACKINGNOTE CN WHERE PACKINGNOTE.CORRECTEDNOTENUMBER = CN.NOTENUMBER
  AND PACKINGNOTE.CORRECTEDNOTENUMBER<>0) CORRECTIONDATE,
PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME,
CUSTOMER.LEGALNAME,
ADDRESS.STREET CUSTOMERSTREET, ADDRESS.STREET2 CUSTOMERSTREET2,  ADDRESS.ZIPCODE CUSTOMERZIP, ADDRESS.CITY CUSTOMERCITY, ADDRESS.STATE CUSTOMERSTATE,
C1.CODE CUSTCOUNTRY, C1.DESCRIPTION CUSTCOUNTRY_DESC, ADDRESS.COUNTY CUSTOMERCOUNTY,
DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
PACKINGNOTE.SEQUENCENUMBER,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A
        WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
              AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
PACKINGNOTE.OCCUPANCY, EMPLOYEE.NAME EMPLOYEENAME, PACKINGNOTE.DELIVERYDATE, PACKINGNOTE.PROCESSEDTIMESTAMP,
PACKINGNOTE.ORIGINALDELIVERYDATE,
PACKINGNOTE.REMARK
, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL, --ORDER 501604
PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
cast (SS.VALUE as varchar2(60)) WEIGHTUNIT,
cast (SS1.VALUE as varchar2(1)) PRINTDELNOTEPERCONTAINER,
cast (SS2.VALUE as varchar2(1)) CONTAINERRECORDINGACTIVE,
cast (SS3.VALUE as varchar2(1)) PRINTDELNOTEZEROLINES,
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(60)) WEEK
,LANGUAGES.CODE LANGUAGECODE, CUSTOMERLANGUAGE.CODE CUSTOMERLANGUAGECODE, PACKINGNOTE.PRODUCTIONDATE PRODUCTIONDATE,
CUSTOMER.SCANSONDELIVERYNOTE,
(CASE WHEN CLM.CUSTOMER_ID = NULL
      THEN 'N'
      ELSE 'Y'
END)  HASLOCKERANAGEMENT,
CLM.CHARGESERVICE, CLM.CHARGERENT, CLM.USELOCKEROBLIGATED, CLM.FIXEDNUMBERBANK,
PACKINGNOTE.NUMBEROFGARMENTSINLOCKER, PACKINGNOTE.NUMBEROFLOCKERS,
coalesce((SELECT min(PNC.PACKINGNOTE_ID) FROM PACKINGNOTECONTAINER PNC
   LEFT OUTER JOIN CONTAINER C ON C.CONTAINER_ID = PNC.CONTAINER_ID
   LEFT OUTER JOIN CONTAINERTYPE CT ON CT.CONTAINERTYPE_ID = PNC.CONTAINERTYPE_ID
   LEFT OUTER JOIN WEIGHINGCATEGORY W ON W.WEIGHINGCATEGORY_ID = PNC.WEIGHINGCATEGORY_ID
 WHERE PNC.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID),0) NOOFCONTAINERS,
PLANTDEPARTMENT.CODE PLANT_DEP_CODE, PLANTDEPARTMENT.DESCRIPTION PLANT_DEP_DESC,
PACKINGNOTE.FREEOFCHARGEREASON_ID,
(SELECT R.CODE FROM REASONCODE R
        WHERE R.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID) FREE_REASON_CODE,
(SELECT RD.DESCRIPTION FROM REASONCODE_DESC RD
        WHERE RD.REASONCODE_ID = PACKINGNOTE.FREEOFCHARGEREASON_ID
        AND RD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FREE_REASON_CODE_DESC
, coalesce((select max(ds.packingnote_id)
                 from   deliveryscan ds
                 where  ds.packingnote_id = packingnote.packingnote_id),
                 (select max(o.packingnote_id)
                   from   outofcirculationhistory o
                   where  o.packingnote_id = packingnote.packingnote_id), 0) numberofpossiblelineswithscans
, PACKINGNOTE.YEAR YEAR
, PACKINGNOTE.PRICESCALCULATED, PACKINGNOTE.TOTALAMOUNT, PACKINGNOTE.TOTALAMOUNTEXCLUDINGVAT
, PACKINGNOTE.WEIGHINGTICKET_ID, CU.DECIMALS, CU.INVOICEAMOUNTDECIMALS, CU.CODE CURRENCYCODE,
INVOICEBU.VATNUMBER VATNUMBER
, PACKINGNOTE.REFERENCENUMBER
, INVOICEBU.INTERNALVATNUMBER
, CUSTOMER.SEARCHNAME, PROCESSBU.CODE PROCESSBUCODE
, ROUTE.PUTUPREPORTPERCUSTOMER
, customer.signaturerequired
, dsig.personidentification personidentification
, dsig.signature signature
, (select rc.drivingdate from routecontrol rc where rc.routecontrol_id = stop.routecontrol_id) signaturedate
, to_char(stop.departuretime,'fmhhfm:MI:AM') signaturetime
, to_char(stop.departuretime,'fmhh24fm:MI') signaturetime24
, packingnote.distributionpoint_id
, packingnote.processbusinessunit_id
, (case when packingnote.origin = 4 then
(select max(wo.referencenumber) from deliveryscan ds, issuehistory ih, workorder wo
where ds.uniqueitem_link_id = ih.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 ih.workorder_id = wo.workorder_id
and ds.packingnote_id = packingnote.packingnote_id)
else ''
end) worefnumber
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,
        BUSINESSUNIT INVOICEBU,
        DELIVERYPOINT, SYSTEMSETTING SS, SYSTEMSETTING SS1,
        SYSTEMSETTING SS2, SYSTEMSETTING SS3,
        STATUS, COUNTRY C1, COUNTRY C2, PLANTDEPARTMENT, CURRENCY CU,
        PACKINGNOTE
          LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
          LEFT OUTER JOIN ROUTE ON (PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID)
          LEFT OUTER JOIN STOP ON (PACKINGNOTE.STOP_ID = STOP.STOP_ID)
          left outer join deliverysignature dsig on dsig.stop_id = packingnote.stop_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 STATUS.STATUSTYPE = 'PN' AND (STATUS.CODE = 30 OR STATUS.CODE = 20)
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
  AND SS.PLANT_ID = PLANT.PLANT_ID
  AND SS.NAME = 'WEIGHTUNIT'
  AND SS1.PLANT_ID = PLANT.PLANT_ID
  AND SS1.NAME = 'PRINTDELNOTEPERCONTAINER'
  AND SS2.PLANT_ID = PLANT.PLANT_ID
  AND SS2.NAME = 'CONTAINERRECORDINGACTIVE'
  AND SS3.PLANT_ID = PLANT.PLANT_ID
  AND SS3.NAME = 'PRINTDELNOTEZEROLINES'
  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 CU.CURRENCY_ID = CUSTOMER.CURRENCY_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID

/
create or replace view V_DELIVERYNOTE_WEARERS_ELI
 (PACKINGNOTENUMBER, PRODUCTCODE, PRODUCTDESCRIPTION, PARENT_CODE, PARENT_DESC, PRODUCTGROUPDESCRIPTION, PGCUSTOMDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, CODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, PACKINGSEQUENCE, STANDARDAMOUNT, VARIATIONAMOUNT, DELIVEREDAMOUNT, TOBEDELIVEREDAMOUNT, REMARKFORPACKINGINSTRUCTIONS, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE, TYPEOFMERCHANDISE, FREEOFCHARGEREASON, FREEOFCHARGEREASON_DESC, NOCHARGEFIRSTISSUE, NOCHARGEACTIVESEASON
, DELIVEREDCOGQTY, LINE_ORIGIN, PRICE, AMOUNT, TAXGROUPCODE, REGUNIT, OLD_QTY, PRICECOG, SEQUENCENUMBER, FINISHINGMETHODCODE, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, WEARERNUMBER, WEARERNAME, PRIMARYID, DELIVERYDATE, WEARERFUNCTION, COLOR)
as SELECT pn.NOTENUMBER PACKINGNOTENUMBER, PRODUCT.CODE PRODUCTCODE,
       (SELECT pde.DESCRIPTION
         FROM   PRODUCT_DESC Pde
         WHERE  Pde.PRODUCT_ID = pnl.PRODUCT_ID AND Pde.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
PRODUCTDESCRIPTION,
       (SELECT p.code
         FROM   PRODUCT  P
         WHERE  P.PRODUCT_ID = PRODUCT.Parentproduct_Id ) Parent_Code,
       (SELECT pd.DESCRIPTION
         FROM   PRODUCT_DESC PD
         WHERE  Pd.PRODUCT_ID = PRODUCT.Parentproduct_Id AND Pd.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
Parent_Desc,
       (SELECT DESCRIPTION
         FROM   PRODUCTGROUP_DESC A
         WHERE  A.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)
PRODUCTGROUPDESCRIPTION,
       (SELECT PGPC.CUSTOMDESCRITPION
         FROM   PRODUCTGROUPPERCUSTOMER PGPC, DISTRIBUTIONPOINT DP, DEPARTMENT DEP
         WHERE  PGPC.PRODUCTGROUP_ID = PRODUCT.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, SIZEDEFINITION.CODE,
       (SELECT DESCRIPTION
         FROM   SIZEDEFINITION_DESC S
         WHERE  S.SIZEDEFINITION_ID = pnl.SIZEDEFINITION_ID AND
                S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDESCRIPTION,
       (SELECT DESCRIPTION
         FROM   FINISHINGMETHOD_DESC F
         WHERE  F.FINISHINGMETHOD_ID = pnl.FINISHINGMETHOD_ID AND
                F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODDESCRIPTION,
       pnl.PACKINGSEQUENCE, pnl.STANDARDAMOUNT,
       pnl.VARIATIONAMOUNT, pnl.DELIVEREDAMOUNT,
       pnl.TOBEDELIVEREDAMOUNT, pnl.REMARKFORPACKINGINSTRUCTIONS,
       pnl.SYSTEMUSER_ID, pnl.TIMESTAMP, LANGUAGES.CODE languagecode,
       PRODUCT.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 = LANGUAGES.LANGUAGE_ID) FREEOFCHARGEREASON_DESC,
       pnl.NOCHARGEFIRSTISSUE, pnl.NOCHARGEACTIVESEASON,
       pnl.DELIVEREDCOGQTY, pnl.ORIGIN LINE_ORIGIN,
       (CASE WHEN pnl.PRICE IS NULL THEN 0 ELSE pnl.PRICE END) PRICE,
             pnl.AMOUNT, pnl.TAXGROUPCODE,
       (SELECT RG.CODE
         FROM   REGISTRATIONUNIT RG
         WHERE  RG.REGISTRATIONUNIT_ID = PRODUCT.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,
         coalesce(pnl.PRICECOG, 0) PRICECOG,
   (SELECT MAX(PSZ.SEQUENCENUMBER) FROM PRODUCTSIZE PSZ WHERE PSZ.PRODUCT_ID = PRODUCT.PRODUCT_ID AND PSZ.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID) SEQUENCENUMBER
  , (SELECT f.CODE FROM FINISHINGMETHOD F
         WHERE  F.FINISHINGMETHOD_ID = pnl.FINISHINGMETHOD_ID) FINISHINGMETHODCODE
, (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
, w.wearernumber, w.fullname wearername, ui.primaryid, pn.Deliverydate
, (select wf.description from wearerfunction wf where wf.wearerfunction_id = we.wearerfunction_id) wearerfunction
, (select cod.description from color_desc cod where cod.color_id = product.color_id and cod.language_id = languages.language_id) color
FROM   PACKINGNOTELINE pnl
       inner join PACKINGNOTE pn on pn.packingnote_id = pnl.packingnote_id
       left outer join deliveryscan ds
              inner join uniqueitem ui on ds.uniqueitem_link_id = ui.uniqueitem_id
              inner join weareremployment we
                   inner join wearer w on we.wearer_id = w.wearer_id
              on ds.weareremployment_link_id = we.weareremployment_id
       on ds.packingnote_id = pnl.packingnote_id and ds.product_link_id = pnl.Product_Id and ds.sizedefinition_link_id = pnl.Sizedefinition_Id
       , PRODUCT, SIZEDEFINITION, LANGUAGES
WHERE  --PACKINGNOTELINE.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID AND
       pnl.PRODUCT_ID = PRODUCT.PRODUCT_ID AND
       pnl.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_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, STD_AMOUNT, AMOUNTDELIVERED, CUSTOMERLANGUAGECODE, LANGUAGECODE, REPORTPARAM_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,
       sda.amount std_amount, 0 amountdelivered,
       ' ' customerlanguagecode, lan.code languagecode, rp.reportparam_id
from standarddelivery sd, standarddeliveryline sdl, standarddeliveryamount sda,
  productlistpercustomer plpc, productlistperdistribpoint plpd,
  customer cust, department d, distributionpoint dp,
  sizedefinition szd, finishingmethod fm, languages lan,
  product p, productgroup pg, reportparam rp
where sd.standarddelivery_id = sdl.standarddelivery_id
  and sdl.standarddeliveryline_id = sda.standarddeliveryline_id
  and sdl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
  and sdl.productlistpercustomer_id = plpc.productlistpercustomer_id
  and plpd.distributionpoint_id = dp.distributionpoint_id
  and dp.department_id = d.department_id
  and plpc.customer_id = cust.customer_id
  and plpc.product_id = p.product_id
  and plpc.sizedefinition_id = szd.sizedefinition_id
  and plpc.finishingmethod_id = fm.finishingmethod_id
  and p.productgroup_id = pg.productgroup_id
  and cust.CUSTOMERNUMBER >= rp.number_value3
  and cust.CUSTOMERNUMBER <= rp.number_value4
  and d.DEPARTMENTNUMBER >= rp.number_value5
  and d.DEPARTMENTNUMBER <= rp.number_value6
  and dp.DISTRIBUTIONPOINTNUMBER >= rp.number_value7
  and dp.DISTRIBUTIONPOINTNUMBER <= rp.number_value8
  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 fm.code >= rp.string_value5
  and fm.code <= rp.string_value6
  and lan.code = rp.string_value/*
  AND sdl.dateactive <= rp.date_value2--SSB 27.03.2012 Leave this filter commented because it creates timeout
  AND sdl.dateinactive > rp.date_value2*/
  and (cust.defaultbusinessunit_id = rp.number_value9 or
      exists (select 1 from customeractivities act where cust.customer_id = act.customer_id and act.processbusinessunit_id = rp.number_value9))
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,
       0 std_amount, dh.amountdelivered,
       ' ' customerlanguagecode, lan.code languagecode, rp.reportparam_id
from deliveryhistory dh,
  customer cust, department d, distributionpoint dp,
  sizedefinition szd, finishingmethod fm, languages lan,
  product p, productgroup pg, reportparam rp
where dh.distributionpoint_link_id = dp.distributionpoint_id
  and dp.department_id = d.department_id
  and d.customer_id = cust.customer_id
  and dh.customer_link_id = cust.customer_id
  and dh.product_link_id = p.product_id
  and dh.sizedefinition_link_id = szd.sizedefinition_id
  and dh.finishingmethod_id = fm.finishingmethod_id
  and p.productgroup_id = pg.productgroup_id
  and cust.CUSTOMERNUMBER >= rp.number_value3
  and cust.CUSTOMERNUMBER <= rp.number_value4
  and d.DEPARTMENTNUMBER >= rp.number_value5
  and d.DEPARTMENTNUMBER <= rp.number_value6
  and dp.DISTRIBUTIONPOINTNUMBER >= rp.number_value7
  and dp.DISTRIBUTIONPOINTNUMBER <= rp.number_value8
  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 fm.code >= rp.string_value5
  and fm.code <= rp.string_value6
  and lan.code = rp.string_value
  --and (dh.year*100 + dh.week) >= rp.number_value1
  --AND (dh.year*100 + dh.week) <= rp.number_value2
  and (dh.deliverydate) >= rp.date_value1
  and (dh.deliverydate) <= rp.date_value2
  and (cust.defaultbusinessunit_id = rp.number_value9 or
      exists (select 1 from customeractivities act where cust.customer_id = act.customer_id and act.processbusinessunit_id = rp.number_value9))

/
create or replace view V_DELIVERYPERDAY_ANG
 (LINETYPE, CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PRODUCTCODE, PACKINDICATION, PRODUCTDESCRIPTION, TYPEOFMERCHANDISE, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODCODE, FINISHINGMETHODDESCRIPTION, DATEACTIVE, DATEINACTIVE, YEARWEEK, DAYNUMBER, STD_AMOUNT, AMOUNTDELIVERED, CUSTOMERLANGUAGECODE, LANGUAGECODE, REPORTPARAM_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,
       sda.amount std_amount, 0 amountdelivered,
       ' ' customerlanguagecode, lan.code languagecode, rp.reportparam_id
from standarddelivery sd, standarddeliveryline sdl, standarddeliveryamount sda,
  productlistpercustomer plpc, productlistperdistribpoint plpd,
  customer cust, department d, distributionpoint dp,
  sizedefinition szd, finishingmethod fm, languages lan,
  product p, productgroup pg, reportparam rp
where sd.standarddelivery_id = sdl.standarddelivery_id
  and sdl.standarddeliveryline_id = sda.standarddeliveryline_id
  and sdl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
  and sdl.productlistpercustomer_id = plpc.productlistpercustomer_id
  and plpd.distributionpoint_id = dp.distributionpoint_id
  and dp.department_id = d.department_id
  and plpc.customer_id = cust.customer_id
  and plpc.product_id = p.product_id
  and plpc.sizedefinition_id = szd.sizedefinition_id
  and plpc.finishingmethod_id = fm.finishingmethod_id
  and p.productgroup_id = pg.productgroup_id
  and cust.CUSTOMERNUMBER >= rp.number_value3
  and cust.CUSTOMERNUMBER <= rp.number_value4
  and d.DEPARTMENTNUMBER >= rp.number_value5
  and d.DEPARTMENTNUMBER <= rp.number_value6
  and dp.DISTRIBUTIONPOINTNUMBER >= rp.number_value7
  and dp.DISTRIBUTIONPOINTNUMBER <= rp.number_value8
  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 fm.code >= rp.string_value5
  and fm.code <= rp.string_value6
  and lan.code = rp.string_value/*
  AND sdl.dateactive <= rp.date_value2--SSB 27.03.2012 Leave this filter commented because it creates timeout
  AND sdl.dateinactive > rp.date_value2*/
  and (cust.defaultbusinessunit_id = rp.number_value9 or
      exists (select 1 from customeractivities act where cust.customer_id = act.customer_id and act.processbusinessunit_id = rp.number_value9))
union all
select --+ INDEX (deliveryhistory XIESPEEDDELIVERYHISTORY)
       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,
       0 std_amount, dh.amountdelivered,
       ' ' customerlanguagecode, lan.code languagecode, rp.reportparam_id
from deliveryhistory dh,
  customer cust, department d, distributionpoint dp,
  sizedefinition szd, finishingmethod fm, languages lan,
  product p, productgroup pg, reportparam rp
where dh.distributionpoint_link_id = dp.distributionpoint_id
  and dp.department_id = d.department_id
  and d.customer_id = cust.customer_id
  and dh.department_link_id = d.department_id
  and dh.customer_link_id = cust.customer_id
  and dh.product_link_id = p.product_id
  and dh.sizedefinition_link_id = szd.sizedefinition_id
  and dh.finishingmethod_id = fm.finishingmethod_id
  and p.productgroup_id = pg.productgroup_id
  and cust.CUSTOMERNUMBER >= rp.number_value3
  and cust.CUSTOMERNUMBER <= rp.number_value4
  and d.DEPARTMENTNUMBER >= rp.number_value5
  and d.DEPARTMENTNUMBER <= rp.number_value6
  and dp.DISTRIBUTIONPOINTNUMBER >= rp.number_value7
  and dp.DISTRIBUTIONPOINTNUMBER <= rp.number_value8
  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 fm.code >= rp.string_value5
  and fm.code <= rp.string_value6
  and lan.code = rp.string_value
  and (dh.year*100 + dh.week) >= rp.number_value1
  AND (dh.year*100 + dh.week) <= rp.number_value2
  and (cust.defaultbusinessunit_id = rp.number_value9 or
      exists (select 1 from customeractivities act where cust.customer_id = act.customer_id and act.processbusinessunit_id = rp.number_value9))

/
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_DELIVERYPERDAY_DUK
 (LINETYPE, CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PRODUCTCODE, PACKINDICATION, PRODUCTDESCRIPTION, TYPEOFMERCHANDISE, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODCODE, FINISHINGMETHODDESCRIPTION, DATEACTIVE, DATEINACTIVE, YEARWEEK, DAYNUMBER, STD_AMOUNT, AMOUNTDELIVERED, CUSTOMERLANGUAGECODE, LANGUAGECODE, REPORTPARAM_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,
       sda.amount std_amount, 0 amountdelivered,
       ' ' customerlanguagecode, lan.code languagecode, rp.reportparam_id
from standarddelivery sd, standarddeliveryline sdl, standarddeliveryamount sda,
  productlistpercustomer plpc, productlistperdistribpoint plpd,
  customer cust, department d, distributionpoint dp,
  sizedefinition szd, finishingmethod fm, languages lan,
  product p, productgroup pg, reportparam rp
where sd.standarddelivery_id = sdl.standarddelivery_id
  and sdl.standarddeliveryline_id = sda.standarddeliveryline_id
  and sdl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
  and sdl.productlistpercustomer_id = plpc.productlistpercustomer_id
  and plpd.distributionpoint_id = dp.distributionpoint_id
  and dp.department_id = d.department_id
  and d.customer_id = cust.customer_id
  and plpc.customer_id = cust.customer_id
  and plpc.product_id = p.product_id
  and plpc.sizedefinition_id = szd.sizedefinition_id
  and plpc.finishingmethod_id = fm.finishingmethod_id
  and p.productgroup_id = pg.productgroup_id
/*  and cust.CUSTOMERNUMBER >= rp.number_value3
  and cust.CUSTOMERNUMBER <= rp.number_value4
  and d.DEPARTMENTNUMBER >= rp.number_value5
  and d.DEPARTMENTNUMBER <= rp.number_value6
  and dp.DISTRIBUTIONPOINTNUMBER >= rp.number_value7
  and dp.DISTRIBUTIONPOINTNUMBER <= rp.number_value8
  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 fm.code >= rp.string_value5
  and fm.code <= rp.string_value6
  and lan.code = rp.string_value*//*
  AND sdl.dateactive <= rp.date_value2--SSB 27.03.2012 Leave this filter commented because it creates timeout
  AND sdl.dateinactive > rp.date_value2*/
  and (cust.defaultbusinessunit_id = rp.number_value9 or
      exists (select 1 from customeractivities act where cust.customer_id = act.customer_id and act.processbusinessunit_id = rp.number_value9))
union all
select
       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,
       0 std_amount, dh.amountdelivered,
       ' ' customerlanguagecode, lan.code languagecode, rp.reportparam_id
from deliveryhistory dh,
  customer cust, department d, distributionpoint dp,
  sizedefinition szd, finishingmethod fm, languages lan,
  product p, productgroup pg, reportparam rp
where dh.distributionpoint_link_id = dp.distributionpoint_id
  and dp.department_id = d.department_id
  and d.customer_id = cust.customer_id
  and dh.customer_link_id = cust.customer_id
  and dh.product_link_id = p.product_id
  and dh.sizedefinition_link_id = szd.sizedefinition_id
  and dh.finishingmethod_id = fm.finishingmethod_id
  and p.productgroup_id = pg.productgroup_id
/*  and cust.CUSTOMERNUMBER >= rp.number_value3
  and cust.CUSTOMERNUMBER <= rp.number_value4
  and d.DEPARTMENTNUMBER >= rp.number_value5
  and d.DEPARTMENTNUMBER <= rp.number_value6
  and dp.DISTRIBUTIONPOINTNUMBER >= rp.number_value7
  and dp.DISTRIBUTIONPOINTNUMBER <= rp.number_value8
  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 fm.code >= rp.string_value5
  and fm.code <= rp.string_value6
  and lan.code = rp.string_value*/
  and (dh.year*100 + dh.week) >= rp.number_value1
  AND (dh.year*100 + dh.week) <= rp.number_value2
  and (cust.defaultbusinessunit_id = rp.number_value9 or
      exists (select 1 from customeractivities act where cust.customer_id = act.customer_id and act.processbusinessunit_id = rp.number_value9))

/
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 bu.code BU_CODE, bu.description BU_DESC,
       p.code product_code, p.legacyproductcode, s.code size_code, s.legacysizecode,
       ds.fromstock, ds.packingnote_id, ds.scantimestamp, ds.chargewashing,
       ri.primaryid, r.code 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
  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)
                  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
 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
UNION ALL
-- UNIQUE ITEMS
SELECT bu.code BU_CODE, bu.description BU_DESC,
       p.code product_code, p.legacyproductcode, s.code size_code, s.legacysizecode,
       ds.fromstock, ds.packingnote_id, ds.scantimestamp, ds.chargewashing,
       ui.primaryid, r.code 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
  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)
                  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
 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

/
create or replace view V_DELIVERYSCANORSNAF
 (PACKINGNOTE_ID, PRODUCT_CODE, PRODDESC, LONGPRODDESC, SIZE_CODE, SDESC, FMCODE, FMDESC, PRIMARYID, EXPIRATIONDATE, CHARGENUMBER, STERILE, LANGUAGECODE)
as SELECT  ds.packingnote_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) proddesc,
(select pd.longdescription from product_desc pd  where pd.product_id=p.product_id
       and pd.language_id=l.language_id) longproddesc,
s.code size_code,
(select sdesc.description from sizedefinition_desc sdesc where sdesc.sizedefinition_id=s.sizedefinition_id
        and sdesc.language_id=l.language_id) sdesc ,
fm.code fmcode,
(select fmdesc.description from finishingmethod_desc fmdesc where fmdesc.finishingmethod_id=fm.finishingmethod_id
        and fmdesc.language_id=l.language_id) fmdesc,
ui.primaryid primaryid,
ui.expirationdate expirationdate,
ui.batchnumber ChargeNumber,
case nvl((select uor.uniqueitem_id from uniqueorpacksterile uor where ui.uniqueitem_id=uor.uniqueitem_id), 0)
       when 0 then null
       else 1
       end sterile,
l.code languagecode
FROM deliveryscan ds,  uniqueitem ui,
product p, sizedefinition s, finishingmethod fm, languages l
WHERE ds.uniqueitem_link_id=ui.uniqueitem_id
and ui.product_id=p.product_id
and ui.sizedefinition_id=s.sizedefinition_id
and ui.finishingmethod_id=fm.finishingmethod_id
and p.packtype=2--ORSPRODUCTS

/
create or replace view V_DELIVERYSCAN_ALL_BNL
 (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, LANGUAGECODE, REFERENCENUMBER, OUTSCANNODELIVERY)
as SELECT --+index(ds XIF11DELIVERYSCAN) index(ri_link XSPEEDUNIQUEITEM_LINK)
       bu.code BU_CODE, bu.description BU_DESC,
       p.code product_code, p.legacyproductcode, 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, wo.referencenumber, ds.outscannodelivery
  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)
                  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 LEFT OUTER JOIN (uniqueitemfixedinfo uifi LEFT OUTER JOIN workorder wo on wo.workorder_id = uifi.issuedbyworkorder_id) on uifi.uniqueitem_id = ri_link.uniqueitem_id,
       raggeditem ri, 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
       ri_link.uniqueitem_link_id = ds.uniqueitem_link_id AND
       ri.raggeditem_id = ri_link.raggeditem_id
UNION ALL
-- UNIQUE ITEMS
SELECT --+index(ds XIF11DELIVERYSCAN)
       bu.code BU_CODE, bu.description BU_DESC,
       p.code product_code, p.legacyproductcode, 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, wo.referencenumber, ds.outscannodelivery
  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)
                  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 LEFT OUTER JOIN (uniqueitemfixedinfo uifi LEFT OUTER JOIN workorder wo on wo.workorder_id = uifi.issuedbyworkorder_id) on uifi.uniqueitem_id = ui_link.uniqueitem_id,
       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
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, 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, wo.referencenumber, null outscannodelivery
  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)
                  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 LEFT OUTER JOIN (uniqueitemfixedinfo uifi LEFT OUTER JOIN workorder wo on wo.workorder_id = uifi.issuedbyworkorder_id) on uifi.uniqueitem_id = ri_link.uniqueitem_id,
       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
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, 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, wo.referencenumber, null outscannodelivery
  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)
                  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 LEFT OUTER JOIN (uniqueitemfixedinfo uifi LEFT OUTER JOIN workorder wo on wo.workorder_id = uifi.issuedbyworkorder_id) on uifi.uniqueitem_id = ui_link.uniqueitem_id,
       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
       o.ragreason_id is null

/
create or replace view V_DELIVERYSCAN_ALL_CBD
 (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, LANGUAGECODE, PRODUCT_DESC)
as SELECT --+index(ds XIF11DELIVERYSCAN) index(ri_link XSPEEDUNIQUEITEM_LINK)
       bu.code BU_CODE, bu.description BU_DESC,
       p.code product_code, p.legacyproductcode, 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,
       (select description from product_desc pd
         where  pd.product_id = p.product_id and pd.language_id = l.language_id) product_desc
  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)
                  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
 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
UNION ALL
-- UNIQUE ITEMS
SELECT --+index(ds XIF11DELIVERYSCAN)
       bu.code BU_CODE, bu.description BU_DESC,
       p.code product_code, p.legacyproductcode, 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,
       (select description from product_desc pd
         where  pd.product_id = p.product_id and pd.language_id = l.language_id) product_desc
  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)
                  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
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, 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,
       (select description from product_desc pd
         where  pd.product_id = p.product_id and pd.language_id = l.language_id) product_desc
  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)
                  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
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, 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,
       (select description from product_desc pd
         where  pd.product_id = p.product_id and pd.language_id = l.language_id) product_desc
  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)
                  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
       o.ragreason_id is null

/
create or replace view V_DELIVERYSCAN_ALL_LTS
 (BU_CODE, BU_DESC, PRODUCT_CODE, LEGACYPRODUCTCODE, SIZE_CODE, LEGACYSIZECODE, FROMSTOCK, PACKINGNOTE_ID, SCANTIMESTAMP, CHARGEWASHING, PRIMARYID, REASON_CODE, PRODUCT_DESC, WEARERNUMBER, WEARERNAME, WEARERSEARCHNAME, EMPLOYMENT_NR, TYPEOFMERCHANDISE, CUPBOARD, LOCKER, LOCKERSTATUS, LOCKER_REMARK, LOCKER_SORTADDRESS, WEAREREMPLOYMENT_LINK_ID, LANGUAGECODE)
as SELECT --+index(ds XIF11DELIVERYSCAN)
       bu.code BU_CODE, bu.description BU_DESC,
       p.code product_code, p.legacyproductcode, 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,
       (select pd.description from product_link_desc pd where pd.product_link_id = p.product_link_id
        and pd.language_id = l.language_id) product_desc,
       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
  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)
                  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
/*commented the 3 unions on E. de Groot remarks
SELECT --+index(ds XIF11DELIVERYSCAN) index(ri_link XSPEEDUNIQUEITEM_LINK)  this is first select
       bu.code BU_CODE, bu.description BU_DESC,
       p.code product_code, p.legacyproductcode, 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,
       (select pd.description from product_link_desc pd where pd.product_link_id = p.product_link_id
        and pd.language_id = l.language_id) product_desc,
       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
  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)
                  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
 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
UNION ALL
union all -- return to stock from raggeditem - never showing
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, 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,
       (select pd.description from product_link_desc pd where pd.product_link_id = p.product_link_id
        and pd.language_id = l.language_id) product_desc,
       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
  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)
                  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
union all -- return to stock from uniqueitem  - never showing
SELECT --+index(o XIE3OUTOFCIRCULATIONHISTORY)
       distinct bu.code BU_CODE, bu.description BU_DESC,
       p.code product_code, p.legacyproductcode, 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,
       (select pd.description from product_link_desc pd where pd.product_link_id = p.product_link_id
        and pd.language_id = l.language_id) product_desc,
       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
  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)
                  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
       o.ragreason_id is null*/

/
create or replace view V_DELIVERYSCAN_ALL_POS
 (BU_CODE, BU_DESC, PRODUCT_CODE, LEGACYPRODUCTCODE, SIZE_CODE, LEGACYSIZECODE, FROMSTOCK, PACKINGNOTE_ID, SCANTIMESTAMP, CHARGEWASHING, PRIMARYID, REASON_CODE, WEARERNUMBER, WEARERNAME, WEARERSEARCHNAME, EMPLOYMENT_NR, TYPEOFMERCHANDISE, WEAREREMPLOYMENT_LINK_ID, LANGUAGECODE)
as SELECT --+index(ds XIF11DELIVERYSCAN) index(ri_link XSPEEDUNIQUEITEM_LINK) index(w_link XPKWEAREREMPLOYMENT_LINK) index(s XPKSIZEDEFINITION_LINK)
       bu.code BU_CODE, bu.description BU_DESC,
       p.code product_code, p.legacyproductcode, 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,
       p.typeofmerchandise, ds.weareremployment_link_id, l.code languagecode
  FROM deliveryscan ds
       LEFT OUTER JOIN reasoncode r ON r.reasoncode_id = ds.reasoncode_id
       LEFT OUTER JOIN weareremployment_link w_link on w_link.weareremployment_link_id = ds.weareremployment_link_id,
       product p,
       businessunit bu, sizedefinition_link s,
       uniqueitem_link ri_link, raggeditem ri, languages l
 WHERE bu.businessunit_id = ds.businessunit_id and
       p.product_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
UNION ALL-- UNIQUE ITEMS
SELECT --+index(ds XIF11DELIVERYSCAN)  index(w_link XPKWEAREREMPLOYMENT_LINK)  index(s XPKSIZEDEFINITION_LINK)
       bu.code BU_CODE, bu.description BU_DESC,
       p.code product_code, p.legacyproductcode, 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,
       p.typeofmerchandise, ds.weareremployment_link_id, l.code languagecode
  FROM deliveryscan ds
       LEFT OUTER JOIN reasoncode r ON r.reasoncode_id = ds.reasoncode_id
       LEFT OUTER JOIN weareremployment_link w_link on w_link.weareremployment_link_id = ds.weareremployment_link_id,
       product p,
       businessunit bu, sizedefinition_link s, uniqueitem_link ui_link, uniqueitem ui, languages l
 WHERE bu.businessunit_id = ds.businessunit_id and
       p.product_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
union all -- return to stock from raggeditem
SELECT --+index(o XIE3OUTOFCIRCULATIONHISTORY)  index(ri_link XSPEEDUNIQUEITEM_LINK)  index(p XIF311PRODUCT_LINK)  index(w_link XPKWEAREREMPLOYMENT_LINK)
       distinct bu.code BU_CODE, bu.description BU_DESC,
       p.code product_code, p.legacyproductcode, 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,
       p.typeofmerchandise, o.weareremployment_link_id, l.code languagecode
  FROM outofcirculationhistory o
       LEFT OUTER JOIN weareremployment_link w_link on w_link.weareremployment_link_id = o.weareremployment_link_id,
       product p,
       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_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
union all -- return to stock from uniqueitem
SELECT --+index(o XIE3OUTOFCIRCULATIONHISTORY)  index(w_link XPKWEAREREMPLOYMENT_LINK) index_rs(we XPKWEAREREMPLOYMENT)
       distinct bu.code BU_CODE, bu.description BU_DESC,
       p.code product_code, p.legacyproductcode, 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,
       p.typeofmerchandise, o.weareremployment_link_id, l.code languagecode
  FROM outofcirculationhistory o
       LEFT OUTER JOIN reasoncode r ON r.reasoncode_id = o.reasoncode_id
       LEFT OUTER JOIN weareremployment_link w_link on w_link.weareremployment_link_id = o.weareremployment_link_id,
       product p,
       businessunit bu, sizedefinition_link s, uniqueitem_link ui_link, uniqueitem ui, languages l
 WHERE bu.businessunit_id = o.processbusinessunit_id and
       p.product_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
       o.ragreason_id is null

/
create or replace view V_DELIVERYSCAN_ALL_SMG
 (LINETYPE, PRODUCT_CODE, SCANSONDELIVERYNOTE, PRODDESC, LEGACYPRODUCTCODE, SIZE_CODE, LEGACYSIZECODE, FROMSTOCK, PACKINGNOTE_ID, SCANTIMESTAMP, CHARGEWASHING, PRIMARYID, REASONCODE, REASON_CODE, WEARERNUMBER, WEARERNAME, WEARERSEARCHNAME, EMPLOYMENT_NR, WEAREREMPLOYMENT_LINK_ID, LANGUAGECODE, LASTOUTSCANDATE, BANKLOCKER, QUANTITY)
as SELECT --+index(ds XIF11DELIVERYSCAN) index(ri_link XSPEEDUNIQUEITEM_LINK)
       1 linetype, p.code product_code,
       (select c.scansondeliverynote from customer c where c.customer_id=ds.customer_link_id) scansondeliverynote,
      (select pd.description from product_desc pd where pd.product_id= p.product_id and pd.language_id = l.language_id) proddesc,
        p.legacyproductcode, s.code size_code, s.legacysizecode,
       ds.fromstock, ds.packingnote_id, ds.scantimestamp, ds.chargewashing,
       ri.primaryid, 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,
       w_link.wearernumber, w_link.wearername, w_link.wearersearchname, w_link.sequencenumber employment_nr,
       ds.weareremployment_link_id, l.code languagecode,
       ds.scantimestamp lastoutscandate,
       (select lo.bank || ' / ' || lo.locker
        from locker lo, weareremployment we
        where lo.locker_id = we.locker_id
              and we.weareremployment_id = w_link.weareremployment_id) banklocker,
       -1 quantity
FROM deliveryscan ds
       LEFT OUTER JOIN reasoncode r ON r.reasoncode_id = ds.reasoncode_id
       LEFT OUTER JOIN weareremployment_link w_link on w_link.weareremployment_link_id = ds.weareremployment_link_id,
       product_link p JOIN product prod ON prod.product_id = p.product_id AND prod.typeofmerchandise = 2,
       sizedefinition_link s,
       uniqueitem_link ri_link, raggeditem ri, languages l
WHERE 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
UNION ALL-- UNIQUE ITEMS
SELECT --+index(ds XIF11DELIVERYSCAN)
      2 linetype, p.code product_code,
      (select c.scansondeliverynote from customer c where c.customer_id=ds.customer_link_id) scansondeliverynote,
       (select pd.description from product_desc pd where pd.product_id= p.product_id and pd.language_id = l.language_id) proddesc,
       p.legacyproductcode, s.code size_code, s.legacysizecode,
       ds.fromstock, ds.packingnote_id, ds.scantimestamp, ds.chargewashing,
       ui.primaryid, 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,
       w_link.wearernumber, w_link.wearername, w_link.wearersearchname, w_link.sequencenumber employment_nr,
       ds.weareremployment_link_id, l.code languagecode,
       ds.scantimestamp lastoutscandate, --ui.lastoutscandate, SO-20011163.140 TR-30013918
       (select lo.bank || ' / ' || lo.locker
        from locker lo, weareremployment we
        where lo.locker_id = we.locker_id
              and we.weareremployment_id = w_link.weareremployment_id) banklocker,
       1 quantity
FROM deliveryscan ds
       LEFT OUTER JOIN reasoncode r ON r.reasoncode_id = ds.reasoncode_id
       LEFT OUTER JOIN weareremployment_link w_link on w_link.weareremployment_link_id = ds.weareremployment_link_id,
       product_link p JOIN product prod ON prod.product_id = p.product_id AND prod.typeofmerchandise = 2,
       sizedefinition_link s, uniqueitem_link ui_link, uniqueitem ui, languages l
WHERE 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
       and ds.scantimestamp=( select max(dss.scantimestamp) from deliveryscan  dss where dss.uniqueitem_link_id=ui.uniqueitem_id and dss.packingnote_id =ds.packingnote_id)
union all -- return to stock from raggeditem
SELECT distinct --+index(o XIE3OUTOFCIRCULATIONHISTORY)  index(ri_link XSPEEDUNIQUEITEM_LINK)
       3 linetype,p.code product_code,
            (select c.scansondeliverynote from customer c where c.customer_id=o.customer_link_id) scansondeliverynote,
       (select pd.description from product_desc pd where pd.product_id= p.product_id and pd.language_id = l.language_id) proddesc,
        p.legacyproductcode, s.code size_code, s.legacysizecode,
       'Z' fromstock, o.packingnote_id, o.outofcircdate scantimestamp, null chargewashing,
       coalesce(ri.primaryid, o.primaryid) primaryid, 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,
       w_link.wearernumber, w_link.wearername, w_link.wearersearchname, w_link.sequencenumber employment_nr,
       o.weareremployment_link_id, l.code languagecode,
       o.outofcircdate lastoutscandate,
       (select lo.bank || ' / ' || lo.locker
        from locker lo, weareremployment we
        where lo.locker_id = we.locker_id
              and we.weareremployment_id = w_link.weareremployment_id) banklocker,
       -1 quantity
FROM outofcirculationhistory o
       LEFT OUTER JOIN weareremployment_link w_link on w_link.weareremployment_link_id = o.weareremployment_link_id,
       product_link p JOIN product prod ON prod.product_id = p.product_id AND prod.typeofmerchandise = 2,
       sizedefinition_link s,
       uniqueitem_link ri_link , raggeditem ri,reasoncode r, languages l
WHERE 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
       r.reasoncode_id = o.reasoncode_id
       and ri.raggeditem_id = ri_link.raggeditem_id
    and (coalesce((select c.customer_id from customer c where o.customer_link_id=c.customer_id),8)>=8)
union all -- return to stock from uniqueitem
SELECT distinct --+index(o XIE3OUTOFCIRCULATIONHISTORY)
      4 linetype, p.code product_code,
                  (select c.scansondeliverynote from customer c where c.customer_id=o.customer_link_id) scansondeliverynote,
       (select pd.description from product_desc pd where pd.product_id= p.product_id and pd.language_id = l.language_id) proddesc,
       p.legacyproductcode, s.code size_code, s.legacysizecode,
       'Z' fromstock, o.packingnote_id, o.outofcircdate scantimestamp, null chargewashing,
       ui.primaryid, 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,
       w_link.wearernumber, w_link.wearername, w_link.wearersearchname, w_link.sequencenumber employment_nr,
       o.weareremployment_link_id, l.code languagecode,
       o.outofcircdate lastoutscandate, --ui.lastoutscandate 20011163.260 TR30014001
       (select lo.bank || ' / ' || lo.locker
        from locker lo, weareremployment we
        where lo.locker_id = we.locker_id
              and we.weareremployment_id = w_link.weareremployment_id) banklocker,
     -1 quantity
FROM outofcirculationhistory o
       LEFT OUTER JOIN reasoncode r ON r.reasoncode_id = o.reasoncode_id
       LEFT OUTER JOIN weareremployment_link w_link on w_link.weareremployment_link_id = o.weareremployment_link_id,
       product_link p JOIN product prod ON prod.product_id = p.product_id AND prod.typeofmerchandise = 2,
       sizedefinition_link s, uniqueitem_link ui_link, uniqueitem ui, languages l
WHERE 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
       (coalesce((select c.customer_id from customer c where o.customer_link_id=c.customer_id),8)>=8) and
      ((o.ragreason_id is NULL) or not exists (SELECT 2 FROM deliveryscan ds
       LEFT OUTER JOIN reasoncode r ON r.reasoncode_id = ds.reasoncode_id
       LEFT OUTER JOIN weareremployment_link w_link on w_link.weareremployment_link_id = ds.weareremployment_link_id,
       product_link p JOIN product prod ON p.product_id = prod.product_id AND prod.typeofmerchandise = 2,
       sizedefinition_link s, uniqueitem_link ui_link, uniqueitem ui, languages l
      WHERE 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
       and ds.uniqueitem_link_id=o.uniqueitem_link_id
       and ds.packingnote_id=o.packingnote_id))

/
create or replace view V_DELIVERYSCAN_FLAGS_CBD
 (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, LANGUAGECODE, PRODUCT_DESC, FLAGCODE, FLAG_DESC, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION)
as select --+index(ds XIF11DELIVERYSCAN)
       bu.code BU_CODE
,      bu.description BU_DESC
,      p.code product_code
,      p.legacyproductcode
,      s.code size_code
,      s.legacysizecode
,      ds.fromstock
,      ds.packingnote_id
,      ds.scantimestamp
,      ds.chargewashing
,      ui.primaryid
,      ( 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
,      ( select description
         from   product_desc pd
         where  pd.product_id = p.product_id
            and pd.language_id = l.language_id) product_desc
,      f.code flagcode
,      ( select description
         from   flag_desc fd
         where  fd.flag_id = f.flag_id
            and fd.language_id = l.language_id) flag_desc
,      ( select pnl.customcode
         from   packingnoteline pnl
         where  pnl.packingnote_id = ds.packingnote_id
            and pnl.product_id = p.product_id
            and pnl.sizedefinition_id = ds.sizedefinition_link_id
            and pnl.finishingmethod_id = ds.finishingmethod_id) productcustomcode
,      ( select pnl.customdescription
         from   packingnoteline pnl
         where  pnl.packingnote_id = ds.packingnote_id
            and pnl.product_id = p.product_id
            and pnl.sizedefinition_id = ds.sizedefinition_link_id
            and pnl.finishingmethod_id = ds.finishingmethod_id) productcustomdescription
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)
                  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
,      uniqueitemflag uf
,      flag f
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
   and uf.uniqueitem_id = ds.uniqueitem_link_id
   and uf.startdate <= ds.scantimestamp
   and uf.flag_id = f.flag_id
   and f.code in ('MAX_KE','BESCHÄ','INFEKT')

/
create or replace view V_DELIVERYSCAN_NAF_L8
 (PRODUCT_CODE, PRODUCTDESCRIPTION, PACKINGNOTE_ID, PRIMARYID, CUSTOMEROWNED, WEARERNUMBER, WEARERNAME, CUPBOARD, LOCKER, WEAREREMPLOYMENT_LINK_ID, LANGUAGECODE)
as select --+index(ds xif11deliveryscan) index(ri_link xspeeduniqueitem_link)
 p.code product_code,
 (select description
    from product_desc a
   where p.product_id = a.product_id
     and a.language_id = l.language_id) productdescription,
 ds.packingnote_id,
 ri.primaryid,
 ri.customerowned,
 w_link.wearernumber,
 w_link.wearername,
 locker.bank cupboard,
 locker.locker,
 ds.weareremployment_link_id,
 l.code languagecode
  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)
                  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, uniqueitem_link ri_link, raggeditem ri,
 languages l
 where p.product_link_id = ds.product_link_id
   and ri_link.uniqueitem_link_id = ds.uniqueitem_link_id
   and ri.raggeditem_id = ri_link.raggeditem_id
union all
-- unique items
select --+index(ds xif11deliveryscan)
 p.code product_code,
 (select description
    from product_desc a
   where p.product_id = a.product_id
     and a.language_id = l.language_id) productdescription,
 ds.packingnote_id,
 ui.primaryid,
 ui.customerowned,
 w_link.wearernumber,
 w_link.wearername,
 locker.bank cupboard,
 locker.locker,
 ds.weareremployment_link_id,
 l.code languagecode
  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)
                  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, uniqueitem_link ui_link, uniqueitem ui,
 languages l
 where p.product_link_id = ds.product_link_id
   and ui_link.uniqueitem_link_id = ds.uniqueitem_link_id
   and ui.uniqueitem_id = ui_link.uniqueitem_id

/
create or replace view V_DELIVERYSCAN_NLI
 (TEST, 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, BANK, LOCKER_REMARK, LOCKER_SORTADDRESS, LANGUAGE_CODE, PRODUCT_DESCRIPTION, WEAREREMPLOYMENT_LINK_ID, LASTINSCANDATE)
as SELECT null test, bu.code BU_CODE, bu.description BU_DESC,
       p.code product_code, p.legacyproductcode, s.code size_code, s.legacysizecode,
       ds.fromstock, ds.packingnote_id, ds.scantimestamp, ds.chargewashing,
       ri.primaryid, r.code 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.bank,
       locker.remark locker_remark, locker.sortaddress locker_sortaddress
       , languages.code language_code, (select pd.description from product_link_desc pd where pd.product_link_id = p.product_link_id
         and pd.language_id = languages.language_id) product_description
       , ds.weareremployment_link_id, null lastinscandate
  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)
                  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
 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
UNION ALL
-- UNIQUE ITEMS
SELECT ds.timestamp test, bu.code BU_CODE, bu.description BU_DESC,
       p.code product_code, p.legacyproductcode, s.code size_code, s.legacysizecode,
       ds.fromstock, ds.packingnote_id, ds.scantimestamp, ds.chargewashing,
       ui.primaryid, r.code 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.bank,
       locker.remark locker_remark, locker.sortaddress locker_sortaddress
       , languages.code language_code, (select pd.description from product_link_desc pd where pd.product_link_id = p.product_link_id
         and pd.language_id = languages.language_id) product_description
       , ds.weareremployment_link_id, ui.lastinscandate
  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)
                  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
 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

/
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_LLG
 (CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, PRODUCT_ID, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDEFINITION_ID, SIZEDESCRIPTION, FINISHINGMETHOD_ID, FINISHINGMETHODCODE, FINISHINGMETHODDESCRIPTION, PACKINGNOTENUMBER, PROCESSBUSINESSUNIT_ID, DELIVERYDATE, ORIGIN, AMOUNT, FIXEDAMOUNT, REFERENCE, PROCESSED, CAUSENOTENUMBER, CAUSENOTEDELIVERYDATE, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE, SOILCOUNTSUBTYPE
, REASONCODE_ID, RC_CODE, RC_DESCRIPTION, ADJ_RC_CODE, ADJ_RC_DESCRIPTION)
as SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME,
  DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
  DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
  PRODUCT.PRODUCT_ID,
  PRODUCT.CODE PRODUCTCODE,
  (SELECT DESCRIPTION FROM PRODUCT_DESC P WHERE P.PRODUCT_ID = DELIVERYVARIATIONS.PRODUCT_ID
     AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  PRODUCTDESCRIPTION,
  DELIVERYVARIATIONS.SIZEDEFINITION_ID,
  --SIZEDEFINITION.CODE,
  (SELECT DESCRIPTION FROM SIZEDEFINITION_DESC S WHERE S.SIZEDEFINITION_ID = DELIVERYVARIATIONS.SIZEDEFINITION_ID
     AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  SIZEDESCRIPTION,
  FINISHINGMETHOD.FINISHINGMETHOD_ID,
  FINISHINGMETHOD.CODE FINISHINGMETHODCODE,
  (SELECT DESCRIPTION FROM FINISHINGMETHOD_DESC F WHERE F.FINISHINGMETHOD_ID = DELIVERYVARIATIONS.FINISHINGMETHOD_ID
     AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  FINISHINGMETHODDESCRIPTION,
  PACKINGNOTE.NOTENUMBER PACKINGNOTENUMBER, PACKINGNOTE.PROCESSBUSINESSUNIT_ID,
  DELIVERYVARIATIONS.DELIVERYDATE, DELIVERYVARIATIONS.ORIGIN,
  DELIVERYVARIATIONS.AMOUNT,
  DELIVERYVARIATIONS.FIXEDAMOUNT, DELIVERYVARIATIONS.REFERENCE, DELIVERYVARIATIONS.PROCESSED,
  CAUSENOTE.NOTENUMBER CAUSENOTENUMBER, CAUSENOTE.DELIVERYDATE CAUSENOTEDELIVERYDATE,
  DELIVERYVARIATIONS.SYSTEMUSER_ID, GETDATEONLY(DELIVERYVARIATIONS.TIMESTAMP) TIMESTAMP, LANGUAGES.CODE LANGUAGECODE,
  DELIVERYVARIATIONS.SOILCOUNTSUBTYPE,
  DELIVERYVARIATIONS.REASONCODE_ID,
  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 = LANGUAGES.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 = LANGUAGES.LANGUAGE_ID) ADJ_RC_DESCRIPTION
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT,
  PRODUCT, FINISHINGMETHOD, LANGUAGES,
  DELIVERYVARIATIONS
    LEFT OUTER JOIN PACKINGNOTE ON (DELIVERYVARIATIONS.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID)
    LEFT OUTER JOIN PACKINGNOTE CAUSENOTE ON (DELIVERYVARIATIONS.CAUSENOTE_ID = CAUSENOTE.PACKINGNOTE_ID)
    LEFT OUTER JOIN REASONCODE RC ON (DELIVERYVARIATIONS.REASONCODE_ID = RC.REASONCODE_ID)
    LEFT OUTER JOIN REASONCODE ADJ_RC ON (DELIVERYVARIATIONS.ADJUSTMENTREASON_ID = ADJ_RC.REASONCODE_ID)
WHERE DELIVERYVARIATIONS.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
  AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
  AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND DELIVERYVARIATIONS.PRODUCT_ID = PRODUCT.PRODUCT_ID
  AND DELIVERYVARIATIONS.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
  AND DEPARTMENT.ACTIVE = 'Y'-- DELIVERYVARIATIONS.RPT
  and packingnote.status_id <> 8 --Cancelled

/
create or replace view V_DELIVERYVARIATIONS_NIX
 (CUSTOMERNUMBER, CUSTOMERNAME, 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, CIRCINVENTORY)
as SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME,
  DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
  DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
  PRODUCT.CODE PRODUCTCODE,
  (SELECT DESCRIPTION FROM PRODUCT_DESC P WHERE P.PRODUCT_ID = DELIVERYVARIATIONS.PRODUCT_ID
     AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  PRODUCTDESCRIPTION,  --SIZEDEFINITION.CODE,
  (SELECT DESCRIPTION FROM SIZEDEFINITION_DESC S WHERE S.SIZEDEFINITION_ID = DELIVERYVARIATIONS.SIZEDEFINITION_ID
     AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  SIZEDESCRIPTION,
  FINISHINGMETHOD.CODE FINISHINGMETHODCODE,
  (SELECT DESCRIPTION FROM FINISHINGMETHOD_DESC F WHERE F.FINISHINGMETHOD_ID = DELIVERYVARIATIONS.FINISHINGMETHOD_ID
     AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  FINISHINGMETHODDESCRIPTION,
  PACKINGNOTE.NOTENUMBER PACKINGNOTENUMBER, PACKINGNOTE.PROCESSBUSINESSUNIT_ID,
  DELIVERYVARIATIONS.DELIVERYDATE, DELIVERYVARIATIONS.ORIGIN,
  DELIVERYVARIATIONS.AMOUNT,
  DELIVERYVARIATIONS.FIXEDAMOUNT, DELIVERYVARIATIONS.REFERENCE, DELIVERYVARIATIONS.PROCESSED,
  CAUSENOTE.NOTENUMBER CAUSENOTENUMBER, CAUSENOTE.DELIVERYDATE CAUSENOTEDELIVERYDATE,
  DELIVERYVARIATIONS.SYSTEMUSER_ID, GETDATEONLY(DELIVERYVARIATIONS.TIMESTAMP) TIMESTAMP, LANGUAGES.CODE LANGUAGECODE,
  DELIVERYVARIATIONS.SOILCOUNTSUBTYPE
  , (select sum(wei.circinventory) from wearerinventory wei, weareremployment wea where wei.product_id = product.product_id and
  wei.sizedefinition_id = DELIVERYVARIATIONS.SIZEDEFINITION_ID and wei.finishingmethod_id = FINISHINGMETHOD.Finishingmethod_Id
  and wei.weareremployment_id = wea.weareremployment_id and wea.distributionpoint_id = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
  ) circinventory
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT,
  PRODUCT, FINISHINGMETHOD, LANGUAGES,
  DELIVERYVARIATIONS
    LEFT OUTER JOIN PACKINGNOTE ON (DELIVERYVARIATIONS.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID)
    LEFT OUTER JOIN PACKINGNOTE CAUSENOTE ON (DELIVERYVARIATIONS.CAUSENOTE_ID = CAUSENOTE.PACKINGNOTE_ID)
WHERE DELIVERYVARIATIONS.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
	AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
	AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
	AND DELIVERYVARIATIONS.PRODUCT_ID = PRODUCT.PRODUCT_ID
  AND DELIVERYVARIATIONS.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
  AND DEPARTMENT.ACTIVE = 'Y'-- DELIVERYVARIATIONS.RPT

/
create or replace view V_DELPIECES_ECL
 (DELIVERYDATE, TYPEOFMERCHANDISE, PRODCODE, PRD_DESC, CODE, PG_DESC, PCK_DEP, DELIVERED, FOC, REJECTED, SHORTS)
as select pn.deliverydate, p.typeofmerchandise, p.code prodcode,
(select pd.description from product_desc pd where pd.product_id=p.product_id and pd.language_id=l.language_id) prd_desc,
pg.code, (select pgd.description from  productgroup_desc pgd where pgd.productgroup_id=pg.productgroup_id and pgd.language_id=l.language_id) pg_desc,
coalesce((select pd.description from distributionpoint dp join standarddelivery sd on sd.distributionpoint_id=dp.distributionpoint_id
join plantdepartment pd on sd.plantdepartment_id=pd.plantdepartment_id where dp.distributionpoint_id=pn.distributionpoint_id),
(select pd.description from productgroup pgi
join packingdepartmentdefinition pkd on pgi.productgroup_id=pkd.productgroup_id
join plantdepartment pd on pkd.plantdepartment_id=pd.plantdepartment_id
join businessunit bu on bu.plant_id = pd.plant_id
join customer c on c.defaultbusinessunit_id = bu.businessunit_id
join department dpp on dpp.customer_id = c.customer_id
join distributionpoint dpdp on dpdp.department_id = dpp.department_id
where pgi.productgroup_id=pg.productgroup_id and dpdp.distributionpoint_id = pn.distributionpoint_id)) pck_dep,
sum(pnl.deliveredamount) delivered, sum(pnl.nochargeprevshortage) foc, sum(pnl.nochargeprevrejected) rejected, sum(pnl.tobedeliveredamount-pnl.actualdelivery) shorts
from packingnote pn join packingnoteline pnl on 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') -- processed
join product p on pnl.product_id=p.product_id
join productgroup pg on p.productgroup_id=pg.productgroup_id
cross join languages l where l.code='EN_GB'
group by p.code, p.product_id, l.language_id, pg.code, pg.productgroup_id, pn.deliverydate, p.typeofmerchandise, pn.distributionpoint_id

/
create or replace view V_DELPRODSCONSIGNMENT_ECL
 (CONSIGNMENTNOTENUMBER, DISTRIBUTIONPOINT_ID, DELIVERYDATE)
as select distinct cn.consignmentnotenumber, pn.distributionpoint_id, pn.deliverydate from
      consignmentnote cn, packingnote pn
      where pn.consignmentnote_id = cn.consignmentnote_id
      order by cn.consignmentnotenumber asc

/
create or replace view V_DELPRODUCTSPERCUSTROUTE_SMG
 (CUSTOMERNUMBER, NAME, DISTRIBUTIONPOINTNUMBER, DP_DESC, LEGACYDISTRIBUTIONPOINTNUMBER, DELIVERYDATE, NOTENUMBER, FREEOFCHARGEREASON_ID, STATUS_ID, FACTORYDESCRIPTION, PRODUCTCODE, PROD_DESC, SIZECODE, FINISHINGMETHODCODE, DELIVEREDAMOUNT, ROUTENUMBER, DRIVINGDATE)
as select c.customernumber, c.name, dp.distributionpointnumber, dp.description dp_desc,
       dp.legacydistributionpointnumber,
       pk.deliverydate,
       pk.notenumber,
       pk.freeofchargereason_id,
       pk.status_id, st.factorydescription,
       p.code productcode,
       (select pdesc.description from product_desc pdesc where pdesc.product_id = p.product_id and pdesc.language_id = c.language_id) prod_desc,
       s.code sizecode, f.code finishingmethodcode,
       --sum(pkl.deliveredamount) deliveredamount,
       pkl.deliveredamount,
       r.routenumber, rc.drivingdate
from   packingnote pk
       left outer join(routecontrol rc join route r on r.route_id = rc.route_id)
            on rc.routecontrol_id = pk.routecontrol_id,
       packingnoteline pkl, distributionpoint dp, department t, customer c, product p, sizedefinition s, finishingmethod f, status st
where  pk.packingnote_id = pkl.packingnote_id
and    pk.distributionpoint_id = dp.distributionpoint_id
and    dp.department_id = t.department_id
and    t.customer_id = c.customer_id
and    pkl.product_id = p.product_id
and    pkl.sizedefinition_id = s.sizedefinition_id
and    pkl.finishingmethod_id = f.finishingmethod_id
and    st.status_id = pk.status_id
and    st.statustype = 'PN'
and    st.code = '30' -- nur verarbeitete LS
/*group  by c.customernumber, c.name, dp.distributionpointnumber, dp.description, dp.legacydistributionpointnumber,
          pk.deliverydate, pk.notenumber, pk.freeofchargereason_id,
          pk.status_id, st.factorydescription,
          p.code, s.code, f.code, r.routenumber
order  by dp.distributionpointnumber, dp.legacydistributionpointnumber, pk.deliverydate,
          r.routenumber, p.code, s.code
and    c.customernumber = 110922
and    pk.deliverydate BETWEEN '01-MAR-2012' AND '31-MAR-2012'*/

/
create or replace view V_DELSCANPERRC_AUX_SMG
 (LINETYPE, PRODUCT_CODE, PRODDESC, LEGACYPRODUCTCODE, SIZE_CODE, LEGACYSIZECODE, FROMSTOCK, PACKINGNOTE_ID, SCANTIMESTAMP, CHARGEWASHING, PRIMARYID, REASONCODE, REASON_CODE, WEARERNUMBER, WEARERNAME, WEARERSEARCHNAME, EMPLOYMENT_NR, WEAREREMPLOYMENT_LINK_ID, LANGUAGECODE, LASTOUTSCANDATE, BANKLOCKER, QUANTITY)
as SELECT --+index(ds XIF11DELIVERYSCAN) index(ri_link XSPEEDUNIQUEITEM_LINK)
       1 linetype,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) proddesc,
        p.legacyproductcode, s.code size_code, s.legacysizecode,
       ds.fromstock, ds.packingnote_id, ds.scantimestamp, ds.chargewashing,
       ri.primaryid, 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,
       w_link.wearernumber, w_link.wearername, w_link.wearersearchname, w_link.sequencenumber employment_nr,
       ds.weareremployment_link_id, l.code languagecode,
       ds.scantimestamp lastoutscandate,
       (select lo.bank || ' / ' || lo.locker
        from locker lo, weareremployment we
        where lo.locker_id = we.locker_id
              and we.weareremployment_id = w_link.weareremployment_id) banklocker,
              1 quantity
  FROM deliveryscan ds
       LEFT OUTER JOIN reasoncode r ON r.reasoncode_id = ds.reasoncode_id
       LEFT OUTER JOIN weareremployment_link w_link on w_link.weareremployment_link_id = ds.weareremployment_link_id,
       product_link p JOIN product prod ON p.product_id = prod.product_id AND prod.typeofmerchandise = 2,
       sizedefinition_link s,
       uniqueitem_link ri_link, raggeditem ri, languages l
 WHERE 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
UNION ALL
-- UNIQUE ITEMS
SELECT --+index(ds XIF11DELIVERYSCAN)
       2 linetype,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) proddesc,
       p.legacyproductcode, s.code size_code, s.legacysizecode,
       ds.fromstock, ds.packingnote_id, ds.scantimestamp, ds.chargewashing,
       ui.primaryid, 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,
       w_link.wearernumber, w_link.wearername, w_link.wearersearchname, w_link.sequencenumber employment_nr,
       ds.weareremployment_link_id, l.code languagecode,
       ds.scantimestamp lastoutscandate, --ui.lastoutscandate, SO-20011163.140 TR-30013918
       (select lo.bank || ' / ' || lo.locker
        from locker lo, weareremployment we
        where lo.locker_id = we.locker_id
              and we.weareremployment_id = w_link.weareremployment_id) banklocker,
              1 quantity
  FROM deliveryscan ds
       LEFT OUTER JOIN reasoncode r ON r.reasoncode_id = ds.reasoncode_id
       LEFT OUTER JOIN weareremployment_link w_link on w_link.weareremployment_link_id = ds.weareremployment_link_id,
       product_link p JOIN product prod ON p.product_id = prod.product_id AND prod.typeofmerchandise = 2,
       sizedefinition_link s, uniqueitem_link ui_link, uniqueitem ui, languages l
 WHERE 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
       and ds.scantimestamp=( select max(dss.scantimestamp) from deliveryscan  dss where dss.uniqueitem_link_id=ui.uniqueitem_id and dss.packingnote_id =ds.packingnote_id)
union all -- return to stock from raggeditem
SELECT distinct --+index(o XIE3OUTOFCIRCULATIONHISTORY)  index(ri_link XSPEEDUNIQUEITEM_LINK)
       3 linetype,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) proddesc,
        p.legacyproductcode, s.code size_code, s.legacysizecode,
       'Z' fromstock, o.packingnote_id, o.outofcircdate scantimestamp, null chargewashing,
       coalesce(ri.primaryid, o.primaryid) primaryid, 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,
       w_link.wearernumber, w_link.wearername, w_link.wearersearchname, w_link.sequencenumber employment_nr,
       o.weareremployment_link_id, l.code languagecode,
       o.outofcircdate lastoutscandate,
       (select lo.bank || ' / ' || lo.locker
        from locker lo, weareremployment we
        where lo.locker_id = we.locker_id
              and we.weareremployment_id = w_link.weareremployment_id) banklocker,
              -1 quantity
  FROM outofcirculationhistory o
       LEFT OUTER JOIN weareremployment_link w_link on w_link.weareremployment_link_id = o.weareremployment_link_id,
       product_link p JOIN product prod ON p.product_id = prod.product_id AND prod.typeofmerchandise = 2,
       sizedefinition_link s,
       uniqueitem_link ri_link,raggeditem ri,reasoncode r, languages l
 WHERE 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
       r.reasoncode_id = o.reasoncode_id
       and ri.raggeditem_id = ri_link.raggeditem_id
    and (coalesce((select c.customer_id from customer c where o.customer_link_id=c.customer_id),8)>=8)
union all -- return to stock from uniqueitem
SELECT distinct --+index(o XIE3OUTOFCIRCULATIONHISTORY)
       4 linetype,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) proddesc,
       p.legacyproductcode, s.code size_code, s.legacysizecode,
       'Z' fromstock, o.packingnote_id, o.outofcircdate scantimestamp, null chargewashing,
       ui.primaryid, 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,
       w_link.wearernumber, w_link.wearername, w_link.wearersearchname, w_link.sequencenumber employment_nr,
       o.weareremployment_link_id, l.code languagecode,
       o.outofcircdate lastoutscandate, --ui.lastoutscandate 20011163.260 TR30014001
       (select lo.bank || ' / ' || lo.locker
        from locker lo, weareremployment we
        where lo.locker_id = we.locker_id
              and we.weareremployment_id = w_link.weareremployment_id) banklocker,
              -1 quantity
FROM outofcirculationhistory o
       LEFT OUTER JOIN reasoncode r ON r.reasoncode_id = o.reasoncode_id
       LEFT OUTER JOIN weareremployment_link w_link on w_link.weareremployment_link_id = o.weareremployment_link_id,
       product_link p JOIN product prod ON p.product_id = prod.product_id AND prod.typeofmerchandise = 2,
       sizedefinition_link s, uniqueitem_link ui_link, uniqueitem ui, languages l
WHERE 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
       (coalesce((select c.customer_id from customer c where o.customer_link_id=c.customer_id),8)>=8) and
       ((o.ragreason_id is NULL) or not exists (SELECT
      2
  FROM deliveryscan ds
       LEFT OUTER JOIN reasoncode r ON r.reasoncode_id = ds.reasoncode_id
       LEFT OUTER JOIN weareremployment_link w_link on w_link.weareremployment_link_id = ds.weareremployment_link_id,
       product_link p JOIN product prod ON p.product_id = prod.product_id AND prod.typeofmerchandise = 2,
       sizedefinition_link s, uniqueitem_link ui_link, uniqueitem ui, languages l
 WHERE 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
       and ds.uniqueitem_link_id=o.uniqueitem_link_id
       and ds.packingnote_id=o.packingnote_id
))

/
create or replace view V_DELSCANPERREASONCODE_SMG
 (POSITION, PRODUCT_CODE, PRODDESC, PACKINGNOTE_ID, REASONCODE, REASON_CODE, LANGUAGECODE, AMOUNT)
as SELECT -- raggeditem / uniqueitem
      '1' position, 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) proddesc,
       ds.packingnote_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,
       count(distinct ds.uniqueitem_link_id) AMOUNT
FROM deliveryscan ds
       inner JOIN reasoncode r ON r.reasoncode_id = ds.reasoncode_id
       inner JOIN product p ON p.product_id = ds.product_link_id AND p.typeofmerchandise = 2,
       languages l
group by ds.packingnote_id, r.code, r.reasoncode_id, p.code, p.product_id, l.language_id, l.code
union all -- return to stock from raggeditem / uniqueitem
SELECT '2' position, 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) proddesc,
        o.packingnote_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,
       (-1)*count(distinct o.uniqueitem_link_id) AMOUNT
FROM outofcirculationhistory o
       inner JOIN reasoncode r ON r.reasoncode_id = o.reasoncode_id
       inner JOIN product p ON p.product_id = o.product_link_id AND p.typeofmerchandise = 2,
       languages l
WHERE (coalesce((select c.customer_id from customer c where o.customer_link_id=c.customer_id),8)>=8)
group by o.packingnote_id, r.code, r.reasoncode_id, p.code, p.product_id, l.language_id, l.code

/
create or replace view V_DELSCAN_ALL_EDW
 (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, LANGUAGECODE, ISSUEREASON, FIXEDINFOREASON)
as SELECT --+index(ds XIF11DELIVERYSCAN) index(ri_link XSPEEDUNIQUEITEM_LINK)
       bu.code BU_CODE, bu.description BU_DESC,
       p.code product_code, p.legacyproductcode, 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,
       (select rd2.description
        from   issuehistory ih, reasoncode_desc rd2
        where  ih.uniqueitem_link_id = ri_link.uniqueitem_link_id
           and ih.assigndate = (select max(ih2.assigndate) from issuehistory ih2 where ih2.uniqueitem_link_id = ih.uniqueitem_link_id)
           and rd2.reasoncode_id = ih.reasoncode_id
           and rd2.language_id = l.language_id) issuereason,
       (select rd3.description
        from   uniqueitemfixedinfo uifi, reasoncode_desc rd3
        where  uifi.uniqueitem_id = ri_link.uniqueitem_id
           and rd3.reasoncode_id = uifi.reasoncode_id
           and rd3.language_id = l.language_id) fixedinforeason
  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)
                  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
 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
UNION ALL
-- UNIQUE ITEMS
SELECT --+index(ds XIF11DELIVERYSCAN)
       bu.code BU_CODE, bu.description BU_DESC,
       p.code product_code, p.legacyproductcode, 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,
       (select rd2.description
        from   issuehistory ih, reasoncode_desc rd2
        where  ih.uniqueitem_link_id = ui_link.uniqueitem_link_id
           and ih.assigndate = (select max(ih2.assigndate) from issuehistory ih2 where ih2.uniqueitem_link_id = ih.uniqueitem_link_id)
           and rd2.reasoncode_id = ih.reasoncode_id
           and rd2.language_id = l.language_id) issuereason,
       (select rd3.description
        from   uniqueitemfixedinfo uifi, reasoncode_desc rd3
        where  uifi.uniqueitem_id = ui_link.uniqueitem_id
           and rd3.reasoncode_id = uifi.reasoncode_id
           and rd3.language_id = l.language_id) fixedinforeason
  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)
                  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
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, 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,
       (select rd2.description
        from   issuehistory ih, reasoncode_desc rd2
        where  ih.uniqueitem_link_id = ri_link.uniqueitem_link_id
           and ih.assigndate = (select max(ih2.assigndate) from issuehistory ih2 where ih2.uniqueitem_link_id = ih.uniqueitem_link_id)
           and rd2.reasoncode_id = ih.reasoncode_id
           and rd2.language_id = l.language_id) issuereason,
       (select rd3.description
        from   uniqueitemfixedinfo uifi, reasoncode_desc rd3
        where  uifi.uniqueitem_id = ri_link.uniqueitem_id
           and rd3.reasoncode_id = uifi.reasoncode_id
           and rd3.language_id = l.language_id) fixedinforeason
  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)
                  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
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, 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,
       (select rd2.description
        from   issuehistory ih, reasoncode_desc rd2
        where  ih.uniqueitem_link_id = ui_link.uniqueitem_link_id
           and ih.assigndate = (select max(ih2.assigndate) from issuehistory ih2 where ih2.uniqueitem_link_id = ih.uniqueitem_link_id)
           and rd2.reasoncode_id = ih.reasoncode_id
           and rd2.language_id = l.language_id) issuereason,
       (select rd3.description
        from   uniqueitemfixedinfo uifi, reasoncode_desc rd3
        where  uifi.uniqueitem_id = ui_link.uniqueitem_id
           and rd3.reasoncode_id = uifi.reasoncode_id
           and rd3.language_id = l.language_id) fixedinforeason
  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)
                  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
       o.ragreason_id is null

/
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 < GETCURRENTDATE() and wey.dateinactive < GETCURRENTDATE() ) 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_DIRECTINVOICEHEADER_PRI
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, DELTOCUSTOMEREXTRANAME, LEGACYCODE, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS
, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL
, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES
, PAYMENTTERMS_DESC, INVOICELAYOUTCODE, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER
, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, INTERNALVATNUMBER, VATNUMBER, SETSPECIAL, CLUSTERCODE, DELTOCUSTLANG, DELIVERYNOTENUMBER, PAYMENTTERMSDUEDATE, REFERENCE, ACTIVITYREFERENCE, PRINTTAXONAPPENDIX, CUSTOMERBILLINGCOMMENT, COUNTREFERENCE, PACKINGNOTEID, TOTALREMARK)
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, a.deltocustomername,
       (select c.extraname1 from customer c where c.customernumber = a.deltocustomernumber) deltocustomerextraname,
       (select c.legacycustomernumber from customer c where c.customer_id = a.billtocustomer_link_id) legacycode,
       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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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
       , /*cast(*/(SELECT pldesc.invoiceremark FROM plantinvoiceremark_desc pldesc
          where pldesc.plant_id = p.plant_id and pldesc.language_id = p.language_id)/* as varchar2(50))*/  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,
       coalesce((select max(pa.packingnote_id) from packingnote pa, packingnoteline pl where pa.packingnote_id=pl.packingnote_id and pl.invoiceheader_id = a.invoiceheader_id and a.invoicefrequency_id = 0 and pa.origin = 5), 0) setspecial,       --0 is not based on special order, >0 is based on special order
(case when A.CLUSTER_ID is null then (select max(C.CODE)
                                                   from CUSTOMERSPERCLUSTER CPC, CUSTOMERCLUSTER C
                                                   where C.INVOICEFREQUENCY_ID = A.INVOICEFREQUENCY_ID
                                                         and CPC.CLUSTER_ID = C.CLUSTER_ID and CPC.CUSTOMER_ID = a.billtocustomer_link_id)
                                             else (select cc.code from customercluster cc where cc.cluster_id = a.cluster_id) end) clustercode,
(select languages.code from languages, customer c where a.deltocustomer_link_id = c.customer_id and languages.language_id = C.LANGUAGE_ID) deltocustlang,
(select max(pn.notenumber)  from packingnote pn, packingnoteline pnl where pn.packingnote_id = pnl.packingnote_id  and pnl.invoiceheader_id = a.invoiceheader_id) deliverynotenumber,
ihextr.paymenttermsduedate, a.reference, a.activityreference,
(select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix,
/*cast(*/(select cbc.description from customerbillingcomment cbc where cbc.customer_id = a.billtocustomer_link_id and cbc.type=1) /*as varchar2(50))*/ customerbillingcomment,
(SELECT distinct count(dv.REFERENCE) from deliveryvariations dv, packingnote pn, packingnoteline pnl where pnl.product_id = dv.product_id and pnl.sizedefinition_id = dv.sizedefinition_id and pnl.finishingmethod_id = dv.finishingmethod_id and dv.packingnote_id=pn.packingnote_id and pn.packingnote_id = pnl.packingnote_id and pnl.invoiceheader_id = a.invoiceheader_id and dv.reference is not null) countreference,
(select max(pn.packingnote_id)  from packingnote pn, packingnoteline pnl where pn.packingnote_id = pnl.packingnote_id and pnl.invoiceheader_id = a.invoiceheader_id) packingnoteid,
(select distinct count(pn.remark)  from packingnote pn, packingnoteline pnl where pn.packingnote_id = pnl.packingnote_id and pnl.invoiceheader_id = a.invoiceheader_id) totalremark
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),
      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)
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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

/
create or replace view V_DIRECTINVOICELINE_BDE
 (INVOICEDATE, INVOICENUMBER, PARENTINVOICEHEADER_ID, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, STARTWEEK, ENDWEEK, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PRICEFACTOR, FREQUENCY)
as select f.invoicedate, f.invoicenumber, f.parentinvoiceheader_id, a.linenumber,
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.adjustmentpermited, 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, b.adjustmentdeliveredqty
, F.NEXTPERIODSTARTWEEK, F.NEXTPERIODENDWEEK, F.STARTWEEK, F.ENDWEEK
, F.NEXTPERIODSTARTDATE, F.NEXTPERIODENDDATE, F.NEXTPERIODNOWEEKS
, b.pricefactor
--, (select dsc.frequency from deliveryscheme dsc, productlistpercustomer plpc where b.deliveryschemecode = dsc.code) Frequency
, (case
  when a.invoicelinetype_id = 1 and a.invoicelinesubtype in (0, 7, 8)--e.type = 1 and a.invoicelinesubtype = 0
  then FGET_BDE_FRECV(f.deltocustomer_link_id, b.product_link_id, b.sizedefinition_link_id, b.finishingmethod_id, f.invoicedate, b.deliveryschemecode)
  else -1
  end ) Frequency
from invoiceheader f, 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, LANGUAGES
where a.invoicelinetype_id = e.invoicelinetype_id
and a.invoiceheader_id = f.invoiceheader_id
and f.documenttype = 1

/
create or replace view V_DIRECTINVOICELINE_PRI
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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 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.adjustmentpermited,
       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
         where pilt.plant_id =bu.plant_id
           and pilt.invoicelinetype_id = a.invoicelinetype_id) InvoiceLine_SequenceNumber,
case (SELECT pilt.suppressprinting
         from plantinvoicelinetype pilt
         where bu.plant_id = pilt.plant_id
               and pilt.invoicelinetype_id = a.invoicelinetype_id)
  when 0 then 0
  when 1 then 1
  when 2 then 2
  else e.supressprinting
end supressprinting, --502161
       b.adjustmentdeliveredqty,
       b.pricefactor
  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, businessunit bu,
 LANGUAGES
 where a.invoicelinetype_id = e.invoicelinetype_id
   and a.invoiceheader_id = f.invoiceheader_id
   and f.invoicebusinessunit_id = bu.businessunit_id
   and f.documenttype = 1

/
create or replace view V_DIRECTINVOICEREF_PRI
 (REFERENCE, PACKINGNOTE_ID)
as SELECT DISTINCT dv.REFERENCE, dv.packingnote_id
 FROM   DELIVERYVARIATIONS dv
 where dv.reference is not null

/
create or replace view V_DIRECTINVOICE_DELNOTE_PRI
 (NOTENUMBER, REMARK, REFERENCE, INVOICEHEADER_ID)
as SELECT DISTINCT PN.NOTENUMBER,
                /*CAST ((*/PN.REMARK/*) as varchar2(60)) remark*/,
                -- CAST (
                (select distinct DV.REFERENCE
                   from deliveryvariations dv
                  where PNL.Product_Id = DV.Product_Id
                    and pnl.sizedefinition_id = dv.sizedefinition_id
                    and pnl.finishingmethod_id = dv.finishingmethod_id
                    and pn.packingnote_id = dv.packingnote_id) REFERENCE,
                -- AS VARCHAR2(60)) REFERENCE,
                PNL.INVOICEHEADER_ID
  FROM PACKINGNOTE PN, INVOICEHEADER IH, PACKINGNOTELINE PNL
 WHERE PN.PACKINGNOTE_ID = PNL.PACKINGNOTE_ID
   AND PNL.INVOICEHEADER_ID = IH.INVOICEHEADER_ID
 ORDER BY PN.NOTENUMBER

/
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)
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
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_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_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_EMBLEMHISTORYCC
 (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, CC_CODE_DESC)
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,
(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
, 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,
(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_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_EMPTY_LOCATIONS_LST
 (BUSINESSUNITCODE, ROWCODE, LOCATIONCODE, OVERFLOWYN, STOCKROOMCODE, BUSSINESSUNITDESCRIPTION)
as SELECT DISTINCT bu.code,
                   sl.rowcode,
                   SL.LOCATIONCODE,
                   SL.OVERFLOWLOCATION,
                   SR.CODE,
                   bu.description
     FROM stockroomlocation sl, stockroom sr, businessunit bu
    WHERE     SR.STOCKROOM_ID = SL.STOCKROOM_ID
          AND SR.MANAGEDBYBU_ID = bu.businessunit_id
          AND NOT EXISTS
                 (SELECT 1
                    FROM uniqueitemfixedinfo uif
                   WHERE UIF.STOCKROOMLOCATION_ID = SL.STOCKROOMLOCATION_ID)
          AND SL.OVERFLOWLOCATION = 'N'
          AND EXISTS
                 (SELECT 1
                    FROM standardlocationperproduct slpp
                   WHERE SLPP.STOCKROOMLOCATION_ID = sl.stockroomlocation_id)
   UNION ALL
   SELECT DISTINCT bu1.code,
                   sl1.rowcode,
                   SL1.LOCATIONCODE,
                   SL1.OVERFLOWLOCATION,
                   SR1.CODE,
                   bu1.description
     FROM stockroomlocation sl1, stockroom sr1, businessunit bu1
    WHERE     SR1.STOCKROOM_ID = SL1.STOCKROOM_ID
          AND SR1.MANAGEDBYBU_ID = bu1.businessunit_id
          AND SL1.OVERFLOWLOCATION = 'N'
          AND NOT EXISTS
                     (SELECT 1
                        FROM standardlocationperproduct slpp1
                       WHERE SLPP1.STOCKROOMLOCATION_ID =
                                sl1.stockroomlocation_id)
   ORDER BY 1, 2, 3

/
create or replace view V_ENHANCEDRETURNTOSTOCK
 (LINETYPE, DATEINACTIVE, DATEACTIVE, LOSSCHARGEDATE, LOSSCHARGEDAYS, MAXINVENTORY, CIRCINVENTORY, MAXFREEOFCHARGE, FREEOFCHARGEQTY, 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)
as select 0 linetype --Layout per Customer with Billing Day ALL
, wi.dateinactive, wi.dateactive, wi.losschargedate
, 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
, 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)--*/'ORA11'
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.customer_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, getdateonly(wi.timestamp) timestamp
, rp.reportparam_id
from wearerinventory wi, wearer w, weareremployment we, customer cu, businessunit bu, salesarea sa, route ro, routestop rs
, languages lan, systemuser curr, reportparam rp
where w.customer_id = cu.customer_id and wi.weareremployment_id = we.weareremployment_id and we.wearer_id = w.wearer_id
      and bu.businessunit_id = cu.defaultbusinessunit_id and sa.salesarea_id = cu.salesarea_id
      AND rs.customer_id = cu.customer_id and rs.route_id = ro.route_id
      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 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 businessunitsperusergroup bug WHERE bug.usergroup_id = curr.usergroup_id AND bug.businessunit_id = bu.businessunit_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))
union all
select 1 linetype--Layout per Customer with Billing Day something selected
, wi.dateinactive, wi.dateactive, wi.losschargedate
, 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
, 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)--*/'ORA11'
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.customer_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, getdateonly(wi.timestamp) timestamp
, rp.reportparam_id
from wearerinventory wi, wearer w, weareremployment we, customer cu, businessunit bu, salesarea sa, route ro, routestop rs
, CUSTOMERDELIVERYDAY cdd, day d
, languages lan, systemuser curr, reportparam rp
where w.customer_id = cu.customer_id and wi.weareremployment_id = we.weareremployment_id and we.wearer_id = w.wearer_id
      and bu.businessunit_id = cu.defaultbusinessunit_id and sa.salesarea_id = cu.salesarea_id
      and cu.customer_id = cdd.customer_id and cdd.day_id = d.day_id and cdd.typeofmerchadise = 2 --and cdd.deliverytype = 'B'
      AND rs.customer_id = cu.customer_id and rs.route_id = ro.route_id
      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 EXISTS (SELECT 1 FROM businessunitsperusergroup bug WHERE bug.usergroup_id = curr.usergroup_id AND bug.businessunit_id = bu.businessunit_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))
union all
select 2 linetype --Layout per Route OR Sales Area with Billing Day ALL
, wi.dateinactive, wi.dateactive, wi.losschargedate
, 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
, 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)--*/'ORA11'
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.customer_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, getdateonly(wi.timestamp) timestamp
, rp.reportparam_id
from wearerinventory wi, wearer w, weareremployment we, customer cu, businessunit bu, salesarea sa, route ro, routestop rs
, languages lan, systemuser curr, reportparam rp
where w.customer_id = cu.customer_id and wi.weareremployment_id = we.weareremployment_id and we.wearer_id = w.wearer_id
      and bu.businessunit_id = cu.defaultbusinessunit_id and sa.salesarea_id = cu.salesarea_id
      AND rs.customer_id = cu.customer_id and rs.route_id = ro.route_id
      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 EXISTS (SELECT 1 FROM businessunitsperusergroup bug WHERE bug.usergroup_id = curr.usergroup_id AND bug.businessunit_id = bu.businessunit_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))
union all
select 3 linetype --Layout per Route OR Sales Area with Billing Day something selected
, wi.dateinactive, wi.dateactive, wi.losschargedate
, 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
, 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)--*/'ORA11'
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.customer_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, getdateonly(wi.timestamp) timestamp
, rp.reportparam_id
from wearerinventory wi, wearer w, weareremployment we, customer cu, businessunit bu, salesarea sa, route ro, routestop rs
, CUSTOMERDELIVERYDAY cdd, day d
, languages lan, systemuser curr, reportparam rp
where w.customer_id = cu.customer_id and wi.weareremployment_id = we.weareremployment_id and we.wearer_id = w.wearer_id
      and bu.businessunit_id = cu.defaultbusinessunit_id and sa.salesarea_id = cu.salesarea_id
      and cu.customer_id = cdd.customer_id and cdd.day_id = d.day_id and cdd.typeofmerchadise = 2 --and cdd.deliverytype = 'B'
      AND rs.customer_id = cu.customer_id and rs.route_id = ro.route_id
      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 EXISTS (SELECT 1 FROM businessunitsperusergroup bug WHERE bug.usergroup_id = curr.usergroup_id AND bug.businessunit_id = bu.businessunit_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))

/
create or replace view V_ERSTEBANK_SMG
 (INVOICENUMBER, INVOICEDATE, QUANTITY, AMOUNT, DESCRIPTION, STREET, INVOICELINE_ID, IL_AMOUNT, PAYTHISAMOUNT)
as select ih.invoicenumber, ih.invoicedate, ccil.quantity, ccil.amount, ccl.description, ih.street, il.invoiceline_id, il.amount il_amount, ih.paythisamount
from invoiceheader ih, invoiceline il, costcenterinvoiceline ccil, costcenter_link ccl
where ih.invoiceheader_id = il.invoiceheader_id
      and il.invoiceline_id = ccil.invoiceline_id
      and ccil.costcenter_link_id = ccl.costcenter_link_id

/
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, MINORDERQTY, BOXQUANTITY, SUPPLIERPRODUCTCODE, SUPPLIERPRODUCTDESCRIPTION, SUPPLIERSIZECODE, PRODUCT_ID, SIZEDEFINITION_ID, SUPPLIERTYPE, SUPPLIER_ID, SUPPLIERPRODUCT_ID)
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.Minorderqty,
Supplierproduct.Boxquantity,
Supplierproductcode,
Supplierproductdescription,
Suppliersizecode,
Productsizepersupproduct.Product_Id,
Productsizepersupproduct.Sizedefinition_Id,
Suppliertype,
Supplier.Supplier_Id,
Supplierproduct.Supplierproduct_Id
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_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, address.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 = languages.language_id ) productDesc
, ( select reasoncode_desc.description from reasoncode_desc where reasoncode_desc.reasoncode_id = rc.reasoncode_id
  and reasoncode_desc.language_id = languages.language_id ) reasonDesc
, pnl.freeofchargereason_id, pnl.deliveredamount
, languages.language_id, cu.language_id customerLanguage_id, languages.code languageCode,
pn.processbusinessunit_id, procbu.code procbucode, procbu.description procbudesc,
pn.invoicebusinessunit_id, invbu.code invbucode, invbu.description invbudesc,
pn.internalprocessingbu_id,
(select intbu.code from businessunit intbu where pn.internalprocessingbu_id = intbu.businessunit_id) intbucode,
(select intbu.description from businessunit intbu where pn.internalprocessingbu_id  =intbu.businessunit_id) intbudesc,
ug.usergroup_id
from
  packingnote pn, status statusPN, distributionpoint dip, department dep, customer cu
, 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.
, product prd, sizedefinition sz, finishingmethod fm
, address, languages, businessunit procbu, businessunit invbu, usergroup ug
where
   pn.status_id = statusPN.status_id
    and statusPN.statustype = 'PN'
        and statusPN.code = '30'
and pn.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 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 pn.processbusinessunit_id=procbu.businessunit_id
and pn.invoicebusinessunit_id=invbu.businessunit_id
and 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_FSTFORWARD_LLG
 (CUSTOMERNUMBER, CUSTOMERNAME, BU_CODE, NOTENUMBER, DELIVERYDATE, ROUTENR, PG_CODE, PRODUCTCODE, PRODUCTDESC, SIZECODE, FMCODE, LANGUAGECODE, RC_CODE, DV_QTY)
as select c.customernumber,
       c.name customername,
       (select bu.code
          from businessunit bu
         where bu.businessunit_id = pn.processbusinessunit_id) bu_code,
       pn.notenumber,
       pn.deliverydate,
       (select r.routenumber from route r where r.route_id = pn.route_id) routenr,
       (select pg.code
          from productgroup pg
         where pg.productgroup_id = p.productgroup_id) pg_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 fmcode,
       l.code languagecode,
       (select rc.code from reasoncode rc where rc.reasoncode_id = dv.reasoncode_id) rc_code,
       dv.amount dv_qty
  from packingnote       pn,
       packingnoteline   pnl,
       distributionpoint dp,
       department        d,
       customer          c,
       product           p,
       sizedefinition    sd,
       finishingmethod   fm,
       languages         l,
       deliveryvariations dv
 where pn.distributionpoint_id = dp.distributionpoint_id
   and dp.department_id = d.department_id
   and d.customer_id = c.customer_id
   and 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 pn.distributionpoint_id = dv.distributionpoint_id
   and pn.packingnote_id = dv.packingnote_id
   and pnl.product_id = dv.product_id
   and pnl.sizedefinition_id = dv.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) --Processed
   and pn.deliverydate >= sysdate

/
create or replace view V_FSTNOTSCANNED_LLG
 (CUSTOMERNUMBER, CUSTOMERNAME, BU_CODE, NOTENUMBER, PRIMARYID, DELIVERYDATE, ROUTENR, PG_CODE, PRODUCTCODE, PRODUCTDESC, SIZECODE, FMCODE, TOBEDELIVEREDAMOUNT, DELIVEREDAMOUNT, LANGUAGECODE)
as select c.customernumber,
       c.name customername,
       (select bu.code
          from businessunit bu
         where bu.businessunit_id = pn.processbusinessunit_id) bu_code,
       pn.notenumber,
       bt.primaryid,
       pn.deliverydate,
       (select r.routenumber from route r where r.route_id = pn.route_id) routenr,
       (select pg.code
          from productgroup pg
         where pg.productgroup_id = p.productgroup_id) pg_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 fmcode,
       pnl.tobedeliveredamount,
       pnl.deliveredamount,
       l.code languagecode
  from packingnote       pn,
       bagtag            bt,
       packingnoteline   pnl,
       distributionpoint dp,
       department        d,
       customer          c,
       product           p,
       sizedefinition    sd,
       finishingmethod   fm,
       languages         l
 where pn.distributionpoint_id = dp.distributionpoint_id
   and dp.department_id = d.department_id
   and d.customer_id = c.customer_id
   and 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 pn.packingnote_id = bt.packingnote_id
   and pn.status_id not in (select s.status_id
                              from status s
                             where s.statustype = 'PN'
                               and s.code in (30, 40, 60)) --Processed or Cancelled or Prepackingnote

/
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_GARMENTCHARGES_VEN
 (INVOICEHEADER_ID, AMOUNT)
as select x.invoiceheader_id, sum(x.amount) amount
from(
select a.invoiceheader_id, sum ( a.amount ) amount
from outofcirculationhistory a
group by a.invoiceheader_id
union all
select b.invoiceheader_id, sum ( b.amount ) amount
from garmentsaleshistory b
group by b.invoiceheader_id
union all
select c.invoiceheader_id, sum ( c.quantity*c.prepcharge ) amount
from  issuehistory c
group by c.invoiceheader_id
union all
select d.invoiceheader_id, sum ( d.amount ) amount
from  printqueue d
group by d.invoiceheader_id
union all
select e.invoiceheader_id, sum ( e.unitprice + e.priceperminute ) amount
from  repairhistory e
group by e.invoiceheader_id
union all
select f.invoiceheader_id, sum ( f.amount ) amount
from  emblemhistory f
group by f.invoiceheader_id ) X
group by x.invoiceheader_id

/
create or replace view V_GARMENTCONTROLLIST_POS
 (ROUTECONTROL_ID, STOPNUMBER, WEARERNUMBER, WEARERNAME, DRIVINGDATE, CUSTOMERNUMBER, NAME, PLANT_CODE, ROUTENUMBER, DAY)
as select rc.routecontrol_id, st.stopnumber, we.wearernumber, we.fullname WearerName, rc.drivingdate
, cu.customernumber, cu.name, pl.code Plant_code, ro.routenumber, GETABSDAYNUMBER(rc.drivingdate) Day
from stop st, wearer we, routecontrol rc, customer cu, route ro, plant pl--, day da
where st.routecontrol_id = rc.routecontrol_id and st.customer_link_id = we.customer_id
and we.customer_id = cu.customer_id and rc.route_id = ro.route_id and ro.plant_id = pl.plant_id--and rc.drivingdate = da
and we.dateinactive > rc.drivingdate
and st.status not in (1, 2)

/
create or replace view V_GARMENTDELIVERY
 (DELIVERYDATE, WEEK, DAYDESC, ROUTENUMBER, ROUTEDESC, STOPNUMBER, CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERLEGALNAME, STREET, ZIPCODE, CITY, WEARERNUMBER, WEARERNAME, PRODUCTCODE, SIZECODE, PRODUCTDESC, SIZEDESC, TYPEOFMERCHANDISE, PRIMARYID, SCANTIMESTAMP, BUSINESSUNIT_ID, UNIQUEITEM_LINK_ID, NOTENUMBER, PLANTDEPARTMENTCODE, CUPBOARD, LOCKER, LOCKERSTATUS, LOCKER_REMARK, LOCKER_SORTADDRESS, LANGUAGECODE)
as select
  pn.deliverydate--, pn.daynumber
, pn.week week
, ( select day_desc.description from day_desc where day_desc.day_id = pn.daynumber
  and day_desc.language_id = languages.language_id ) dayDesc
, coalesce(route.routenumber, -1) routenumber, route.description routeDesc, pn.stopnumber
, cu.customer_id, cu.customernumber, cu.name customerName, cu.legalname customerLegalName
, address.Street, address.Zipcode, address.City
, coalesce(weylk.wearernumber, -1) wearernumber, weylk.wearername
, 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
, prd.typeofmerchandise
, 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
, GETDATEONLY( (SELECT MAX(DELIVERYSCAN.scantimestamp) FROM DELIVERYSCAN
               WHERE DELIVERYSCAN.BUSINESSUNIT_ID = DS.BUSINESSUNIT_ID
                 AND DELIVERYSCAN.UNIQUEITEM_LINK_ID = DS.UNIQUEITEM_LINK_ID
                 and GETDATEONLY(DELIVERYSCAN.scantimestamp) <= pn.deliverydate)) scantimestamp--, ds.scantimestamp scanDateTime
, ds.BUSINESSUNIT_ID, ds.UNIQUEITEM_LINK_ID
, pn.notenumber, plantdepartment.code plantdepartmentCode
, locker.bank cupboard, locker.locker
, locker.lockerstatus, locker.remark locker_remark, locker.sortaddress locker_sortaddress
, languages.code languageCode
from
  deliveryscan ds
    left outer join (weareremployment_link weylk left outer join
               (weareremployment we left outer join locker on locker.locker_id = we.locker_id)
               on we.weareremployment_id = weylk.weareremployment_id)
         on ds.weareremployment_link_id = weylk.weareremployment_link_id
, packingnote pn
    left outer join route on (pn.route_id = route.route_id and route.active = 'Y')
, uniqueitem_link uqlk, product prd, sizedefinition sz
, distributionpoint dip, department dep, customer cu
, plantdepartment
, STATUS, address , languages
where
    PN.STATUS_ID = STATUS.STATUS_ID
    AND STATUS.CODE = '30'
        AND STATUS.STATUSTYPE = 'PN'
AND ds.packingnote_id = pn.packingnote_id
and ds.uniqueitem_link_id = uqlk.uniqueitem_link_id
and ds.product_link_id = prd.product_id
and ds.sizedefinition_link_id = sz.sizedefinition_id
and pn.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 ds.plantdepartment_id = plantdepartment.plantdepartment_id
and cu.language_id = languages.language_id

/
create or replace view V_GARMENTDELIVERY_REI
 (DELIVERYDATE, WEEK, DAYDESC, ROUTENUMBER, ROUTEDESC, STOPNUMBER, CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERLEGALNAME, STREET, ZIPCODE, CITY, WEARERNUMBER, WEARERNAME, WEAREFUNCTIONCODE, WEAREFUNCTIONDESC, PRODUCTCODE, SIZECODE, PRODUCTDESC, TYPEOFMERCHANDISE, PRIMARYID, SCANTIMESTAMP, BUSINESSUNIT_ID, UNIQUEITEM_LINK_ID, NOTENUMBER, PLANTDEPARTMENTCODE, CUPBOARD, LOCKER, LOCKERSTATUS, LOCKER_REMARK, LOCKER_SORTADDRESS, LANGUAGECODE)
as select
  pn.deliverydate--, pn.daynumber
, pn.week week
, ( select day_desc.description from day_desc where day_desc.day_id = pn.daynumber
  and day_desc.language_id = languages.language_id ) dayDesc
, coalesce(route.routenumber, -1) routenumber, route.description routeDesc, pn.stopnumber
, cu.customer_id, cu.customernumber, cu.name customerName, cu.legalname customerLegalName
, address.Street, address.Zipcode, address.City
, coalesce(weylk.wearernumber, -1) wearernumber, weylk.wearername
, (select wf.code from wearerfunction wf where wf.wearerfunction_id = we.wearerfunction_id) wearefunctioncode
, (select wf.description from wearerfunction wf where wf.wearerfunction_id = we.wearerfunction_id) wearefunctiondesc
, 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
, prd.typeofmerchandise
, 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
, GETDATEONLY( (SELECT MAX(DELIVERYSCAN.scantimestamp) FROM DELIVERYSCAN
               WHERE DELIVERYSCAN.BUSINESSUNIT_ID = DS.BUSINESSUNIT_ID
                 AND DELIVERYSCAN.UNIQUEITEM_LINK_ID = DS.UNIQUEITEM_LINK_ID
                 and GETDATEONLY(DELIVERYSCAN.scantimestamp) <= pn.deliverydate)) scantimestamp--, ds.scantimestamp scanDateTime
, ds.BUSINESSUNIT_ID, ds.UNIQUEITEM_LINK_ID
, pn.notenumber, plantdepartment.code plantdepartmentCode
, locker.bank cupboard, locker.locker
, locker.lockerstatus, locker.remark locker_remark, locker.sortaddress locker_sortaddress
, languages.code languageCode
from
  deliveryscan ds
    left outer join (weareremployment_link weylk left outer join
               (weareremployment we left outer join locker on locker.locker_id = we.locker_id)
               on we.weareremployment_id = weylk.weareremployment_id)
         on ds.weareremployment_link_id = weylk.weareremployment_link_id
, packingnote pn
    left outer join route on (pn.route_id = route.route_id and route.active='Y')
, uniqueitem_link uqlk, product prd, sizedefinition sz
, distributionpoint dip, department dep, customer cu
, plantdepartment
, STATUS, address , languages
where
    PN.STATUS_ID = STATUS.STATUS_ID
    AND STATUS.CODE = '30'
        AND STATUS.STATUSTYPE = 'PN'
AND ds.packingnote_id = pn.packingnote_id
and ds.uniqueitem_link_id = uqlk.uniqueitem_link_id
and ds.product_link_id = prd.product_id
and ds.sizedefinition_link_id = sz.sizedefinition_id
and pn.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 ds.plantdepartment_id = plantdepartment.plantdepartment_id
and cu.language_id = languages.language_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 GETDATEONLY(scan.scantimestamp) >= we.dateactive
                   and GETDATEONLY(scan.scantimestamp)<= we.dateinactive),'N') WearerActiveStatus
, scan.scantimestamp  --, GETDATEONLY(scan.scantimestamp) scantimestamp, GETDATEONLY(we.dateactive), GETDATEONLY(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 --, GETDATEONLY(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_GARMENTEXCHANGEFREQUENCY_CBD
 (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, MAXINVENTORY)
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 GETDATEONLY(scan.scantimestamp) >= we.dateactive
                   and GETDATEONLY(scan.scantimestamp)<= we.dateinactive),'N') WearerActiveStatus
, scan.scantimestamp  --, GETDATEONLY(scan.scantimestamp) scantimestamp, GETDATEONLY(we.dateactive), GETDATEONLY(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,Wei.Maxinventory
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 --, GETDATEONLY(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,wei.maxinventory
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_GARMENTHISTORYCC
 (YEAR, WEEK, DEPARTMENTNUMBER, DEPARTMENTDESC, WEARERNUMBER, WEARERNAME, PRODUCTCODE, PRODUCTDESC, SIZECODE, QUANTITY, SALESPRICE, INVOICEHEADER_ID, LANGUAGECODE, DISCOUNTPERCENTAGE, AMOUNT, CC_CODE_DESC)
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,
 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_GARMENTHISTORY_NAF
 (YEAR, WEEK, WEAREREMPLOYMENT_ID, DEPARTMENTNUMBER, DEPARTMENTDESC, WEARERNUMBER, WEARERNAME, PRODUCTCODE, PRODUCTDESC, SIZECODE, QUANTITY, SALESPRICE, INVOICEHEADER_ID, LANGUAGECODE, LANGUAGE_ID, DISCOUNTPERCENTAGE, AMOUNT, REFERENCENUMBER)
as select
 a.year, a.week, w.weareremployment_id,
 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,
 get_wo_refno(w.weareremployment_id, a.invoiceheader_id) referencenumber
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_GARMENTSINCIRCPERCUST_LTS
 (BILLNUMBER, BILLNAME, BILLSTREET, BILLZIP, BILLCITY, DELNUMBER, DELNAME, DELSTREET, DELZIP, DELCITY, DEPARTMENTNUMBER, DEPARTMENTDESC, PRODUCTCODE, SIZECODE, FINMETHCODE, PRODUCTDESC, FABRICDESC, CUSTOMEROWNED, STATUSCODE, LANGUAGECODE, BUCODE, BUDESCRIPTION)
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 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
, (select bu.code from businessunit bu where bu.businessunit_id = ui.businessunit_id) bucode
, (select bu.description from businessunit bu where bu.businessunit_id = ui.businessunit_id) budescription
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
 (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)
as select cu.customer_id,
  cu.customernumber, cu.name CustomerName, address.city CustomerCyty, dept.departmentnumber
, dept.description DepartmentDescription, flag.code Flagcode
, (select description from flag_desc where flag_desc.flag_id = flag.flag_id
  and flag_desc.language_id = languages.language_id )FlagDescription
, wearer.wearernumber, wearer.fullname wearerFullname, wearerfunction.code wearerfunction
, weareremployment.sequencenumber EmploymentNumber
, uq.primaryid IDcode, 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
, sizedefinition.code sizedefinitionCode, finishingmethod.code finishingmethodCode
, (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sizedefinition.sizedefinition_id
  and sdd.language_id = languages.language_id) SizeDescription
, (select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = finishingmethod.finishingmethod_id
  and fmd.language_id = languages.language_id) finishingmethodDescription
, coalesce(uqfi.lastissuedate, GETABSMAXDATE()) lastissuedate
, coalesce(uq.lastscandate, GETABSMAXDATE()) lastscandate
, coalesce(uniqueitemflag.startdate, GETABSMAXDATE()) StartFlag
, uniqueitemflag.freetextitem
, (select count (uf.flag_id) from uniqueitemflag uf where uf.uniqueitem_id = uq.uniqueitem_id) CountFlags
, uq.businessunit_id, uq.timestamp
, coalesce(GETDATEONLY(uniqueitemflag.timestamp), GETABSMAXDATE()) DatePutFlag, languages.code languagecode
, (select su.username from systemuser su where su.systemuser_id = uq.systemuser_id) system_user
from
uniqueitem uq
  left outer join finishingmethod on uq.finishingmethod_id = finishingmethod.finishingmethod_id
, uniqueitemfixedinfo uqfi, uniqueitemnonpool, uniqueitemflag, product prd, sizedefinition
, wearer, weareremployment
  left outer join wearerfunction on weareremployment.wearerfunction_id = wearerfunction.wearerfunction_id
, flag, customer cu, address, department dept, DISTRIBUTIONPOINT DIP, languages
where
    uq.uniqueitem_id = uqfi.uniqueitem_id
and uq.uniqueitem_id = uniqueitemnonpool.uniqueitem_id
    and uniqueitemnonpool.weareremployment_id = weareremployment.weareremployment_id
        AND WEAREREMPLOYMENT.DISTRIBUTIONPOINT_ID = DIP.DISTRIBUTIONPOINT_ID
            AND DIP.DEPARTMENT_ID = DEPT.DEPARTMENT_ID
        and weareremployment.wearer_id = wearer.wearer_id
            and wearer.customer_id = cu.customer_id
                and cu.customer_id = dept.customer_id
                and cu.visitaddress_id = address.address_id
and uq.uniqueitem_id = uniqueitemflag.uniqueitem_id
    and uniqueitemflag.flag_id = flag.flag_id
and uq.product_id = prd.product_id
and uq.sizedefinition_id = sizedefinition.sizedefinition_id

/
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, GETDATEONLY(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)
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(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(*) 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
, GETDATEONLY(uq.lastscandate) lastscandate, GETDATEONLY(uq.lastoutscandate) lastoutscandate, GETDATEONLY(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
,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, we.firstname wearerfirstname
, GETDATEDIFF(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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
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
, 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 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(*) 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
, 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,
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, we.firstname wearerfirstname
, GETDATEDIFF(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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
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
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(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(*) FROM UNIQUEITEMFLAG uf, automaticflag af WHERE uf.UNIQUEITEM_ID = uq.UNIQUEITEM_ID and af.flag_id = uf.flag_id
           and uf.startdate <= GETCURRENTDATE() 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 <= GETCURRENTDATE() 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
, GETDATEONLY(uq.lastscandate) lastscandate, GETDATEONLY(uq.lastoutscandate) lastoutscandate,  GETDATEONLY(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
,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, we.firstname wearerfirstname
, (-1)*GETDATEDIFF(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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
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
, 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
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 <= GETCURRENTDATE() and af.automaticflag_id in (12, 4, 5, 7, 2) )

/
create or replace view V_GARMENTSPERWEARER_CBD
 (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
, INTPROCESSBUSINESSUNIT_ID, CITY, DEFAULTBUSINESSUNIT_ID, WEARERNUMBER, WEARERNAME, WEARERSEARCHNAME, WEARERACTIVE, WEARERDATEACTIVE, WEARERDATEINACTIVE, LANGUAGECODE, LANGUAGE_ID, CUSTOMERLANGUAGE_ID, SUBSTITUTEYN, QUALITYGRADE_CODE, LEASEWEEKS)
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 ,
    COALESCE(suq.secondaryid, 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 ,
    GETDATEONLY(uq.lastscandate) lastscandate,
    GETDATEONLY(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,
    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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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
  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 secondaryuniqueitem suq
  ON uq.UNIQUEITEM_ID = suq.uniqueitem_id
  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 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,
    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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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
  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
  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 ,
    COALESCE(suq.secondaryid, 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        <= GETCURRENTDATE()
    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        <= GETCURRENTDATE()
    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 ,
    GETDATEONLY(uq.lastscandate) lastscandate,
    GETDATEONLY(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,
    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 ,
    (-1)*GETDATEDIFF(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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
  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 secondaryuniqueitem suq
  ON uq.uniqueitem_id = suq.uniqueitem_id
  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
  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        <= GETCURRENTDATE()
    AND af.automaticflag_id IN (12, 4, 5, 7, 2)
    )

/
create or replace view V_GARMENTSPERWEARER_DRE
 (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
, INTPROCESSBUSINESSUNIT_ID, CITY, DEFAULTBUSINESSUNIT_ID, WEARERNUMBER, WEARERNAME, WEARERSEARCHNAME, WEARERACTIVE, WEARERDATEACTIVE, WEARERDATEINACTIVE, LANGUAGECODE, LANGUAGE_ID, CUSTOMERLANGUAGE_ID, SUBSTITUTEYN, QUALITYGRADE_CODE, LEASEWEEKS, LAST5SCANS, WEEKSINCIRC)
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 max(mo.code) from uniqueitemmodification um, modification mo
   where um.uniqueitem_id=uq.uniqueitem_id and mo.modification_id = um.modification_id) modifications
, r.code reason, uq.customerowned, uqnp.freeextragarment
, GETDATEONLY(uq.lastscandate) lastscandate, GETDATEONLY(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,
 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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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 CAST( listagg(trunc(sc.scantimestamp),'  ') within group(order by sc.scantimestamp) AS VARCHAR2(60))
  from scan sc where sc.primaryid = uq.primaryid and sc.transactiontype_id = 2 --outscans
   and sc.customer_link_id = cu.customer_id and sc.weareremployment_link_id = wey.weareremployment_id ) Last5Scans
, round(0.5+(sysdate-uqfx.lastissuedate)/7) WeeksInCirc
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 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
, null 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,
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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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
, ' ' Last5Scans
, 0 WeeksInCirc
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
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 <= GETCURRENTDATE() 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 <= GETCURRENTDATE() and af.automaticflag_id in (12, 4, 5, 7, 2)) uiflagcode
, ( select max(mo.code) from uniqueitemmodification um, modification mo
   where um.uniqueitem_id=uq.uniqueitem_id and mo.modification_id = um.modification_id) modifications
, r.code reason, uq.customerowned, uqnp.freeextragarment
, GETDATEONLY(uq.lastscandate) lastscandate, GETDATEONLY(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,
 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
, (-1)*GETDATEDIFF(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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
, (select CAST( listagg(trunc(sc.scantimestamp),'  ') within group(order by sc.scantimestamp) AS VARCHAR2(60))
  from scan sc where sc.primaryid = uq.primaryid and sc.transactiontype_id = 2 --outscans
   and sc.customer_link_id = cu.customer_id and sc.weareremployment_link_id = wey.weareremployment_id ) Last5Scans
, round(0.5+(sysdate-uqfx.lastissuedate)/7) WeeksInCirc
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
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 <= GETCURRENTDATE() and af.automaticflag_id in (12, 4, 5, 7, 2) )

/
create or replace view V_GARMENTSPERWEARER_LST
 (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, SCANDATE3, SCANDATE2, SCANDATE1)
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
, 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(*) 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
, GETDATEONLY(uq.lastscandate) lastscandate, GETDATEONLY(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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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 max(sc.scantimestamp)
    from   scan sc
    where  uq.primaryid = sc.primaryid
       and sc.transactiontype_id in (2, 8, 9, 95, 540, 541, 542, 543)
       and sc.scantimestamp < ( select max(sc2.scantimestamp)
                                from   scan sc2
                                where  sc2.primaryid = sc.primaryid
                                   and sc2.transactiontype_id in (2, 8, 9, 95, 540, 541, 542, 543)
                                   and sc2.scantimestamp < ( select max(sc3.scantimestamp)
                                                             from   scan sc3
                                                             where  sc3.primaryid = sc2.primaryid
                                                                and sc3.transactiontype_id in (2, 8, 9, 95, 540, 541, 542, 543)
                                                           and sc3.customer_link_id=cu.customer_id
                                                           )
                                                           and sc2.customer_link_id=cu.customer_id
                              )
                              and sc.customer_link_id=cu.customer_id
  ) scandate3
, ( select max(sc.scantimestamp)
    from   scan sc
    where  uq.primaryid = sc.primaryid
       and sc.transactiontype_id in (2, 8, 9, 95, 540, 541, 542, 543)
       and sc.scantimestamp < ( select max(sc2.scantimestamp)
                                from   scan sc2
                                where  sc2.primaryid = sc.primaryid
                                   and sc2.transactiontype_id in (2, 8, 9, 95, 540, 541, 542, 543)
                                   and sc2.customer_link_id=cu.customer_id
                              )
       and sc.customer_link_id=cu.customer_id
  ) scandate2
, ( select max(sc.scantimestamp)
    from   scan sc
    where  uq.primaryid = sc.primaryid
       and sc.transactiontype_id in (2, 8, 9, 95, 540, 541, 542, 543)
       and sc.customer_link_id=cu.customer_id
  ) scandate1
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
, 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
  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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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
, null scandate3
, null scandate2
, null scandate1
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_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
, GETDATEONLY(uq.lastscandate) lastscandate, GETDATEONLY(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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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)
       */
 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,
                                             we.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,
                                                                         we.deliverypoint_id)),999999),
                             r.plant_id, u.customerowned, 0)) 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,
                                                                              we.deliverypoint_id)),999999),
                                  r.plant_id, u.customerowned, 0)) 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.deliverypoint_id = delp.deliverypoint_id  -- HVH To do 8178 Remove clause
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 -- HVH To do 8178 Add clause
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_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
, GETDATEONLY(uq.lastscandate) lastscandate, GETDATEONLY(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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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_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_HEAVYSOILED_LLG
 (CUSTOMER_ID, DISTRIBUTIONPOINT_ID, BUCODE, CUSTOMERNUMBER, CUSTOMERNAME, CHAINCODE, PRODUCT_ID, PRODUCTCODE, PRODUCTDESC, SIZEDEFINITION_ID, SIZECODE, FMCODE, DELIVERYDATE, NOTENUMBER, GPLCODE, DELIVEREDQTY, HEAVYSOILEDQTY, PLPCHEAVYSOILPRICE, GENERALHEAVYSOILPRICE, LANGUAGECODE, CHARGEABLESTOCK)
as select c.customer_id,
dp.distributionpoint_id,
(select bu.code from businessunit bu where bu.businessunit_id = c.defaultbusinessunit_id) bucode,
c.customernumber,
c.name customername,
(select ch.code from chain ch where ch.chain_id = c.chain_id) chaincode,
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,
sd.sizedefinition_id,
sd.code sizecode,
fm.code fmcode,
dv.deliverydate,
pn.notenumber,
(select gpl.code from pricelistpercustomer plc, generalpricelist gpl, generalwashprice gwp where
               plc.generalpricelist_id = gpl.generalpricelist_id
               and plc.customer_id = c.customer_id
               and gpl.generalpricelist_id = gwp.generalpricelist_id
               and gwp.product_id = p.product_id
               and gwp.sizedefinition_id = sd.sizedefinition_id
               and gwp.finishingmethod_id = fm.finishingmethod_id
               and gwp.pricetype = 5
               and plc.priority = (select min(plc1.priority) from pricelistpercustomer plc1, generalwashprice gwp
                                   where plc1.customer_id = c.customer_id
                                   and gwp.generalpricelist_id = plc1.generalpricelist_id
                                   and gwp.pricetype = 5)
) gplcode,
(select sum(pnl.deliveredamount) from packingnoteline pnl where pnl.packingnote_id = pn.packingnote_id
                   and pnl.product_id = p.product_id
                   and pnl.sizedefinition_id = sd.sizedefinition_id
                   and pnl.finishingmethod_id = fm.finishingmethod_id) deliveredqty,
sum(dv.amount) heavysoiledqty,
(select cwp.price from customerwashprice cwp, productlistpercustomer plpc
               where cwp.productlistpercustomer_id = plpc.productlistpercustomer_id
               and 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 cwp.pricetype = 5) plpcheavysoilprice,
(select gwp.price from generalpricelist gpl, generalwashprice gwp where gpl.code = 'L-H/S'
               and gpl.generalpricelist_id = gwp.generalpricelist_id
               and gwp.product_id = p.product_id
               and gwp.sizedefinition_id = sd.sizedefinition_id
               and gwp.finishingmethod_id = fm.finishingmethod_id
               and gwp.pricetype = 5) generalheavysoilprice,
l.code languagecode,
(select sum(rqa.quantity) from rentalqtyadjustment rqa
               where rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
               and rqa.adjustmentdate <= sysdate
               and rqa.origin <> 2
               and rqa.sampleitem = 'N') chargeablestock
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
inner join finishingmethod fm on dv.finishingmethod_id = fm.finishingmethod_id
inner join packingnote pn on dv.packingnote_id = pn.packingnote_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
where dv.origin = 1 and dv.soilcountsubtype = 4
group by c.customer_id, dp.distributionpoint_id, c.defaultbusinessunit_id, c.customernumber, c.name, c.chain_id, p.product_id, p.code,
sd.sizedefinition_id, sd.code, fm.finishingmethod_id, fm.code, dv.deliverydate,
l.language_id, l.code, pn.packingnote_id, pn.notenumber, plpd.productlistperdistribpoint_id

/
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_INCREASES_DECREASES_LLG
 (DELIVERYDATE, PRODUCTGROUPCODE, PG_DESCRIPTION, LANGUAGECODE, PRODUCTCODE, PRODUCTDESC, SIZECODE, ORIGIN, REASON_CODE, DV_AMOUNT)
as select dv.deliverydate,
       pg.code productgroupcode,
       (select pg_desc.description from productgroup_desc pg_desc where pg_desc.productgroup_id = pg.productgroup_id and pg_desc.language_id = l.language_id) pg_description,
       l.code languagecode,
       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.origin,
       (select rc.code from reasoncode rc where rc.reasoncode_id = dv.reasoncode_id) reason_code,
       sum(dv.amount) dv_amount
from deliveryvariations dv,
     product p,
     sizedefinition sd,
     productgroup pg,
     languages l
where dv.product_id = p.product_id
and dv.sizedefinition_id = sd.sizedefinition_id
and p.productgroup_id = pg.productgroup_id
and dv.origin = 3
and dv.amount > 0
group by dv.deliverydate, pg.code, pg.productgroup_id, p.product_id, p.code, sd.code, dv.origin, dv.reasoncode_id, l.language_id, l.code
union
select dv.deliverydate,
       pg.code productgroupcode,
      (select pg_desc.description from productgroup_desc pg_desc where pg_desc.productgroup_id = pg.productgroup_id and pg_desc.language_id = l.language_id) pg_description,
       l.code languagecode,
       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.origin,
       (select rc.code from reasoncode rc where rc.reasoncode_id = dv.reasoncode_id) reason_code,
       sum(dv.amount) dv_amount
from deliveryvariations dv,
     product p,
     sizedefinition sd,
     productgroup pg,
     languages l
where dv.product_id = p.product_id
and dv.sizedefinition_id = sd.sizedefinition_id
and p.productgroup_id = pg.productgroup_id
and (dv.origin = 1
     or (dv.amount < 0 and dv.origin = 3)
     )
group by dv.deliverydate, pg.code, pg.productgroup_id, p.product_id, p.code, sd.code, dv.origin, dv.reasoncode_id, l.language_id, l.code

/
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(GETCURRENTDATE(),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(GETCURRENTDATE(), 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_INTERNALVALUECIRCINV_NLI
 (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 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(GETCURRENTDATE(),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
, 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 in ('20', '30') -- In Circulation, Assigned
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 ui.uniqueitem_id = uqnp.uniqueitem_id
    and uqnp.weareremployment_id = wey.weareremployment_id
        and wey.wearer_id = we.wearer_id
            and we.customer_id = cu.customer_id
and ui.businessunit_id = bu.businessunit_id
and bu.businessunit_id = cu.defaultbusinessunit_id
    and bu.plant_id = plant.plant_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 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(GETCURRENTDATE(), 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
, 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 ivh.nonuniqueitem_id = nui.nonuniqueitem_id
and nui.wearerinventory_id = weiv.wearerinventory_id
and weiv.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 weiv.sizedefinition_id = sz.sizedefinition_id
and weiv.weareremployment_id = wey.weareremployment_id
    and wey.wearer_id = we.wearer_id
            and we.customer_id = cu.customer_id
                and cu.defaultbusinessunit_id = bu.businessunit_id
                    and bu.plant_id = plant.plant_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(GETCURRENTDATE(),uqfx.lastissuedate)) / 7 ) weeksUsed
, ui.washestotal
, F_CEIL( coalesce(GETDATEDIFF(GETCURRENTDATE(),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_INTERNALVALUESTOCK_NLI
 (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)
as select distinct 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(GETCURRENTDATE(),uqfx.lastissuedate)) / 7 ) weeksUsed
, ui.washestotal
, F_CEIL( coalesce(GETDATEDIFF(GETCURRENTDATE(),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
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
, 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 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 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, srg.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
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
, reportparam rp, currency cy, languages
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 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
    )

/
create or replace view V_INTERNETORDERHEADER
 (INTERNETORDER_ID, STATUS, ORDERDATE, ORDERDATE_WEEKNUMBER, ORDERDATE_DAY_DESC, DISTRIBUTIONPOINT_LINK_ID, DISTRIBUTIONPOINTNUMBER, DISTRIBPOINT_DESC, DISTRIBPOINT_ACTIVE, DEPARTMENT_ID, DEPARTMENTNUMBER, DEPARTMENT_DESC, DEPARTMENT_OCCUPANCY, DEPARTMENT_ACTIVE, SHOWWEBORDERTOTALS, PLANT_CODE, PLANT_NAME, BU_CODE, BU_DESCRIPTION)
as SELECT IO.INTERNETORDER_ID,
       IO.STATUS,
       IO.ORDERDATE,
       GETISOWEEK(IO.ORDERDATE) ORDERDATE_WEEKNUMBER,
       CAST(GETDAYDESCRIPTION(IO.ORDERDATE) AS VARCHAR2(30)) ORDERDATE_DAY_DESC,
       IO.DISTRIBUTIONPOINT_LINK_ID,
       DIP.DISTRIBUTIONPOINTNUMBER,
       DIP.DESCRIPTION DISTRIBPOINT_DESC,
       DIP.ACTIVE DISTRIBPOINT_ACTIVE,
       DIP.DEPARTMENT_ID,
       DEP.DEPARTMENTNUMBER,
       DEP.DESCRIPTION DEPARTMENT_DESC,
       DEP.OCCUPANCY DEPARTMENT_OCCUPANCY,
       DEP.ACTIVE DEPARTMENT_ACTIVE,
       (SELECT SS.VALUE
          FROM SYSTEMSETTING SS
         WHERE SS.PLANT_ID = P.PLANT_ID
           AND SS.NAME = 'SHOWWEBORDERTOTALS') SHOWWEBORDERTOTALS,
       P.CODE PLANT_CODE,
       P.NAME PLANT_NAME,
       BU.CODE BU_CODE,
       BU.DESCRIPTION BU_DESCRIPTION
  FROM INTERNETORDER IO
  JOIN DISTRIBUTIONPOINT DIP
    ON IO.DISTRIBUTIONPOINT_LINK_ID = DIP.DISTRIBUTIONPOINT_ID
  JOIN DEPARTMENT DEP
    ON DIP.DEPARTMENT_ID = DEP.DEPARTMENT_ID
  join CUSTOMER C
    ON DEP.CUSTOMER_ID = C.CUSTOMER_ID
  join BUSINESSUNIT BU
    on C.DEFAULTBUSINESSUNIT_ID = BU.BUSINESSUNIT_ID
  JOIN PLANT P
    on BU.PLANT_ID = P.PLANT_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 (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, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDEFINITION_LINK_ID, SIZE_CODE, SIZE_DESC, FINISHINGMETHOD_ID, FINMETH_CODE, FINMETH_DESC, TYPE, QUANTITY, FIXEDAMOUNT, DELIVERYVARIATIONS_ID, PN_STATUS_CODE, PN_NOTENUMBER, NORMSTOCKAMOUNT, STANDARDDELIVERYAMOUNT, SYSTEMUSER_ID, TIMESTAMP, OCCUPANCYRELATED, LANGUAGE_CODE, SEQ)
as select ioline.internetorder_id, ioline.internetorderline_id,
       ioline.product_link_id, ioline.productcode, ioline.productdescription,
       ioline.sizedefinition_link_id, s.code size_code,
       (select sd.description from sizedefinition_desc sd
         where  sd.sizedefinition_id = ioline.sizedefinition_link_id  and sd.language_id = l.language_id) size_desc,
       ioline.finishingmethod_id, f.code finmeth_code,
       (select fd.description from finishingmethod_desc fd
         where  fd.finishingmethod_id = ioline.finishingmethod_id and fd.language_id = l.language_id) finmeth_desc,
       ioline.type, ioline.quantity, ioline.fixedamount,
       ioline.deliveryvariations_id,
       (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, 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_notenumber,
       ioline.normstockamount, ioline.standarddeliveryamount,
       ioline.systemuser_id, ioline.timestamp, p.occupancyrelated,
       l.code language_code,
(select dp.COUNTSEQUENCE from distributionpoint_link dl,
                                 productlistperdistribpoint dp
       where io.distributionpoint_link_id = dl.distributionpoint_link_id
       and dl.distributionpoint_id = dp.distributionpoint_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   sizedefinition s, finishingmethod f, product p,
      internetorder io,
       internetorderline ioline, languages l
where  ioline.sizedefinition_link_id = s.sizedefinition_id
and    ioline.finishingmethod_id = f.finishingmethod_id
and    ioline.product_link_id = p.product_id
and  ioline.internetorder_id = io.internetorder_id

/
create or replace view V_INTERNETORDERLINE_ANG
 (INTERNETORDER_ID, INTERNETORDERLINE_ID, PRODUCT_LINK_ID, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDEFINITION_LINK_ID, SIZE_CODE, SIZE_DESC, FINISHINGMETHOD_ID, FINMETH_CODE, FINMETH_DESC, TYPE, QUANTITY, FIXEDAMOUNT, DELIVERYVARIATIONS_ID, PN_NOTENUMBER, PN_STATUS_CODE, NORMSTOCKAMOUNT, STANDARDDELIVERYAMOUNT, SYSTEMUSER_ID, TIMESTAMP, OCCUPANCYRELATED, BUNDLEQTY, LANGUAGE_CODE, ORDERSEQ)
as select ioline.internetorder_id, ioline.internetorderline_id,
       ioline.product_link_id, ioline.productcode, ioline.productdescription,
       ioline.sizedefinition_link_id, s.code size_code,
       (select sd.description from sizedefinition_desc sd
          where sd.sizedefinition_id = ioline.sizedefinition_link_id and sd.language_id = l.language_id) size_desc,
       ioline.finishingmethod_id, f.code finmeth_code,
       (select fd.description from finishingmethod_desc fd
          where fd.finishingmethod_id = ioline.finishingmethod_id and fd.language_id = l.language_id) finmeth_desc,
       ioline.type, ioline.quantity, ioline.fixedamount,
       ioline.deliveryvariations_id,
       (select pn.notenumber from packingnote pn, deliveryvariations dv
       where ioline.deliveryvariations_id = dv.deliveryvariations_id
       and dv.packingnote_id = pn.packingnote_id) pn_notenumber,
       (select s.code from packingnote pn, deliveryvariations dv, status s
       where ioline.deliveryvariations_id = dv.deliveryvariations_id
       and dv.packingnote_id = pn.packingnote_id
       and pn.status_id = s.status_id) pn_status_code,
       --status.code pn_status_code, pn.notenumber pn_notenumber,
       ioline.normstockamount, ioline.standarddeliveryamount,
       ioline.systemuser_id, ioline.timestamp, p.occupancyrelated,
       F_GET_BUNDLE_QTY_ANG(bu.plant_id, c.customer_id, ioline.product_link_id, ioline.sizedefinition_link_id,
                                       ioline.finishingmethod_id, io.orderdate, 'N', 'N') bundleQty,
       l.code language_code
, (select pldp.countsequence from productlistperdistribpoint pldp where pldp.distributionpoint_id = dp.distributionpoint_id
and pldp.product_id = p.product_id and pldp.sizedefinition_id = s.sizedefinition_id and pldp.finishingmethod_id = f.finishingmethod_id
) OrderSeq
from  internetorder io, distributionpoint dp, department d,
      sizedefinition s, finishingmethod f, product p,
      internetorderline ioline
 --             left outer join (deliveryvariations dv left outer join
  --                                (packingnote pn left outer join status
 --                                   on pn.status_id = status.status_id)
 --                              on dv.packingnote_id = pn.packingnote_id)
 --             on ioline.deliveryvariations_id = dv.deliveryvariations_id
      , languages l
      , customer c, businessunit bu
where io.internetorder_id = ioline.internetorder_id and
      io.distributionpoint_link_id = dp.distributionpoint_id and
      dp.department_id = d.department_id and
      ioline.sizedefinition_link_id = s.sizedefinition_id and
      ioline.finishingmethod_id = f.finishingmethod_id and
      ioline.product_link_id = p.product_id and
      d.customer_id = c.customer_id and
      c.defaultbusinessunit_id = bu.businessunit_id

/
create or replace view V_INTERNETORDERLINE_DUK
 (INTERNETORDER_ID, INTERNETORDERLINE_ID, PRODUCT_LINK_ID, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDEFINITION_LINK_ID, SIZE_CODE, SIZE_DESC, FINISHINGMETHOD_ID, FINMETH_CODE, FINMETH_DESC, TYPE, QUANTITY, FIXEDAMOUNT, DELIVERYVARIATIONS_ID, PN_NOTENUMBER, PN_STATUS_CODE, NORMSTOCKAMOUNT, STANDARDDELIVERYAMOUNT, SYSTEMUSER_ID, TIMESTAMP, OCCUPANCYRELATED, BUNDLEQTY, LANGUAGE_CODE, ORDERSEQ)
as select ioline.internetorder_id, ioline.internetorderline_id,
       ioline.product_link_id, ioline.productcode, ioline.productdescription,
       ioline.sizedefinition_link_id, s.code size_code,
       (select sd.description from sizedefinition_desc sd
          where sd.sizedefinition_id = ioline.sizedefinition_link_id and sd.language_id = l.language_id) size_desc,
       ioline.finishingmethod_id, f.code finmeth_code,
       (select fd.description from finishingmethod_desc fd
          where fd.finishingmethod_id = ioline.finishingmethod_id and fd.language_id = l.language_id) finmeth_desc,
       ioline.type, ioline.quantity, ioline.fixedamount,
       ioline.deliveryvariations_id,
       (select pn.notenumber from packingnote pn, deliveryvariations dv
       where ioline.deliveryvariations_id = dv.deliveryvariations_id
       and dv.packingnote_id = pn.packingnote_id) pn_notenumber,
       (select s.code from packingnote pn, deliveryvariations dv, status s
       where ioline.deliveryvariations_id = dv.deliveryvariations_id
       and dv.packingnote_id = pn.packingnote_id
       and pn.status_id = s.status_id) pn_status_code,
       --status.code pn_status_code, pn.notenumber pn_notenumber,
       ioline.normstockamount, ioline.standarddeliveryamount,
       ioline.systemuser_id, ioline.timestamp, p.occupancyrelated,
       F_GET_BUNDLE_QTY_ANG(bu.plant_id, c.customer_id, ioline.product_link_id, ioline.sizedefinition_link_id,
                                       ioline.finishingmethod_id, io.orderdate, 'N', 'N') bundleQty,
       l.code language_code
, (select pldp.countsequence from productlistperdistribpoint pldp where pldp.distributionpoint_id = dp.distributionpoint_id
and pldp.product_id = p.product_id and pldp.sizedefinition_id = s.sizedefinition_id and pldp.finishingmethod_id = f.finishingmethod_id
) OrderSeq
from  internetorder io, distributionpoint dp, department d,
      sizedefinition s, finishingmethod f, product p,
      internetorderline ioline
 --             left outer join (deliveryvariations dv left outer join
  --                                (packingnote pn left outer join status
 --                                   on pn.status_id = status.status_id)
 --                              on dv.packingnote_id = pn.packingnote_id)
 --             on ioline.deliveryvariations_id = dv.deliveryvariations_id
      , languages l
      , customer c, businessunit bu
where io.internetorder_id = ioline.internetorder_id and
      io.distributionpoint_link_id = dp.distributionpoint_id and
      dp.department_id = d.department_id and
      ioline.sizedefinition_link_id = s.sizedefinition_id and
      ioline.finishingmethod_id = f.finishingmethod_id and
      ioline.product_link_id = p.product_id and
      d.customer_id = c.customer_id and
      c.defaultbusinessunit_id = bu.businessunit_id

/
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 GETDATEONLY(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_INVCLIENTLINE_DELDATES_LLG
 (DELIVERYDATE, INVOICELINE_ID)
as select distinct to_char(pn.deliverydate, 'dd Mon yyyy') deliverydate, il.invoiceline_id
                 from packingnote        pn,
                      packingnoteline    pnl,
                      invoiceline        il,
                      invoicelineproduct ilp
                where pn.packingnote_id = pnl.packingnote_id
                  and pnl.invoiceheader_id = il.invoiceheader_id
                  and il.invoiceline_id = ilp.invoiceline_id
                  and pnl.product_id = ilp.product_link_id
                  and pnl.sizedefinition_id = ilp.sizedefinition_link_id
                  and pnl.finishingmethod_id = ilp.finishingmethod_id
                  and il.invoicelinetype_id = 2

/
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_INVENTORYUSAGEANALYSIS4W_POS
 (BUSINESSUNIT, BU_DESCRIPTION, CUSTOMERNUMBER, CUSTOMERNAME, STREET, STREET2, CITY, STATE, ZIPCODE, WEARERNUMBER, DATEACTIVE, DATEINACTIVE, PRODUCTCODE, PRODUCTDESCRIPTION, SIZECODE, TOTALQTYDELIVERED, CIRCINVENTADJUSTMENTS, CIRCULATINGINVENTORY, REPLACEMENTS, REPLACEMENTSLOGGED, REPAIRPRODUCT, CHAIN_CODE)
as select /*+rule*/--l.language_id,
       bu.code businessunit, bu.description bu_description, c.customernumber, c.name customername, a.street,
       a.street2, a.city, a.state, a.zipcode, w.wearernumber, wi.dateactive, wi.dateinactive,
       p.code productcode,
       (select pd.description from product_desc pd where wi.product_id = pd.product_id and pd.language_id=c.language_id) productdescription
      , s.code sizecode,
       nvl((select count(1)
            from   uniqueitem u, uniqueitemnonpool un, deliveryscan ds, packingnote pn
            where  u.businessunit_id = c.defaultbusinessunit_id
            and    u.uniqueitem_id = un.uniqueitem_id
            and    un.weareremployment_id = wi.weareremployment_id
            and    u.product_id = wi.product_id
            and    u.sizedefinition_id = wi.sizedefinition_id
            and    u.finishingmethod_id = wi.finishingmethod_id
            and    ds.packingnote_id is not null
            and    ds.uniqueitem_link_id = u.uniqueitem_id
            and    ds.packingnote_id = pn.packingnote_id
            and    pn.deliverydate between trunc(sysdate) - (4 * 7) and trunc(sysdate)), 0) totalqtydelivered,
       (nvl((select sum(ih.quantity)
             from   issuehistory ih, scan sc
             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    ih.incircdate between trunc(sysdate) - (4 * 7) and trunc(sysdate)
             and ih.uniqueitem_link_id = sc.uniqueitem_link_id
             and sc.scantimestamp = (select max(sc2.scantimestamp) from scan sc2 where sc2.uniqueitem_link_id = ih.uniqueitem_link_id
                                    and sc2.scantimestamp between trunc(sysdate) - (4 * 7) and trunc(sysdate))), 0) -
        nvl((select sum(oh.quantity)
             from   outofcirculationhistory oh
             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    oh.outofcircdate between trunc(sysdate) - (4 * 7) and trunc(sysdate)), 0)) circinventadjustments,
       (wi.circinventory + wi.freeofchargeqty -
        nvl((select sum(ih.quantity)
             from   issuehistory ih
             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    ih.incircdate > trunc(sysdate)), 0) +
        nvl((select sum(oh.quantity)
             from   outofcirculationhistory oh
             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    oh.outofcircdate > trunc(sysdate)), 0)) circulatinginventory,
       nvl((select sum(ih.quantity)
            from   issuehistory ih, workorder wo
            where  ih.processbusinessunit_id = c.defaultbusinessunit_id
            and    ih.weareremployment_link_id = wi.weareremployment_id
            and    ih.product_link_id = wi.product_id
            and    ih.sizedefinition_link_id = wi.sizedefinition_id
            and    wo.workorder_id = ih.workorder_id
            and    wo.replacement = 'Y'
            and    ih.incircdate between trunc(sysdate) - (4 * 7) and trunc(sysdate)), 0) replacements,
       nvl((select count(1)
            from   uniqueitem u, uniqueitemnonpool un, uniqueitemflag uf, automaticflag af
            where  u.businessunit_id = c.defaultbusinessunit_id
            and    u.uniqueitem_id = un.uniqueitem_id
            and    un.weareremployment_id = wi.weareremployment_id
            and    u.product_id = wi.product_id
            and    u.sizedefinition_id = wi.sizedefinition_id
            and    u.finishingmethod_id = wi.finishingmethod_id
            and    u.uniqueitem_id = uf.uniqueitem_id
            and    uf.flag_id = af.flag_id
            and    af.automaticflag_id = 4
            and    uf.startdate between trunc(sysdate) - (4 * 7) and trunc(sysdate)), 0) replacementslogged,
       nvl((select count(1)
            from   repairhistory rh, uniqueitem u
            where  rh.weareremployment_link_id = wi.weareremployment_id
            and    rh.uniqueitem_link_id = u.uniqueitem_id
            and    u.product_id = wi.product_id
            and    u.sizedefinition_id = wi.sizedefinition_id
            and    rh.product_link_id = wi.product_id
            and    rh.repairdate between trunc(sysdate) - (4 * 7) and trunc(sysdate)), 0) repairproduct
, (select ch.code from chain ch where c.chain_id = ch.chain_id) chain_code
from   wearerinventory wi, weareremployment we, wearer w, customer c, address a, --languages l,
       product p, sizedefinition s, businessunit bu
where  wi.weareremployment_id = we.weareremployment_id
and    we.wearer_id = w.wearer_id
and    w.customer_id = c.customer_id
and    c.defaultbusinessunit_id = bu.businessunit_id
and    c.visitaddress_id = a.address_id
and    wi.product_id = p.product_id
and    wi.sizedefinition_id = s.sizedefinition_id
and    wi.dateactive <= trunc(sysdate) AND (wi.dateinactive is null or wi.dateinactive >=  trunc(sysdate))--order  by c.customernumber, p.code, s.code

/
create or replace view V_INVENTORYUSAGEANALYSIS8W_POS
 (BUSINESSUNIT, BU_DESCRIPTION, CUSTOMERNUMBER, CUSTOMERNAME, STREET, STREET2, CITY, STATE, ZIPCODE, WEARERNUMBER, DATEACTIVE, DATEINACTIVE, PRODUCTCODE, PRODUCTDESCRIPTION, SIZECODE, TOTALQTYDELIVERED, CIRCINVENTADJUSTMENTS, CIRCULATINGINVENTORY, REPLACEMENTS, REPLACEMENTSLOGGED, REPAIRPRODUCT)
as select --l.language_id,
       bu.code businessunit, bu.description bu_description, c.customernumber, c.name customername, a.street,
       a.street2, a.city, a.state, a.zipcode, w.wearernumber, wi.dateactive, wi.dateinactive,
       p.code productcode,
       (select pd.description from product_desc pd where wi.product_id = pd.product_id and pd.language_id=c.language_id) productdescription
      , s.code sizecode,
       nvl((select count(1)
            from   uniqueitem u, uniqueitemnonpool un, deliveryscan ds, packingnote pn
            where  u.businessunit_id = c.defaultbusinessunit_id
            and    u.uniqueitem_id = un.uniqueitem_id
            and    un.weareremployment_id = wi.weareremployment_id
            and    u.product_id = wi.product_id
            and    u.sizedefinition_id = wi.sizedefinition_id
            and    u.finishingmethod_id = wi.finishingmethod_id
            and    ds.packingnote_id is not null
            and    ds.uniqueitem_link_id = u.uniqueitem_id
            and    ds.packingnote_id = pn.packingnote_id
            and    pn.deliverydate between trunc(sysdate) - (8 * 7) and trunc(sysdate)), 0) totalqtydelivered,
       (nvl((select sum(ih.quantity)
             from   issuehistory ih, scan sc
             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    ih.incircdate between trunc(sysdate) - (8 * 7) and trunc(sysdate)
             and sc.scantimestamp = (select max(sc2.scantimestamp) from scan sc2 where sc2.uniqueitem_link_id = ih.uniqueitem_link_id)
             and ih.uniqueitem_link_id = sc.uniqueitem_link_id), 0) -
        nvl((select sum(oh.quantity)
             from   outofcirculationhistory oh
             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    oh.outofcircdate between trunc(sysdate) - (8 * 7) and trunc(sysdate)), 0)) circinventadjustments,
       (wi.circinventory + wi.freeofchargeqty -
        nvl((select sum(ih.quantity)
             from   issuehistory ih
             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    ih.incircdate > trunc(sysdate)), 0) +
        nvl((select sum(oh.quantity)
             from   outofcirculationhistory oh
             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    oh.outofcircdate > trunc(sysdate)), 0)) circulatinginventory,
       nvl((select sum(ih.quantity)
            from   issuehistory ih, workorder wo
            where  ih.processbusinessunit_id = c.defaultbusinessunit_id
            and    ih.weareremployment_link_id = wi.weareremployment_id
            and    ih.product_link_id = wi.product_id
            and    ih.sizedefinition_link_id = wi.sizedefinition_id
            and    wo.workorder_id = ih.workorder_id
            and    wo.replacement = 'Y'
            and    ih.incircdate between trunc(sysdate) - (8 * 7) and trunc(sysdate)), 0) replacements,
       nvl((select count(1)
            from   uniqueitem u, uniqueitemnonpool un, uniqueitemflag uf, automaticflag af
            where  u.businessunit_id = c.defaultbusinessunit_id
            and    u.uniqueitem_id = un.uniqueitem_id
            and    un.weareremployment_id = wi.weareremployment_id
            and    u.product_id = wi.product_id
            and    u.sizedefinition_id = wi.sizedefinition_id
            and    u.finishingmethod_id = wi.finishingmethod_id
            and    u.uniqueitem_id = uf.uniqueitem_id
            and    uf.flag_id = af.flag_id
            and    af.automaticflag_id = 4
            and    uf.startdate between trunc(sysdate) - (8 * 7) and trunc(sysdate)), 0) replacementslogged,
       nvl((select count(1)
            from   repairhistory rh, uniqueitem u
            where  rh.weareremployment_link_id = wi.weareremployment_id
            and    rh.uniqueitem_link_id = u.uniqueitem_id
            and    u.product_id = wi.product_id
            and    u.sizedefinition_id = wi.sizedefinition_id
            and    rh.product_link_id = wi.product_id
            and    rh.repairdate between trunc(sysdate) - (8 * 7) and trunc(sysdate)), 0) repairproduct
from   wearerinventory wi, weareremployment we, wearer w, customer c, address a, --languages l,
       product p, sizedefinition s, businessunit bu
where  wi.weareremployment_id = we.weareremployment_id
and    we.wearer_id = w.wearer_id
and    w.customer_id = c.customer_id
and    c.defaultbusinessunit_id = bu.businessunit_id
and    c.visitaddress_id = a.address_id
and    wi.product_id = p.product_id
and    wi.sizedefinition_id = s.sizedefinition_id--order  by c.customernumber, p.code, s.code

/
create or replace view V_INVENTORYUSAGEANALYSIS_POS
 (BUSINESSUNIT, BU_DESCRIPTION, CUSTOMERNUMBER, CUSTOMERNAME, STREET, STREET2, CITY, STATE, ZIPCODE, WEARERNUMBER, DATEACTIVE, DATEINACTIVE, PRODUCTCODE, PRODUCTDESCRIPTION, SIZECODE, TOTALQTYDELIVERED, CIRCINVENTADJUSTMENTS, CIRCULATINGINVENTORY, REPLACEMENTS, REPLACEMENTSLOGGED, REPAIRPRODUCT, REPORTPARAM_ID, CHAIN_CODE)
as select --l.language_id,
       bu.code businessunit, bu.description bu_description, c.customernumber, c.name customername, a.street,
       a.street2, a.city, a.state, a.zipcode, w.wearernumber, wi.dateactive, wi.dateinactive,
       p.code productcode,
       (select pd.description from product_desc pd where wi.product_id = pd.product_id and pd.language_id=c.language_id) productdescription
      , s.code sizecode,
       nvl((select count(1)
            from   uniqueitem u, deliveryscan ds, packingnote pn
            where  u.businessunit_id = c.defaultbusinessunit_id
            and    u.product_id = wi.product_id
            and    u.sizedefinition_id = wi.sizedefinition_id
            and    u.finishingmethod_id = wi.finishingmethod_id
            and    ds.weareremployment_link_id = wi.weareremployment_id
            and    ds.uniqueitem_link_id = u.uniqueitem_id
            and    nvl(ds.packingnote_id,0) = pn.packingnote_id
            and    TRUNC(pn.deliverydate) >= TRUNC(rp.date_value1) and
                   TRUNC(pn.deliverydate)<=TRUNC(rp.date_value2)), 0) totalqtydelivered,
        (nvl((select count(distinct(ih.uniqueitem_link_id))
             from   issuehistory ih
             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    TRUNC(ih.incircdate) between TRUNC(rp.date_value1) and TRUNC(rp.date_value2)), 0) -
        nvl((select sum(oh.quantity)
             from   outofcirculationhistory oh
             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.chargetype<>1
             and    oh.sizedefinition_link_id = wi.sizedefinition_id
             and    TRUNC(oh.outofcircdate) between TRUNC(rp.date_value1) and TRUNC(rp.date_value2)), 0)) circinventadjustments,
  /*(wi.circinventory + wi.freeofchargeqty -
        nvl((select sum(ih.quantity)
             from   issuehistory ih
             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    TRUNC(ih.incircdate) > TRUNC(rp.date_value2)), 0) +
        nvl((select sum(oh.quantity)
             from   outofcirculationhistory oh
             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.chargetype<>1
             and    oh.sizedefinition_link_id = wi.sizedefinition_id
             and    TRUNC(oh.outofcircdate) > TRUNC(rp.date_value2)), 0))*/wi.maxinventory circulatinginventory,
       nvl((select sum(ih.quantity)
            from   issuehistory ih, workorder wo
            where  ih.processbusinessunit_id = c.defaultbusinessunit_id
            and    ih.weareremployment_link_id = wi.weareremployment_id
            and    ih.product_link_id = wi.product_id
            and    ih.sizedefinition_link_id = wi.sizedefinition_id
            and    wo.workorder_id = ih.workorder_id
                    and    wo.replacement = 'Y'
            and    TRUNC(ih.incircdate) >= TRUNC(rp.date_value1) and TRUNC(ih.incircdate)  <=TRUNC(rp.date_value2)), 0) replacements,
       nvl((select count(1)
            from   uniqueitem u, uniqueitemnonpool un, uniqueitemflag uf, automaticflag af
            where  u.businessunit_id = c.defaultbusinessunit_id
            and    u.uniqueitem_id = un.uniqueitem_id
            and    un.weareremployment_id = wi.weareremployment_id
            and    u.product_id = wi.product_id
            and    u.sizedefinition_id = wi.sizedefinition_id
            and    u.finishingmethod_id = wi.finishingmethod_id
            and    u.uniqueitem_id = uf.uniqueitem_id
            and    uf.flag_id = af.flag_id
            and    af.automaticflag_id = 4
            and    TRUNC(uf.startdate) >= TRUNC(rp.date_value1) and TRUNC(uf.startdate)  < TRUNC(rp.date_value2)), 0) replacementslogged,
       nvl((select count(1)
            from   repairhistory rh, uniqueitem u
            where  rh.weareremployment_link_id = wi.weareremployment_id
            and    rh.uniqueitem_link_id = u.uniqueitem_id
            and    u.product_id = wi.product_id
            and    u.sizedefinition_id = wi.sizedefinition_id
            and    rh.product_link_id = wi.product_id
            and    TRUNC(rh.repairdate) >= TRUNC(rp.date_value1) and TRUNC(rh.repairdate) <= TRUNC(rp.date_value2)), 0) repairproduct
, rp.reportparam_id,
ch.code  chain_code
from   wearerinventory wi, weareremployment we, wearer w, customer c LEFT OUTER JOIN chain ch ON ch.chain_id = c.chain_id, address a,-- languages l,
       product p, sizedefinition s, businessunit bu
       , reportparam rp
where  wi.weareremployment_id = we.weareremployment_id
and we.wearer_id = w.wearer_id
and w.customer_id = c.customer_id
and c.defaultbusinessunit_id = bu.businessunit_id
and c.visitaddress_id = a.address_id
and wi.product_id = p.product_id
and wi.sizedefinition_id = s.sizedefinition_id
and c.customernumber between rp.number_value1 and rp.number_value2

/
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)

/
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, SIZE_DESC)
as select uil.uniqueitemloss_id, --credit
       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.creditinvoiceheader_id,
       ih.invoiceheader_id,
       ih.invoicenumber,
       ih.invoicedate,
       ih.startdate,
       ih.enddate,
       ih.invoicebusinessunit_id,
       ih.invoicefrequency_id,
       ih.cluster_id,
       (select c.code from currency c where c.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,
       (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
union
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.startdate,
       ih.enddate,
       ih.invoicebusinessunit_id,
       ih.invoicefrequency_id,
       ih.cluster_id,
       (select c.code from currency c where c.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,
       (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
union
select uil.uniqueitemloss_id, --credit ragged
       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.creditinvoiceheader_id,
       ih.invoiceheader_id,
       ih.invoicenumber,
       ih.invoicedate,
       ih.startdate,
       ih.enddate,
       ih.invoicebusinessunit_id,
       ih.invoicefrequency_id,
       ih.cluster_id,
       (select c.code from currency c where c.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.finishingmethod_id = any
                  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,
       (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
union
select uil.uniqueitemloss_id, --loss charges ragged
       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.startdate,
       ih.enddate,
       ih.invoicebusinessunit_id,
       ih.invoicefrequency_id,
       ih.cluster_id,
       (select c.code from currency c where c.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.finishingmethod_id = any
                  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,
       (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

/
create or replace view V_INVOICECLIENT
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, ACTIVITYREFERENCE, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE
, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY
, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC
, INVOICELAYOUTCODE, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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
, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE
, INVOICEREMARKENDDATE, INTERNALVATNUMBER, VATNUMBER, CLIENT_LINK_ID, IHCLIENTNUMBER, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, IHCCLIENTTYPE, CLIENTINVOICETYPE, PAYMENTTERMSDUEDATE, BILL_LEGAL_NAME, PRINTTAXONAPPENDIX, CUSTBILLTOCOMMENT, CUSTDELTOCOMMENT, SENDINVOICEBY)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       a.invoicenumber,a.activityreference, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, a.billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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
       , ihc.clientinvoicetype--502813
       , ihextr.paymenttermsduedate
       , (SELECT c.legalname FROM customer c WHERE c.customer_id=a.billtocustomer_link_id) BILL_LEGAL_NAME --todo6927
       , (select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix
       , (select cbc.description from customerbillingcomment cbc where cbc.customer_id = a.billtocustomer_link_id) custbilltocomment
       , (select cbc.description from customerbillingcomment cbc where cbc.customer_id = a.deltocustomer_link_id) custdeltocomment
       , (select cbi.SENDINVOICEBY from customerbillinginfo cbi where a.billtocustomer_link_id=cbi.customer_id) sendinvoiceby
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),--501528
      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)
where a.currency_id = b.currency_id--      and a.documenttype = 1
      and a.documenttype in (1, 3) --501528
      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

/
create or replace view V_INVOICECLIENTLINE
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, GENERATED, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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, PRODUCTCUSTOMCODE)
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.generated,
a.adjustedamount, a.adjustedprice, a.adjustmentbilledqty, a.extend, a.amount, a.discountpercentage,
a.price, a.billedqty, a.adjustmentpermited, 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,
(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, 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,
case (SELECT pilt.suppressprinting
         from plantinvoicelinetype pilt, businessunit bu
         where f.invoicebusinessunit_id = bu.businessunit_id
               and bu.plant_id = pilt.plant_id
               and pilt.invoicelinetype_id = a.invoicelinetype_id)
  when 0 then 0
  when 1 then 1
  when 2 then 2
  else e.supressprinting
end supressprinting, --502161
b.adjustmentdeliveredqty, b.pricefactor,
(select plpc.customcode from productlistpercustomer plpc
        where plpc.product_id=b.product_link_id
              and plpc.sizedefinition_id=b.sizedefinition_link_id
              and plpc.finishingmethod_id=b.finishingmethod_id
              and plpc.customer_id=coalesce(f.deltocustomer_link_id,f.billtocustomer_link_id)
              and plpc.dateactive <= f.invoicedate and plpc.dateinactive > f.invoicedate
      ) productcustomcode
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 in (1, 3) -- 501528

/
create or replace view V_INVOICECLIENTLINECRI
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, GENERATED, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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.adjustmentpermited, 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_INVOICECLIENTLINE_AAA
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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, RENTALPRICE)
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
, ( select z.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.adjustmentpermited
, a.taxgroupcode
, a.taxtype
, a.subjecttominimum
, d.code turnovergroupcode
, ( select t.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
, b.adjustmentdeliveredqty
, b.pricefactor
, pack_price.Rent_Price(cl.customer_id, pl.product_id, sdl.sizedefinition_id, b.finishingmethod_id, null, 0) rentalprice
from
  invoiceline a
     left outer join invoicelineproduct b
        left outer join product_link pl
           on (pl.product_link_id = b.product_link_id)
        left outer join sizedefinition_link sdl
           on (b.sizedefinition_link_id = sdl.sizedefinition_link_id)
        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
     left outer join customer_link cl
        on f.billtocustomer_link_id = cl.customer_link_id
, languages
where a.invoicelinetype_id = e.invoicelinetype_id
  and a.invoiceheader_id = f.invoiceheader_id
  and f.documenttype in (1, 3) -- 501528

/
create or replace view V_INVOICECLIENTLINE_CBD
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, GENERATED, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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, COSTCENTER_CODE, COSTCENTER_DESC, COSTCENTERINVOICELINE_QUANTITY, COSTCENTERINVOICELINE_AMOUNT, BESTELLNR)
as select --XPKINVOICELINE
f.invoicedate, f.invoicenumber, a.linenumber,
/*(CASE --WHEN e.TYPE = 1 AND a.invoicelinesubtype = 13 --changes per week       THEN 1.6
      when e.type = 26
           and (((select max(plpc.budgetusage) from productlistpercustomer plpc where plpc.customer_id = f.deltocustomer_link_id
                  and plpc.product_id = b.product_link_id and plpc.sizedefinition_id = b.sizedefinition_link_id and plpc.finishingmethod_id = b.finishingmethod_id
                  and plpc.dateactive in (select max(plpc2.dateactive) from productlistpercustomer plpc2 where plpc2.customer_id = f.deltocustomer_link_id
                  and plpc2.product_id = b.product_link_id and plpc2.sizedefinition_id = b.sizedefinition_link_id and plpc2.finishingmethod_id = b.finishingmethod_id
                  and plpc2.dateactive <= f.invoicedate)) = 1) --self paid product
               OR ((select max(cl.budgetclient) from clientdeliverynoteline cdl, clientdeliverynote cdn , client cl
                  where cdl.invoiceline_id = a.invoiceline_id and cdl.clientdeliverinote_id = cdn.clientdeliverynote_id
                  and cdn.client_link_id = cl.client_id)  = 1) --self payer client
               )
      THEN 26.2
      ELSE e.TYPE
END) */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.generated,
a.adjustedamount, a.adjustedprice, a.adjustmentbilledqty, a.extend, a.amount, a.discountpercentage,
a.price, a.billedqty, a.adjustmentpermited, 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
, cc.code costcenter_code, cc.description costcenter_desc
, ccil.quantity costcenterinvoiceline_quantity
, ccil.amount costcenterinvoiceline_amount
, case when e.type = 5 and a.invoicelinesubtype = 17 --Garment sales via sales note
 then case  when (select max(cast(lpad(replace(pcv.version, '.', ''), 3) as numeric)) from product_component_version pcv) >= 112
  then (select
  ( CAST( listagg(sn.referencenumber,',') within group(order by sn.referencenumber) AS VARCHAR2(255)) )--use VARCHAR2(60) when re-importing the view !!!
  from workorder sn, workorderline snl, product_link prdlk where snl.workorder_id = sn.workorder_id and snl.product_link_id = prdlk.product_link_id
  and sn.invoiceheader_id = a.invoiceheader_id and prdlk.code = a.code and sn.referencenumber is not null and sn.origin = 6) --sales note
  else 'Only for Oracle version 11.R2' end
 else ' ' end Bestellnr
from invoiceline a
LEFT OUTER JOIN costreportinfo cri
     LEFT OUTER JOIN costcenter_link cc ON cc.costcenter_id = cri.costcenter_link_id
     LEFT OUTER JOIN costcenterinvoiceline ccil ON ccil.costcenter_link_id = cri.costcenter_link_id and ccil.invoiceline_id = cri.invoiceline_id
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)
and a.budgetcode is null

/
create or replace view V_INVOICECLIENTLINE_CIW
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, DESCRIPTION, GENERATED, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, TAXGROUPCODE, TAXGROUPDESC, 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, FINISHMETHOD, NOOFWEEKS, CRI_QUANTITY)
as select f.invoicedate, f.invoicenumber, a.linenumber,
(CASE WHEN e.TYPE = 1 AND a.invoicelinesubtype = 13 THEN 1.6
    --  when e.type = 8 then 2
      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.generated,
a.adjustedamount, a.adjustedprice, a.adjustmentbilledqty, a.extend, a.amount, a.discountpercentage,
a.price,a.billedqty, a.adjustmentpermited, a.taxgroupcode,
(select tg.description from taxgroup tg  where tg.code = 'SSTD' and tg.country_id in (select cu.COUNTRY_ID from customer cu where cu.customernumber = f.BILLTOCUSTOMERNUMBER)) taxgroupdesc,
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,
(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, coalesce(b.billingmethod, 0) 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,
case (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)
  when 0 then 0
  when 1 then 1
  when 2 then 2
  else e.supressprinting
end supressprinting, --502161
b.adjustmentdeliveredqty, b.pricefactor
, (select fm.code from finishingmethod fm where fm.finishingmethod_id = b.finishingmethod_id) FinishMethod
, X.NoOfWeeks, X.quantity cri_quantity
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)
LEFT OUTER JOIN  (select y.invoiceline_id, y.quantity, count(distinct y.yearweek) NoOfWeeks
   from (select crin.invoiceline_id, (crin.year*100+crin.week) yearweek, sum(crin.quantity) quantity
        from costreportinfo crin
        group by crin.invoiceline_id, crin.year*100+crin.week) Y
   group by y.invoiceline_id, y.quantity
   ) X on X.invoiceline_id = a.invoiceline_id and a.invoicelinetype_id = 1,
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) -- 501528

/
create or replace view V_INVOICECLIENTLINE_DFD
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, GENERATED, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, TAXGROUPCODE, TAXTYPE, SUBJECTTOMINIMUM, TURNOVERGROUPCODE, TURNOVERGROUPDESCRIPTION, INVOICELINESUBTYPE, INVOICELINESUBTYPEDESC, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PRODUCTSHORTDESCRIPTION, SHORTDESCRIPTION, SIZECODE, SIZEDESCRIPTION
, FINISHINGMETHODCODE, FINISHINGMETHODDESCRIPTION, 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, DELIVERYSCHEMECODE, CHANGESWEEKFREQUENCY)
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 rpad(trim(DESCRIPTION), 63) 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.adjustmentpermited, 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,
(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, 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,
case (SELECT pilt.suppressprinting
         from plantinvoicelinetype pilt, businessunit bu
         where f.invoicebusinessunit_id = bu.businessunit_id
               and bu.plant_id = pilt.plant_id
               and pilt.invoicelinetype_id = a.invoicelinetype_id)
  when 0 then 0
  when 1 then 1
  when 2 then 2
  else e.supressprinting
end supressprinting, --502161
b.adjustmentdeliveredqty, b.pricefactor, b.deliveryschemecode
, (case
  when a.invoicelinetype_id = 1 and a.invoicelinesubtype in (0, 7, 8)--e.type = 1 and a.invoicelinesubtype = 0
  then FGET_BDE_FRECV(f.deltocustomer_link_id, b.product_link_id, b.sizedefinition_link_id, b.finishingmethod_id, f.invoicedate, b.deliveryschemecode)
  else -1
  end ) changesweekFrequency
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 in (1, 3) -- 501528

/
create or replace view V_INVOICECLIENTLINE_ECL
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPE_ID, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, GENERATED, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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, COLOR_DESC, PRODUCTDESCRIPTION, REGISTRATIONUNITDESCRIPTION
, ADJUSTMENTREASON_CODE, INVOICELINE_SEQUENCENUMBER, SUPRESSPRINTING, ADJUSTMENTDELIVEREDQTY, PRICEFACTOR, PRODUCTCUSTOMCODE, MINIMUMPERCENTAGE, CIRCINV, COUNTWEEK, FIRSDAY, LASTDAY, MINDATE, MAXDATE)
as select f.invoicedate, f.invoicenumber, a.linenumber, --a.invoicelinetype_id invoicelinetype,
(CASE WHEN e.TYPE = 1 AND a.invoicelinesubtype = 6
      THEN 2
      when e.TYPE = 1 AND a.invoicelinesubtype <>  6 then 1
      when e.TYPE = 2 then 2
      ELSE e.type
END)  invoicelinetype, --e.type invoicelinetype,*/,
a.invoicelinetype_id,
( 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.adjustmentpermited, 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,
(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, 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 cd.description from product p join color_desc cd on p.color_id=cd.color_id where cd.language_id=languages.language_id and p.product_id=b.product_link_id ) color_desc,
 ( 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,
case (SELECT pilt.suppressprinting
         from plantinvoicelinetype pilt, businessunit bu
         where f.invoicebusinessunit_id = bu.businessunit_id
               and bu.plant_id = pilt.plant_id
               and pilt.invoicelinetype_id = a.invoicelinetype_id)
  when 0 then 0
  when 1 then 1
  when 2 then 2
  else e.supressprinting
end supressprinting, --502161
b.adjustmentdeliveredqty, b.pricefactor,
(select plpc.customcode from productlistpercustomer plpc
        where plpc.product_id=b.product_link_id
              and plpc.sizedefinition_id=b.sizedefinition_link_id
              and plpc.finishingmethod_id=b.finishingmethod_id
              and plpc.customer_id=coalesce(f.deltocustomer_link_id,f.billtocustomer_link_id)
              and plpc.dateactive <= f.invoicedate and plpc.dateinactive > f.invoicedate
      ) productcustomcode,
(select plpc.minimumturnaround from productlistpercustomer plpc where plpc.product_id= b.product_link_id and plpc.customer_id=coalesce(f.deltocustomer_link_id,f.billtocustomer_link_id)
              and plpc.dateactive <= f.invoicedate and plpc.dateinactive > f.invoicedate
and plpc.finishingmethod_id=b.finishingmethod_id
and plpc.sizedefinition_id=b.sizedefinition_link_id)minimumpercentage,
(select sum(rqa.quantity) from rentalqtyadjustment rqa, productlistperdistribpoint plpd, distributionpoint dp, department d
where rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
and plpd.distributionpoint_id = dp.distributionpoint_id
and dp.department_id = d.department_id
and d.customer_id =f.deltocustomer_link_id
and plpd.product_id =b.product_link_id) circinv,
            (select count(cri.week) from costreportinfo cri where cri.invoiceline_id=a.invoiceline_id) countweek,
           getdateforweekyear(8,(select cast(substr(min(cri.year*100+cri.week),-2,2)as int) from costreportinfo cri where cri.invoiceline_id=a.invoiceline_id)-1,nvl((select min(cri.year) from costreportinfo cri where cri.invoiceline_id=a.invoiceline_id),9999)) firsday
          ,getdateforweekyear(7,(select cast(substr(max(cri.year*100+cri.week),-2,2)as int) from costreportinfo cri where cri.invoiceline_id=a.invoiceline_id),nvl((select max(cri.year) from costreportinfo cri where cri.invoiceline_id=a.invoiceline_id),9999)) lastday,
          (select min(pn.deliverydate) from packingnote pn join packingnoteline pnl on pn.packingnote_id=pnl.packingnote_id
          where pnl.invoiceheader_id=a.invoiceheader_id
          and pnl.product_id=b.product_link_id
          ) mindate,
                    (select max(pn.deliverydate) from packingnote pn join packingnoteline pnl on pn.packingnote_id=pnl.packingnote_id
          where pnl.invoiceheader_id=a.invoiceheader_id
          and pnl.product_id=b.product_link_id
          ) maxdate
from invoiceline a --join costreportinfo cc on  cc.invoiceline_id=a.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)
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 in (1, 3) -- 501528

/
create or replace view V_INVOICECLIENTLINE_ELI
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, GENERATED, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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, PRODUCTCUSTOMCODE, TAXRATE, COSTCENTER_ID, COSTCENTER_DESC, COSTCENTER_PONUMBER, COSTCENTER_QUANTITY, COSTCENTER_AMOUNT, CONTRACTCOEFFICIENT, COSTCENTER_CODE, DEPTDESC, PLPC_FLEXFIELD)
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 = l.LANGUAGE_ID) invoicelinetypedesc,
case when a.invoicelinetype_id=2 then
     case when b.product_link_id <> (select p.parentproduct_id from product p where b.product_link_id=p.product_id)
       then (select parent.code from product parent join product pr on pr.parentproduct_id=parent.product_id where b.product_link_id=pr.product_id) else a.code end
        else a.code
         end code
, cast(FSGET_TAXCODE(f.invoicenumber, a.linenumber) as varchar2(255)) taxcode
, case when a.invoicelinetype_id = 2 then
     case when b.product_link_id <> (select p.parentproduct_id from product p where b.product_link_id=p.product_id)
       then (select pd.description||'  '||b.finishingmethoddescription from product_desc pd join product parent on pd.product_id=parent.product_id join product pr on pr.parentproduct_id=parent.product_id where b.product_link_id=pr.product_id and pd.language_id=l.language_id)
         else a.description||'  '||b.finishingmethoddescription
         end
        else a.description
         end description,
a.generated,
a.adjustedamount, a.adjustedprice, a.adjustmentbilledqty, a.extend, a.amount, a.discountpercentage, a.price,
case when e.type = 6 --repair
     then coalesce((select sum(rh.minutes) from repairhistory rh where rh.invoiceheader_id = a.invoiceheader_id
                           and rh.product_link_id = b.product_link_id), a.billedqty)
  else a.billedqty end billedqty,
a.adjustmentpermited, 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 = l.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 = l.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, c.transactiontype, c.transactiondate, c.percentage,
a.systemuser_id, a.timestamp, a.invoiceline_id,
coalesce(a.remark, (select max(plpc.remark) from productlistpercustomer plpc
        where plpc.product_id = b.product_link_id
              and plpc.sizedefinition_id = b.sizedefinition_link_id
              and plpc.finishingmethod_id = b.finishingmethod_id
              and plpc.customer_id = coalesce(f.deltocustomer_link_id,f.billtocustomer_link_id)
              and plpc.dateactive <= f.invoicedate and plpc.dateinactive > f.invoicedate)) remark,
l.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 = l.LANGUAGE_ID) PRODUCTDESCRIPTION,
 ( SELECT PD.REGISTRATIONUNITDESCRIPTION FROM PRODUCT_LINK_DESC pd WHERE pd.product_link_id = b.product_link_id AND pd.language_id = l.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,
case (SELECT pilt.suppressprinting
         from plantinvoicelinetype pilt, businessunit bu
         where f.invoicebusinessunit_id = bu.businessunit_id
               and bu.plant_id = pilt.plant_id
               and pilt.invoicelinetype_id = a.invoicelinetype_id)
  when 0 then 0
  when 1 then 1
  when 2 then 2
  else e.supressprinting
end supressprinting, --502161
b.adjustmentdeliveredqty, b.pricefactor,
(select max(plpc.customcode) from productlistpercustomer plpc
        where plpc.product_id=b.product_link_id
              and plpc.sizedefinition_id=b.sizedefinition_link_id
              and plpc.finishingmethod_id=b.finishingmethod_id
              and plpc.customer_id=coalesce(f.deltocustomer_link_id,f.billtocustomer_link_id)
              and plpc.dateactive <= f.invoicedate and plpc.dateinactive > f.invoicedate
      ) productcustomcode,
coalesce((select case when f.invoicedate < tg.startdatetaxrate then tg.oldtaxrate
       else tg.taxrate
       end taxrate
 from taxgroup tg, customer bill
 where a.taxgroupcode = tg.code
       and bill.customer_id = f.billtocustomer_link_id
       and tg.country_id = bill.country_id), 0) taxrate
, coalesce(cc.costcenter_id, -1) costcenter_id, cc.description costcenter_desc, cc.ponumber costcenter_ponumber
, ccil.quantity costcenter_quantity, ccil.amount costcenter_amount, a.CONTRACTCOEFFICIENT, cc.code costcenter_code
, (Select max(dep.description) from department dep where dep.costcenter_id = cc.costcenter_id) DeptDesc
, (select max(dff.stringvalue)
  from  dialogs di, characteristicstemplate cht, CharacteristicsTempLine chtl, characteristic ch, DialogFlexFields dff, productlistpercustomer plpc
  where cht.dialog_id = di.dialog_id and chtl.characteristicstemplate_id = cht.characteristicstemplate_id
  and chtl.characteristic_id = ch.characteristic_id and dff.dialog_id = di.dialog_id and dff.characteristic_id = ch.characteristic_id
  and dff.entity_id = plpc.productlistpercustomer_id and di.code = 'ProductListPerCustomer' and ch.code = '1'
  and plpc.customer_id = f.deltocustomer_link_id and plpc.product_id = b.product_link_id and (plpc.sizedefinition_id = b.sizedefinition_link_id
  or (plpc.sizedefinition_id in (select sd.sizedefinition_id from sizedefinition sd where sd.code = '*')))and plpc.finishingmethod_id = b.finishingmethod_id) PLPC_FlexField
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)
LEFT OUTER JOIN costcenterinvoiceline ccil inner join costcenter cc on ccil.costcenter_link_id = cc.costcenter_id on ccil.invoiceline_id = a.invoiceline_id,
invoicelinetype e,
invoiceheader f, LANGUAGES l
where a.invoicelinetype_id = e.invoicelinetype_id and
a.invoiceheader_id = f.invoiceheader_id
and f.documenttype in (1, 3) -- 501528

/
create or replace view V_INVOICECLIENTLINE_HOW
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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.adjustmentpermited, 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_INVOICECLIENTLINE_HRB
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, GENERATED, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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, PRODUCTCUSTOMCODE, TAXRATE)
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.generated,
a.adjustedamount, a.adjustedprice, a.adjustmentbilledqty, a.extend, a.amount, a.discountpercentage,
a.price, a.billedqty, a.adjustmentpermited, 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,
(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, 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,
case (SELECT pilt.suppressprinting
         from plantinvoicelinetype pilt, businessunit bu
         where f.invoicebusinessunit_id = bu.businessunit_id
               and bu.plant_id = pilt.plant_id
               and pilt.invoicelinetype_id = a.invoicelinetype_id)
  when 0 then 0
  when 1 then 1
  when 2 then 2
  else e.supressprinting
end supressprinting, --502161
b.adjustmentdeliveredqty, b.pricefactor,
(select plpc.customcode from productlistpercustomer plpc
        where plpc.product_id=b.product_link_id
              and plpc.sizedefinition_id=b.sizedefinition_link_id
              and plpc.finishingmethod_id=b.finishingmethod_id
              and plpc.customer_id=coalesce(f.deltocustomer_link_id,f.billtocustomer_link_id)
              and plpc.dateactive <= f.invoicedate and plpc.dateinactive > f.invoicedate
      ) productcustomcode
, (select tg.taxrate from taxgroup tg, plant pl, businessunit ibu where tg.code = a.taxgroupcode and tg.country_id = pl.country_id
                           and pl.plant_id = ibu.plant_id and ibu.businessunit_id = f.invoicebusinessunit_id) taxrate
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 in (1, 3) -- 501528

/
create or replace view V_INVOICECLIENTLINE_LLG
 (LINENUMBER, INVOICEHEADER_ID, INVOICELINE_ID, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, DESCRIPTION, AMOUNT, PRICE, BILLEDQTY, TAXGROUPCODE, INVOICELINESUBTYPE, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, SIZECODE, FINISHINGMETHODCODE, CHANGEDDATE, INVOICEQTYCOLUMN, PERCENTAGE, REMARK, LANGUAGECODE, OVERAMOUNT, REGISTRATIONUNITDESCRIPTION, INVOICELINE_SEQUENCENUMBER, SUPRESSPRINTING, PRICEFACTOR, NUMBEROFWEEKS)
as select a.linenumber, a.invoiceheader_id, a.invoiceline_id,
(CASE WHEN e.TYPE = 1 AND a.invoicelinesubtype = 13
      THEN 1.6
      WHEN e.TYPE = 1 AND a.invoicelinesubtype = 8
        then 1.8  --corrections
      when e.type = 1 and a.invoicelinesubtype = 43
        then 1.43 --excess
      WHEN e.type = 1 AND a.invoicelinesubtype = 41
        then 1.41 --new loan
      WHEN e.type = 1 AND a.invoicelinesubtype = 42
        then 1.42 --outstanding loan
      WHEN e.type = 2 and a.invoicelinesubtype = 43
        then 2.43 --heavily soiled
      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, a.description, a.amount, a.price, a.billedqty, a.taxgroupcode,a.invoicelinesubtype
, b.productgroupcode, b.productgroupdescription
, b.sizecode, b.finishingmethodcode
, b.startdate changeddate
, b.invoiceqtycolumn, c.percentage,
a.remark, LANGUAGES.CODE LANGUAGECODE,
c.overamount,
 ( 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) InvoiceLine_SequenceNumber,
case (SELECT pilt.suppressprinting
         from plantinvoicelinetype pilt, businessunit bu
         where f.invoicebusinessunit_id = bu.businessunit_id
               and bu.plant_id = pilt.plant_id
               and pilt.invoicelinetype_id = a.invoicelinetype_id)
  when 0 then 0
  when 1 then 1
  when 2 then 2
  else e.supressprinting
end supressprinting,
b.pricefactor, b.numberofweeks
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),
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_INVOICECLIENTLINE_LTB
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, GENERATED, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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, PRODUCTCUSTOMCODE, PRODUCTCODE, DOCUMENTTYPE)
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.generated,
a.adjustedamount, a.adjustedprice, a.adjustmentbilledqty, a.extend, a.amount, a.discountpercentage,
a.price, a.billedqty, a.adjustmentpermited, 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,
(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, 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,
case (SELECT pilt.suppressprinting
         from plantinvoicelinetype pilt, businessunit bu
         where f.invoicebusinessunit_id = bu.businessunit_id
               and bu.plant_id = pilt.plant_id
               and pilt.invoicelinetype_id = a.invoicelinetype_id)
  when 0 then 0
  when 1 then 1
  when 2 then 2
  else e.supressprinting
end supressprinting, --502161
b.adjustmentdeliveredqty, b.pricefactor,
(select plpc.customcode from productlistpercustomer plpc
        where plpc.product_id=b.product_link_id
              and plpc.sizedefinition_id=b.sizedefinition_link_id
              and plpc.finishingmethod_id=b.finishingmethod_id
              and plpc.customer_id=coalesce(f.deltocustomer_link_id,f.billtocustomer_link_id)
              and plpc.dateactive <= f.invoicedate and plpc.dateinactive > f.invoicedate
      ) productcustomcode,
(select pr.code from product pr
  where b.product_link_id = pr.product_id
  ) productcode, f.documenttype
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)
inner join invoicelinetype e on e.invoicelinetype_id = a.invoicelinetype_id
inner join invoiceheader f on f.invoiceheader_id = a.invoiceheader_id
, LANGUAGES
where f.documenttype in (1, 3)

/
create or replace view V_INVOICECLIENTLINE_PHS
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, GENERATED, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, TAXGROUPCODE, TAXTYPE, SUBJECTTOMINIMUM, TURNOVERGROUPCODE, TURNOVERGROUPDESCRIPTION, INVOICELINESUBTYPE, INVOICELINESUBTYPEDESC, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PRODUCTSHORTDESCRIPTION, SHORTDESCRIPTION, SIZECODE, SIZEDESCRIPTION
, FINISHINGMETHODCODE, FINISHINGMETHODDESCRIPTION, INVOICEQTYCOLUMN, SETSIZE, WEARERFUNCTIONCODE, WEARERFUNCTIONDESC, 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, PRODUCTCUSTOMCODE, NROFWEEKS)
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.generated,
a.adjustedamount, a.adjustedprice, a.adjustmentbilledqty, a.extend, a.amount, a.discountpercentage,
a.price, a.billedqty, a.adjustmentpermited, 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,
(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,
/* ROP - add setsize and wearerfunction  */
( select count(*)
    from setcontents sco
   where sco.set_id = b.product_link_id) SETSIZE,
( select wfu.code
    from wearerfunction wfu, weareremployment wem
   where b.weareremployment_link_id = wem.weareremployment_id
     and wem.wearerfunction_id = wfu.wearerfunction_id) wearerfunctioncode,
( select wfu.description
    from wearerfunction wfu, weareremployment wem
   where b.weareremployment_link_id = wem.weareremployment_id
     and wem.wearerfunction_id = wfu.wearerfunction_id) wearerfunctiondesc,
/* end */
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,
case (SELECT pilt.suppressprinting
         from plantinvoicelinetype pilt, businessunit bu
         where f.invoicebusinessunit_id = bu.businessunit_id
               and bu.plant_id = pilt.plant_id
               and pilt.invoicelinetype_id = a.invoicelinetype_id)
  when 0 then 0
  when 1 then 1
  when 2 then 2
  else e.supressprinting
end supressprinting, --502161
b.adjustmentdeliveredqty, b.pricefactor,
(select plpc.customcode from productlistpercustomer plpc
        where plpc.product_id=b.product_link_id
              and plpc.sizedefinition_id=b.sizedefinition_link_id
              and plpc.finishingmethod_id=b.finishingmethod_id
              and plpc.customer_id=coalesce(f.deltocustomer_link_id,f.billtocustomer_link_id)
              and plpc.dateactive <= f.invoicedate and plpc.dateinactive > f.invoicedate
      ) productcustomcode
, (select count(1)--count(cri.week)--+count(cri.year)-1
   from costreportinfo cri where cri.invoiceline_id = a.invoiceline_id) NROFWEEKS
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 in (1, 3) -- 501528

/
create or replace view V_INVOICECLIENTLINE_PLS
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, GENERATED, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, TAXGROUPCODE, TAXTYPE, SUBJECTTOMINIMUM, TURNOVERGROUPCODE, TURNOVERGROUPDESCRIPTION, INVOICELINESUBTYPE, INVOICELINESUBTYPEDESC, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PRODUCTSHORTDESCRIPTION, MINIMUMPERCENTAGE, CIRCINV, 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, PRODUCTCUSTOMCODE, MINDESC)
as select f.invoicedate, f.invoicenumber, a.linenumber,
(CASE WHEN e.TYPE = 1 AND a.invoicelinesubtype = 13 --changes per week
      THEN 1.13
       WHEN e.TYPE = 1 AND a.invoicelinesubtype = 6 --under use
      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.generated,
a.adjustedamount, a.adjustedprice, a.adjustmentbilledqty, a.extend, a.amount, a.discountpercentage,
a.price, a.billedqty, a.adjustmentpermited, 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,
(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,
(select plpc.minimumturnaround from productlistpercustomer plpc where plpc.product_id= b.product_link_id and plpc.customer_id=coalesce(f.deltocustomer_link_id,f.billtocustomer_link_id)
              and plpc.dateactive <= f.invoicedate and plpc.dateinactive > f.invoicedate
and plpc.finishingmethod_id=b.finishingmethod_id
and plpc.sizedefinition_id=b.sizedefinition_link_id)minimumpercentage,
(select sum(rqa.quantity) from rentalqtyadjustment rqa, productlistperdistribpoint plpd, distributionpoint dp, department d
where rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
and plpd.distributionpoint_id = dp.distributionpoint_id
and dp.department_id = d.department_id
and d.customer_id =f.deltocustomer_link_id
and plpd.product_id =b.product_link_id) circinv
, 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,
case (SELECT pilt.suppressprinting
         from plantinvoicelinetype pilt, businessunit bu
         where f.invoicebusinessunit_id = bu.businessunit_id
               and bu.plant_id = pilt.plant_id
               and pilt.invoicelinetype_id = a.invoicelinetype_id)
  when 0 then 0
  when 1 then 1
  when 2 then 2
  else e.supressprinting
end supressprinting, --502161
b.adjustmentdeliveredqty, b.pricefactor,
(select plpc.customcode from productlistpercustomer plpc
        where plpc.product_id=b.product_link_id
              and plpc.sizedefinition_id=b.sizedefinition_link_id
              and plpc.finishingmethod_id=b.finishingmethod_id
              and plpc.customer_id=coalesce(f.deltocustomer_link_id,f.billtocustomer_link_id)
              and plpc.dateactive <= f.invoicedate and plpc.dateinactive > f.invoicedate
      ) productcustomcode,
f_mindesc(a.invoiceline_id, b.product_link_id, f.deltocustomer_link_id) mindesc
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 in (1, 3)
-- 501528

/
create or replace view V_INVOICECLIENTLINE_PRI
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, GENERATED, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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)
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.generated,
a.adjustedamount, a.adjustedprice, a.adjustmentbilledqty, a.extend, a.amount, a.discountpercentage,
a.price, a.billedqty, a.adjustmentpermited, 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,
(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, 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,
case (SELECT pilt.suppressprinting
         from plantinvoicelinetype pilt, businessunit bu
         where f.invoicebusinessunit_id = bu.businessunit_id
               and bu.plant_id = pilt.plant_id
               and pilt.invoicelinetype_id = a.invoicelinetype_id)
  when 0 then 0
  when 1 then 1
  when 2 then 2
  else e.supressprinting
end supressprinting, --502161
b.adjustmentdeliveredqty, b.pricefactor
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 in (1, 3) -- 501528

/
create or replace view V_INVOICECLIENT_BDM
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, TVA, TVA_AMOUNT, INVOICENUMBER, ACTIVITYREFERENCE, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS
, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL
, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, PAYMENTMETHOD, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES
, PAYMENTTERMS_DESC, INVOICELAYOUTCODE, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER
, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, INTERNALVATNUMBER, VATNUMBER, CLIENT_LINK_ID, IHCLIENTNUMBER, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, IHCCLIENTTYPE, CLIENTINVOICETYPE, PAYMENTTERMSDUEDATE, BILL_LEGAL_NAME, PRINTTAXONAPPENDIX, CUSTBILLTOCOMMENT, CUSTDELTOCOMMENT, SENDINVOICEBY, COGAMOUNT, LOGAMOUNT, HYGAMOUNT, HYGAMOUNTRENT, HYGAMOUNTWASH)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       (select min(c.percentage) from invoiceline il LEFT OUTER JOIN invoicelinevarious c ON (il.invoiceline_id = c.invoiceline_id) where il.invoiceheader_id=a.invoiceheader_id and il.invoicelinetype_id=18) tva,
       (select sum(il.amount) from invoiceline il where il.invoiceheader_id=a.invoiceheader_id and il.invoicelinetype_id = 18 and il.description='TVA') tva_amount,
       a.invoicenumber,a.activityreference, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, a.billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, a.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,ihextr.paymenttype paymentmethod,
       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 fl.code from customer cus join formlayout fl on (cus.invoicelayout_id=fl.formlayout_id and fl.formtype='IN') where cus.customer_id=a.deltocustomer_link_id) invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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.internalidcode cust_bank_idcode, cbank.description cust_bank_desc, cbank.internalidcode cust_bank_internid,
       cbank.laundrybankaccount cust_lndrybankaccount, cbank.ibanno cust_ibanno,
       lbank.internalidcode 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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
       , ihc.clientinvoicetype--502813
       , ihextr.paymenttermsduedate
       , (SELECT c.legalname FROM customer c WHERE c.customer_id=a.billtocustomer_link_id) BILL_LEGAL_NAME --todo6927
       , (select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix
       , (select max(cbc.description) from customerbillingcomment cbc where cbc.customer_id = a.billtocustomer_link_id) custbilltocomment
       , (select max(cbc.description) from customerbillingcomment cbc where cbc.customer_id = a.deltocustomer_link_id) custdeltocomment
       , (select cbi.SENDINVOICEBY from customerbillinginfo cbi where a.billtocustomer_link_id=cbi.customer_id) sendinvoiceby,
   (select sum(coalesce(cc.quantity * il.price, il.amount)) from invoicelineproduct ilp, invoiceline il left outer join costreportinfo cc on cc.invoiceline_id = il.invoiceline_id
   where il.invoiceline_id = ilp.invoiceline_id and il.invoiceheader_id = a.invoiceheader_id and ilp.productgroupcode <> 'HYGIEN'
   and ((il.invoicelinetype_id = 2 and il.invoicelinesubtype = 15) or (il.invoicelinetype_id = 28 and il.invoicelinesubtype in (1, 4)))) cogamount,
   (select sum(coalesce(cc.quantity * il.price, il.amount)) from invoicelineproduct ilp, invoiceline il left outer join costreportinfo cc on cc.invoiceline_id = il.invoiceline_id
   where il.invoiceline_id = ilp.invoiceline_id and il.invoiceheader_id = a.invoiceheader_id and ilp.productgroupcode <> 'HYGIEN' and il.invoicelinetype_id in (2, 8, 20, 21) and il.invoicelinesubtype <> 15)
   logamount,
coalesce((select sum(il.amount) from invoiceline il join invoicelineproduct ilp on il.invoiceline_id=ilp.invoiceline_id
 where il.invoiceheader_id = a.invoiceheader_id and ilp.productgroupcode = 'HYGIEN' and il.invoicelinetype_id not in (1,2)),0 ) hygamount,
 coalesce((select sum(il.amount) from invoiceline il join invoicelineproduct ilp on il.invoiceline_id=ilp.invoiceline_id
 where il.invoiceheader_id = a.invoiceheader_id and ilp.productgroupcode = 'HYGIEN' and il.invoicelinetype_id=1),0) hygamountrent,
 coalesce((select sum(coalesce(cc.quantity * il.price, il.amount)) from invoicelineproduct ilp, invoiceline il left outer join costreportinfo cc on cc.invoiceline_id = il.invoiceline_id
  where il.invoiceline_id=ilp.invoiceline_id and il.invoiceheader_id = a.invoiceheader_id and ilp.productgroupcode = 'HYGIEN' and il.invoicelinetype_id = 2),0) hygamountwash
from  currency b,
      businessunit e, status s, bankinstitution Lbank,
      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,customerbillinginfo cbi  LEFT OUTER JOIN bankinstitution Cbank ON (cbank.bankinstitution_id = cbi.laundrybankinstitution_id),
      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),--501528
      invoiceheaderextrainfo ihextr
where a.currency_id = b.currency_id -- and a.documenttype = 1
      and a.documenttype in (1, 3) --501528
      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 cbi.customer_id=a.billtocustomer_link_id
      and lbank.laundrybank = 'Y' and lbank.defaultlaundrybank = 'Y'

/
create or replace view V_INVOICECLIENT_CBD
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, ACTIVITYREFERENCE, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE
, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY
, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC
, INVOICELAYOUTCODE, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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
, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE
, INVOICEREMARKENDDATE, INTERNALVATNUMBER, VATNUMBER, CLIENT_LINK_ID, IHCLIENTNUMBER, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, IHCCLIENTTYPE, CLIENTINVOICETYPE, PAYMENTTERMSDUEDATE, BILL_LEGAL_NAME, PRINTTAXONAPPENDIX, CUSTBILLINGCOMMENT, EMPLOYEENAME, EMPLOYEEPHONENO, EMPLOYEEMOBILENO, EMPLOYEEFAXNO, EMPLOYEEEMAIL, WO_REFNR, DELPOINTADDRESS, SALESAREA)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       a.invoicenumber,a.activityreference, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, cast(
       a.billtocustomername as varchar2(60)) billtocustomername
       , a.extraname1, a.extraname2,
       a.deltocustomernumber, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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_6_YEARWEEKS(a.invoiceheader_id, a.invoicefrequency_id) as varchar2(47)) min_year_weeks,
, cast(CBD_FSGET_MIN_6_YEARWEEKS_REV(a.invoiceheader_id, a.invoicefrequency_id) as varchar2(47)) 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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 number(1)) 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
       , ihc.sendinvoiceto, ihc.roomnumber ihcroomnumber, ihc.clienttype ihcclienttype
       , ihc.clientinvoicetype
       , ihextr.paymenttermsduedate
       , (SELECT c.legalname FROM customer c WHERE c.customer_id=a.billtocustomer_link_id) BILL_LEGAL_NAME --todo6927
       , (select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix
       , (select max(cbc.description) from customerbillingcomment cbc where cbc.customer_id = a.billtocustomer_link_id) custbillingcomment
, emp.name employeename, emp.phoneno employeephoneno, emp.mobileno employeemobileno, emp.faxno employeefaxno, emp.email employeeemail
, (select max(wo.referencenumber) from workorder wo where wo.invoiceheader_id = a.invoiceheader_id) WO_RefNr,  --cast(
 (select max(delad.street || CHR(13) || delad.zipcode || ' ' || delad.city) from workorder wo, distributionpoint dp, deliverypoint delp, address delad
   where wo.invoiceheader_id = a.invoiceheader_id and wo.distributionpoint_link_id = dp.distributionpoint_id
   and dp.deliverypoint_id = delp.deliverypoint_id and delp.deliveryaddress_id = delad.address_id) --as varchar2(60))
DelPointAddress, dell.salesarea_id Salesarea
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 dell
             left outer join employee emp on dell.serviceemployee_id = emp.employee_id
        on a.deltocustomer_link_id = dell.customer_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)
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

/
create or replace view V_INVOICECLIENT_CIW
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, ACTIVITYREFERENCE, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE
, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, PLANTCOMPANYPHONE
, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES
, PAYMENTTERMS_DESC, INVOICELAYOUTCODE, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER
, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, INTERNALVATNUMBER, VATNUMBER, CLIENT_LINK_ID, IHCLIENTNUMBER, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, IHCCLIENTTYPE, CLIENTINVOICETYPE, PAYMENTTERMSDUEDATE, BILL_LEGAL_NAME, CUSTOMERTAXABLE)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       a.invoicenumber,a.activityreference, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, a.billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, a.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,
       (select pc.phone from plantcompany pc where pc.code = (select min(pc.code) from plantcompany pc where pc.plant_id = p.plant_id) and pc.plant_id = p.plant_id) plantcompanyphone,
       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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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
       , ihc.clientinvoicetype--502813
       , ihextr.paymenttermsduedate
       , (SELECT c.legalname FROM customer c WHERE c.customer_id=a.billtocustomer_link_id) BILL_LEGAL_NAME --todo6927
       , (select c.taxable from customer c where c.customer_id = a.billtocustomer_link_id) customertaxable
       --, (select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix
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),--501528
      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)
where a.currency_id = b.currency_id--      and a.documenttype = 1
      and a.documenttype in (1, 3) --501528
      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

/
create or replace view V_INVOICECLIENT_DELNOTE_LTS
 (REMARK, INVOICEHEADER_ID)
as SELECT DISTINCT /*CAST ((*/trim(PN.REMARK)/*) AS VARCHAR2(60))*/ REMARK,
                PNL.INVOICEHEADER_ID
  FROM PACKINGNOTE PN, INVOICEHEADER IH, PACKINGNOTELINE PNL
 WHERE PN.PACKINGNOTE_ID = PNL.PACKINGNOTE_ID
   AND PNL.INVOICEHEADER_ID = IH.INVOICEHEADER_ID
   and PN.REMARK IS NOT NULL

/
create or replace view V_INVOICECLIENT_DELNOTE_PRI
 (NOTENUMBER, REMARK, REFERENCE, INVOICEHEADER_ID)
as SELECT DISTINCT PN.NOTENUMBER,
                /*CAST ((*/PN.REMARK/*) AS VARCHAR2(60)) REMARK*/,
                -- CAST (
                (SELECT DV.REFERENCE
                   FROM DELIVERYVARIATIONS DV
                  WHERE PNL.PRODUCT_ID = DV.PRODUCT_ID
                    AND PNL.SIZEDEFINITION_ID = DV.SIZEDEFINITION_ID
                    AND PNL.FINISHINGMETHOD_ID = DV.FINISHINGMETHOD_ID
                    AND PN.PACKINGNOTE_ID = DV.PACKINGNOTE_ID) REFERENCE,
                -- AS VARCHAR2(60)) REFERENCE,
                PNL.INVOICEHEADER_ID
  FROM PACKINGNOTE PN, INVOICEHEADER IH, PACKINGNOTELINE PNL
 WHERE PN.PACKINGNOTE_ID = PNL.PACKINGNOTE_ID
   AND PNL.INVOICEHEADER_ID = IH.INVOICEHEADER_ID
 ORDER BY PN.NOTENUMBER

/
create or replace view V_INVOICECLIENT_DFD
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, ACTIVITYREFERENCE, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, DELTOLEGALNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS
, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL
, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, DELTOCOUNTRYCODE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS
, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE, ACCEPTGIROCODELINE, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, WEEKSDIFFERENCE, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT
, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, INTERNALVATNUMBER, VATNUMBER, CLIENT_LINK_ID, IHCLIENTNUMBER, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, IHCCLIENTTYPE, CLIENTINVOICETYPE, PAYMENTTERMSDUEDATE, BILL_LEGAL_NAME, PRINTTAXONAPPENDIX, CUSTBILLINGCOMMENT, PLANTLANGUAGECODE, DISCOUNTDESCMIN)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       a.invoicenumber,a.activityreference, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, a.billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, (select custl.name  from customer custl where custl.customer_id = a.deltocustomer_link_id) deltocustomername, (select custl.legalname  from customer custl where custl.customer_id = a.deltocustomer_link_id) deltolegalname,
       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 ct.code from country ct, customer c where ct.country_id = c.country_id and c.customer_id = a.deltocustomer_link_id) deltocountrycode,
       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,
       ihextr.formlayoutcode invoicelayoutcode, ihextr.acceptgirocodeline,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode,
--, 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
, GETWEEKSDIFFERENCE_BDE(YEAR(A.NEXTPERIODSTARTDATE), A.NEXTPERIODSTARTWEEK, YEAR(A.NEXTPERIODENDDATE), A.NEXTPERIODENDWEEK) WEEKSDIFFERENCE,
       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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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,
       A.NEXTPERIODSTARTWEEK, A.NEXTPERIODENDWEEK,
       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
			 , ihc.clientinvoicetype--502813
       , ihextr.paymenttermsduedate
       , (SELECT c.legalname FROM customer c WHERE c.customer_id=a.billtocustomer_link_id) BILL_LEGAL_NAME --todo6927
       , (select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix
       , (select cbc.description from customerbillingcomment cbc where cbc.customer_id = a.billtocustomer_link_id) custbillingcomment
       , (select lan.code from languages lan where lan.language_id = p.language_id) plantlanguagecode
       --, (select contact.contactpersonname from contact where contact.customer_link_id = a.deltocustomer_link_id) delto_contactpersonname
       , coalesce((select min(il.description) from invoiceline il where il.invoiceheader_id = a.invoiceheader_id and il.invoicelinetype_id = 16 and il.code like 'RA%'), 'Rabat') discountdescmin
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),--501528
      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)
where a.currency_id = b.currency_id--      and a.documenttype = 1
      and a.documenttype in (1, 3) --501528
      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

/
create or replace view V_INVOICECLIENT_DIA
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, ACTIVITYREFERENCE, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE
, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY
, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC
, INVOICELAYOUTCODE, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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
, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE
, INVOICEREMARKENDDATE, INTERNALVATNUMBER, VATNUMBER, CLIENT_LINK_ID, IHCLIENTNUMBER, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, IHCCLIENTTYPE, CLIENTINVOICETYPE, IHCCLIENTGENDER, IHCCLIENTFIRSTNAME, IHCCLIENTNAME, PAYMENTTERMSDUEDATE, BILL_LEGAL_NAME, PRINTTAXONAPPENDIX, CUSTBILLTOCOMMENT, CUSTDELTOCOMMENT, SENDINVOICEBY)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       a.invoicenumber,a.activityreference, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, a.billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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
       , ihc.clientinvoicetype--502813
       , cl.gender ihcclientgender--30824
       , cl.firstname ihcclientfirstname--30824
       , cl.name ihcclientname--30824
       , ihextr.paymenttermsduedate
       , (SELECT c.legalname FROM customer c WHERE c.customer_id=a.billtocustomer_link_id) BILL_LEGAL_NAME --todo6927
       , (select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix
       , (select cbc.description from customerbillingcomment cbc where cbc.customer_id = a.billtocustomer_link_id) custbilltocomment
       , (select cbc.description from customerbillingcomment cbc where cbc.customer_id = a.deltocustomer_link_id) custdeltocomment
       , (select cbi.SENDINVOICEBY from customerbillinginfo cbi where a.billtocustomer_link_id=cbi.customer_id) sendinvoiceby
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)--501528
        LEFT OUTER JOIN client cl ON (ihc.client_link_id = cl.client_id),--30824
      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)
where a.currency_id = b.currency_id--      and a.documenttype = 1
      and a.documenttype in (1, 3) --501528
      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

/
create or replace view V_INVOICECLIENT_DN_PAN
 (NOTENUMBER, DELIVERYDATE, INVOICEHEADER_ID)
as select distinct pn.notenumber,
       pn.deliverydate,
       pnl.invoiceheader_id
  from packingnote pn, packingnoteline pnl, invoiceline il
 where pn.packingnote_id = pnl.packingnote_id
   and pnl.invoiceheader_id = il.invoiceheader_id
   order by pn.deliverydate, pn.notenumber

/
create or replace view V_INVOICECLIENT_DRE
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, ACTIVITYREFERENCE, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE
, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY
, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC
, INVOICELAYOUTCODE, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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
, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE
, INVOICEREMARKENDDATE, INTERNALVATNUMBER, VATNUMBER, CLIENT_LINK_ID, IHCLIENTNUMBER, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, IHCCLIENTTYPE, CLIENTINVOICETYPE, PAYMENTTERMSDUEDATE, BILL_LEGAL_NAME, PRINTTAXONAPPENDIX, CUSTBILLTOCOMMENT, CUSTDELTOCOMMENT, PREBILLAMOUNT_STR, BILLTOCHAIN_CODE)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       a.invoicenumber,a.activityreference, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, a.billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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
       , ihc.clientinvoicetype--502813
       , ihextr.paymenttermsduedate
       , (SELECT c.legalname FROM customer c WHERE c.customer_id=a.billtocustomer_link_id) BILL_LEGAL_NAME --todo6927
       , (select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix
       , (select cbc.description from customerbillingcomment cbc where cbc.customer_id = a.billtocustomer_link_id) custbilltocomment
       , (select cbc.description from customerbillingcomment cbc where cbc.customer_id = a.deltocustomer_link_id) custdeltocomment
       , --              cast(
       f_spell_numberNL(a.prebillamount)--             as varchar2(250))
       prebillamount_str
       , (select ch.code from customer cu, chain ch WHERE cu.customer_id=a.billtocustomer_link_id and ch.chain_id = cu.chain_id) billtochain_code
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),--501528
      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)
where a.currency_id = b.currency_id--      and a.documenttype = 1
      and a.documenttype in (1, 3) --501528
      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

/
create or replace view V_INVOICECLIENT_ECL
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, ACTIVITYREFERENCE, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE
, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY
, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC
, INVOICELAYOUTCODE, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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
, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE
, INVOICEREMARKENDDATE, INTERNALVATNUMBER, VATNUMBER, CLIENT_LINK_ID, IHCLIENTNUMBER, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, IHCCLIENTTYPE, CLIENTINVOICETYPE, PAYMENTTERMSDUEDATE, BILL_LEGAL_NAME, PRINTTAXONAPPENDIX, CUSTBILLTOCOMMENT, CUSTDELTOCOMMENT, SENDINVOICEBY, LEGACYDELLTOCUSTOMER, LEGACYBILLTOCUSTOMER, TVA, TVA_AMOUNT)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       a.invoicenumber,a.activityreference, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, a.billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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
       , ihc.clientinvoicetype--502813
       , ihextr.paymenttermsduedate
       , (SELECT c.legalname FROM customer c WHERE c.customer_id=a.billtocustomer_link_id) BILL_LEGAL_NAME --todo6927
       , (select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix
       , (select cbc.description from customerbillingcomment cbc where cbc.customer_id = a.billtocustomer_link_id) custbilltocomment
       , (select cbc.description from customerbillingcomment cbc where cbc.customer_id = a.deltocustomer_link_id) custdeltocomment
       , (select cbi.SENDINVOICEBY from customerbillinginfo cbi where a.billtocustomer_link_id=cbi.customer_id) sendinvoiceby,
       (select cus.legacycustomernumber from customer cus where cus.customer_id=a.deltocustomer_link_id) legacydelltocustomer,
       (select cus.legacycustomernumber from customer cus where cus.customer_id=a.billtocustomer_link_id) legacybilltocustomer,
              (select MAX(c.percentage) from invoiceline il LEFT OUTER JOIN invoicelinevarious c ON (il.invoiceline_id = c.invoiceline_id) where il.invoiceheader_id=a.invoiceheader_id and il.invoicelinetype_id=18) tva,
       (select sum(il.amount) from invoiceline il where il.invoiceheader_id=a.invoiceheader_id and il.invoicelinetype_id=18 /*and il.description='TVA'*/) tva_amount
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),--501528
      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)
where a.currency_id = b.currency_id--      and a.documenttype = 1
      and a.documenttype in (1, 3) --501528
      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

/
create or replace view V_INVOICECLIENT_EDE
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS
, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE
, INTERNALVATNUMBER, VATNUMBER, CLIENT_LINK_ID, IHCLIENTNUMBER, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, IHCCLIENTTYPE, CLIENTINVOICETYPE, PAYMENTTERMSDUEDATE, BILL_LEGAL_NAME, ROUTEDESC, CLIENTBANKACCOUNT, CLIENTDEBTORNR, BILLTOCUSTOMERVATNUMBER)
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
,      a.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
,      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
,      ihextr.formlayoutcode invoicelayoutcode
,      e.code default_BU_code
,      ( 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
,      rc.code Adjustment_ReasonCode
,      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
,      a.deltostreet
,      a.deltostreet2
,      a.deltocounty
,      a.deltocity
,      a.deltozipcode
,      a.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
,      ihc.sendinvoiceto
,      ihc.roomnumber ihcroomnumber
,      ihc.clienttype ihcclienttype
,      ihc.clientinvoicetype
,      ihextr.paymenttermsduedate
,      ( select c.legalname
         from   customer c
         where  c.customer_id = a.billtocustomer_link_id) BILL_LEGAL_NAME
,      ( select r.description
         from   route r
         where  r.route_id = a.route_id) routedesc
,      ( select cbi.bankaccountnumber
         from   clientbillinginfo cbi
         where  cbi.client_id = cl.client_id ) clientbankaccount
,      ( select cbi.debtornumber
         from   clientbillinginfo cbi
         where  cbi.client_id = cl.client_id ) clientdebtornr
,      ( select cus.vatnumber from customer cus where cus.customer_id = a.billtocustomer_link_id ) billtocustomervatnumber
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 left outer join client_link cl on cl.client_link_id = ihc.client_link_id)
             on (a.invoiceheader_id = ihc.invoiceheader_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)
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

/
create or replace view V_INVOICECLIENT_ELI
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, ACTIVITYREFERENCE, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, PURCHASEORDER, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS
, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY
, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC
, INVOICELAYOUTCODE, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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
, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE
, INVOICEREMARKENDDATE, INTERNALVATNUMBER, VATNUMBER, CLIENT_LINK_ID, IHCLIENTNUMBER, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, IHCCLIENTTYPE, CLIENTINVOICETYPE, PAYMENTTERMSDUEDATE, BILL_LEGAL_NAME, PRINTTAXONAPPENDIX, CUSTBILLTOCOMMENT, CUSTDELTOCOMMENT, SENDINVOICEBY, SALESPERSON, CREATIONUSEREMPLOYEE, CREATIONUSERPHONE, DELPOINTNAME, DELPOINTSTREET, DELPOINTSTREET2, DELPOINTZIP, DELPOINTCITY, PRINTDATE, WONUMBER, REFWONUMBER, SALES_EXTERNALREMARK)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       a.invoicenumber,a.activityreference, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, a.billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, a.deltocustomername, a.purchaseorder,
       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.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (select max(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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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
       , ihc.clientinvoicetype--502813
       , ihextr.paymenttermsduedate
       , (SELECT c.legalname FROM customer c WHERE c.customer_id=a.billtocustomer_link_id) BILL_LEGAL_NAME --todo6927
       , (select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix
       , (select max(cbc.description) from customerbillingcomment cbc where cbc.customer_id = a.billtocustomer_link_id) custbilltocomment
       , (select max(cbc.description) from customerbillingcomment cbc where cbc.customer_id = a.deltocustomer_link_id) custdeltocomment
       , (select cbi.SENDINVOICEBY from customerbillinginfo cbi where a.billtocustomer_link_id=cbi.customer_id) sendinvoiceby
,      ( select emp.name from   employee emp
         where  emp.dateactive <= a.invoicedate
            and (emp.dateinactive is null or emp.dateinactive > a.invoicedate)
            and emp.employee_id in (select coalesce(c.salesemployee1_id, c.salesemployee2_id) from   customer c where c.customer_id=a.billtocustomer_link_id)) SalesPerson
, ( select emp.name from employee emp
         where emp.dateactive <= a.invoicedate
            and (emp.dateinactive is null or emp.dateinactive > a.invoicedate)
            and emp.employee_id in (select c.serviceemployee_id from   customer c where c.customer_id=a.billtocustomer_link_id)) CreationUserEmployee
, p.phoneno CreationUserPhone
, dp.description delpointname
, ad.street delpointstreet
, ad.street2 delpointstreet2
, ad.zipcode delpointzip
, ad.city delpointcity
, a.printdate
, (select max(wo.workordernumber) from garmentsaleshistory gsh, workorderline wol, workorder wo
          where gsh.invoiceheader_id = a.invoiceheader_id
          and gsh.workorderline_id = wol.workorderline_id
          and wol.workorder_id = wo.workorder_id
          and wo.origin = 6) wonumber
, (select max(wo.referencenumber) from garmentsaleshistory gsh, workorderline wol, workorder wo
          where gsh.invoiceheader_id = a.invoiceheader_id
          and gsh.workorderline_id = wol.workorderline_id
          and wol.workorder_id = wo.workorder_id
          and wo.origin = 6) refwonumber
, (select max(DBMS_LOB.SUBSTR(wo.externalremark, 4000, 1)) from garmentsaleshistory gsh, workorderline wol, workorder wo
          where gsh.invoiceheader_id = a.invoiceheader_id
          and gsh.workorderline_id = wol.workorderline_id
          and wol.workorder_id = wo.workorder_id
          and wo.origin = 6) sales_externalremark
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 (select * from deliverypoint dp where dp.code = (select min(dp1.code) from deliverypoint dp1 where dp1.customer_id = dp.customer_id)) dp
             LEFT OUTER JOIN address ad on dp.deliveryaddress_id = ad.address_id
        on dp.customer_id = a.deltocustomer_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)
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

/
create or replace view V_INVOICECLIENT_FIS
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS
, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, DELTOEXTRANAME1, DELTOEXTRANAME2, DELTOCONTACTPERSONNAME, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER
, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, INTERNALVATNUMBER, VATNUMBER, CLIENT_LINK_ID, IHCLIENTNUMBER, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, IHCCLIENTTYPE, PAYMENTTERMSDUEDATE, BILL_LEGAL_NAME, BILL_SEARCHNAME, FORMLAYOUTCODE, BILL_LEGACYCUSTOMERNUMBER)
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, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.deltostate,
(SELECT delto.extraname1 FROM customer delto WHERE a.deltocustomer_link_id = delto.customer_id) deltoextraname1,
(SELECT delto.extraname2 FROM customer delto WHERE a.deltocustomer_link_id = delto.customer_id) deltoextraname2,
(SELECT max(cp.name) FROM contactperson cp WHERE a.deltocustomer_link_id = cp.customer_id AND cp.invoicecontactperson = 'Y') deltocontactpersonname,
       country.description PLANTCOUNTRYDESCRIPTION
			 , (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 = 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
			 , (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, 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 c.legalname FROM customer c WHERE c.customer_id=a.billtocustomer_link_id) BILL_LEGAL_NAME --todo6927
       , (SELECT c.searchname FROM customer c WHERE c.customer_id=a.billtocustomer_link_id) BILL_SEARCHNAME
			 , ihextr.formlayoutcode
       , (SELECT c.legacycustomernumber FROM customer c WHERE c.customer_id=a.billtocustomer_link_id) bill_legacycustomernumber
from  currency b, businessunit e, status s, plant p, 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),--501528
      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)
where a.currency_id = b.currency_id--      and a.documenttype = 1
      and a.documenttype in (1, 3) --501528
      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

/
create or replace view V_INVOICECLIENT_HOW
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, ORIGINALENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, ORIGINALPAYMENTTERMS_DESC
, INVOICELAYOUTCODE, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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
, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE
, INVOICEREMARKENDDATE, INTERNALVATNUMBER, VATNUMBER, CLIENT_LINK_ID, IHCLIENTNUMBER, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, IHCCLIENTTYPE, PAYMENTTERMSDUEDATE, ORIGINALPAYMENTTERMSDUEDATE, BILL_LEGAL_NAME, NOOFDAYS, EXCHANGERATE, BILLTO_PHONENO, BILLTO_FAXNO, BILLTO_EMAIL, PARENTINVNUMBER, CHILDNUMBER)
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, --a.deltocustomername,
       coalesce (dp.code ,a.deltocustomername) 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,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
        --a.deltostreet,a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.deltostate,
       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)--501528
        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) --501528
      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_INVOICECLIENT_HRB
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, ACTIVITYREFERENCE, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE
, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY
, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC
, INVOICELAYOUTCODE, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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
, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE
, INVOICEREMARKENDDATE, INTERNALVATNUMBER, VATNUMBER, CLIENT_LINK_ID, IHCLIENTNUMBER, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, IHCCLIENTTYPE, CLIENTINVOICETYPE, PAYMENTTERMSDUEDATE, BILL_LEGAL_NAME, PRINTTAXONAPPENDIX, CUSTBILLTOCOMMENT, CUSTDELTOCOMMENT, SENDINVOICEBY, COCNUMBER, EUR_EXCHANGERATE, DRIVERNAME, DRIVERREMARK, PONUMBER, INV_EXCHANGERATE, CURRENCY_DESC, CURRENCY_ID, DEFAULTCURRENCY_ID, LICENCEPLATE)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       a.invoicenumber,a.activityreference, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, a.billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, a.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, (select bill_adr.city from address bill_adr where bill_adr.address_id = deb.invoiceaddress_id) 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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.deltocounty 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
       , (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
       , ihc.clientinvoicetype--502813
       , ihextr.paymenttermsduedate
       , deb.legalname BILL_LEGAL_NAME --todo6927
       , deb.printtaxonappendix
       , (select cbc.description from customerbillingcomment cbc where cbc.customer_id = a.billtocustomer_link_id) custbilltocomment
       , (select cbc.description from customerbillingcomment cbc where cbc.customer_id = a.deltocustomer_link_id) custdeltocomment
       , (select cbi.SENDINVOICEBY from customerbillinginfo cbi where a.billtocustomer_link_id=cbi.customer_id) sendinvoiceby
       , deb.cocnumber, b.exchangerate EUR_ExchangeRate
       , (select max(em.name)
          from stop s, routecontrol rcl, employee em
          where s.routecontrol_id = rcl.routecontrol_id
          and s.customer_link_id = a.deltocustomer_link_id
          AND s.STATUS in (0,3)
          and em.employeenumber = rcl.drivernumber and em.plant_id = rcl.plant_id
          and rcl.drivingdate in (select max(rcl.drivingdate)
                                  from  stop s, routecontrol rcl, employee em
                                  where s.routecontrol_id = rcl.routecontrol_id
                                  and s.customer_link_id = a.deltocustomer_link_id
                                  AND s.STATUS in (0,3)
                                  and em.employeenumber = rcl.drivernumber and em.plant_id = rcl.plant_id
                                  and rcl.drivingdate <= a.invoicedate )) driverName
       , (select max(em.remark)
          from stop s, routecontrol rcl, employee em
          where s.routecontrol_id = rcl.routecontrol_id
          and s.customer_link_id = a.deltocustomer_link_id
          AND s.STATUS in (0,3)
          and em.employeenumber = rcl.drivernumber and em.plant_id = rcl.plant_id
          and rcl.drivingdate in (select max(rcl.drivingdate)
                                  from  stop s, routecontrol rcl, employee em
                                  where s.routecontrol_id = rcl.routecontrol_id
                                  and s.customer_link_id = a.deltocustomer_link_id
                                  AND s.STATUS in (0,3)
                                  and em.employeenumber = rcl.drivernumber and em.plant_id = rcl.plant_id
                                  and rcl.drivingdate <= a.invoicedate )) driverRemark
       , /*(select max(cc.ponumber) from costcenter cc, department dep where dep.costcenter_id = cc.costcenter_id and dep.customer_id = a.deltocustomer_link_id)*/
       (select LISTAGG(cpc.purchaseorder, ', ') within group (order by cpc.purchaseorder)
          from contractspercustomer cpc Where cpc.customer_id = a.billtocustomer_link_id) ponumber
       , b.exchangerate Inv_ExchangeRate, '1 ' || b.description Currency_Desc, b.currency_id, country.defaultcurrency_id
       , (select max(tr.description)
          from stop s, routecontrol rcl, truck tr
          where s.routecontrol_id = rcl.routecontrol_id
          and s.customer_link_id = a.deltocustomer_link_id
          AND s.STATUS in (0,3)
          and tr.code = rcl.truckcode
          and rcl.drivingdate in (select max(rcl.drivingdate)
                                  from  stop s, routecontrol rcl
                                  where s.routecontrol_id = rcl.routecontrol_id
                                  and s.customer_link_id = a.deltocustomer_link_id
                                  AND s.STATUS in (0,3)
                                  and rcl.drivingdate <= a.invoicedate )) LicencePlate
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 customer deb ON (deb.customer_id=a.billtocustomer_link_id)
        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),--501528
      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)
where a.currency_id = b.currency_id--      and a.documenttype = 1
      and a.documenttype in (1, 3) --501528
      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

/
create or replace view V_INVOICECLIENT_LLG
 (INVOICEDATE, INVOICENUMBER, ACTIVITYREFERENCE, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, CITY, ZIPCODE, STREET, CONTACTPERSONNAME, ORIGINALCOLLECTIONTYPE, PURCHASEORDER, INVOICECOMMENTS, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, STATUSTYPE, STATUSCODE, BILLTO_CITY, BILLTO_STREET
, BILLTO_STREET2, BILLTO_ZIPCODE, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, TOTALAMOUNTEXCLVAT, DECIMALS, ENDDATE, PAYMENTTERMS_DESC, INVOICELAYOUTCODE, SPLITUPCODE, SPLITUPDESCRIPTION, PARENTINVOICEHEADER_ID, CREDITSQUEEZEPERC, DELTOSTREET, DELTOSTREET2, DELTOCITY, DELTOZIPCODE, ROUNDINGAMOUNT, NEXTPERIODENDDATE, DISCOUNTDAYS, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER
, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, CLIENTINVOICETYPE, PAYMENTTERMSDUEDATE, BILLTOSEARCHNAME, BILLTOLEGALNAME, BILLTOLEGACYCUSTNUMBER, BILLTOCHAINDESCR, RENTSTOPSTARTDATE, RENTSTOPENDDATE, NA_CODE, NA_NAME, BILLTOCUSTOMERNAME_CUST, DELTOCUSTOMERNAME_CUST)
as select a.invoicedate,
       a.invoicenumber,a.activityreference, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, a.billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, a.deltocustomername,
       a.startweek, a.endweek, a.startmonth, a.endmonth,
       a.city, a.zipcode, a.street,
       a.contactpersonname, a.originalcollectiontype,
       a.purchaseorder,
       a.invoicecomments,
       a.paythisamount, a.prebillamount, a.invoicefrequency_id invoicefrequencynumber,
       b.code currencycode,
       s.statustype, s.code statuscode,
       a.city billto_city, a.street billto_street,
       a.street2 billto_Street2, a.zipcode billto_zipcode, a.invoiceheader_id,
       a.creditsqueezeamount, b.invoiceamountdecimals, a.totalamountexclvat,
       b.decimals, a.enddate,
       ihextr.paymenttermsdescription paymentterms_desc,
       ihextr.formlayoutcode invoicelayoutcode,
       a.splitupcode, a.splitupdescription,
       a.parentinvoiceheader_id, a.creditsqueezeperc,
       a.deltostreet, a.deltostreet2, a.deltocity, a.deltozipcode,
       a.roundingamount, A.NEXTPERIODENDDATE, ihextr.discountdays, ihextr.discountdays2, ihextr.paymentdiscount2
       , cast(SS1.VALUE as numeric) WEIGHTDECIMALSMANUALINPUT
       , (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, ihc.name ihclientname--501528
       , ihc.sendinvoiceto, ihc.roomnumber ihcroomnumber--501528
			 , ihc.clientinvoicetype--502813
       , ihextr.paymenttermsduedate
       , (select c.searchname from customer c where c.customer_id = a.billtocustomer_link_id) billtosearchname
       , (select c.legalname from customer c where c.customer_id = a.billtocustomer_link_id) billtolegalname
       , (select c.legacycustomernumber from customer c where c.customer_id = a.billtocustomer_link_id) billtolegacycustnumber
       , (select ch.name from customer c, chain ch where ch.chain_id = c.chain_id and c.customer_id = a.billtocustomer_link_id ) billtochaindescr
       , a.rentstopstartdate
       , a.rentstopenddate
       , (select na.code from nationalaccount na, customer c where na.nationalaccount_id = c.nationalaccount_id
                                                             and c.customer_id = a.billtocustomer_link_id) na_code
       , (select na.name from nationalaccount na, customer c where na.nationalaccount_id = c.nationalaccount_id
                                                             and c.customer_id = a.billtocustomer_link_id) na_name
       , (select c.name from customer c where c.customer_id = a.billtocustomer_link_id) billtocustomername_cust
       , (select c.name from customer c where c.customer_id = a.deltocustomer_link_id) deltocustomername_cust
from  currency b,
      businessunit e, status s,
      plant p
        LEFT OUTER JOIN SYSTEMSETTING SS1 ON (P.PLANT_ID = SS1.PLANT_ID AND SS1.NAME = 'WEIGHTDECIMALSMANUALINPUT'),
      country,
      invoiceheader a
        LEFT OUTER JOIN invoiceheaderclient ihc ON (a.invoiceheader_id = ihc.invoiceheader_id),--501528
      invoiceheaderextrainfo ihextr
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 a.invoiceheader_id = ihextr.invoiceheader_id

/
create or replace view V_INVOICECLIENT_MFM
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, ACTIVITYREFERENCE, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE
, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, PLANTCOUNTRY
, DEFPLANTDEPART, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS
, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT
, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, INTERNALVATNUMBER, VATNUMBER, CLIENT_LINK_ID, IHCLIENTNUMBER, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, IHCCLIENTTYPE, CLIENTINVOICETYPE, PAYMENTTERMSDUEDATE, BILL_LEGAL_NAME, PRINTTAXONAPPENDIX, CUSTBILLTOCOMMENT, CUSTDELTOCOMMENT)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       a.invoicenumber,a.activityreference, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, a.billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, a.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,
       (select c.description from country c where p.country_id = c.country_id) plantcountry,
       (select pd.description from plantdepartment pd, plant p2, businessunit bu2, customer c2
        where pd.plant_id = p2.plant_id and pd.defaultplantdepartment = 'Y'
        and p2.plant_id = bu2.plant_id
        and bu2.businessunit_id = c2.defaultbusinessunit_id
        and c2.customer_id = a.billtocustomer_link_id) defplantdepart,
       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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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
			 , ihc.clientinvoicetype--502813
       , ihextr.paymenttermsduedate
       , (SELECT c.legalname FROM customer c WHERE c.customer_id=a.billtocustomer_link_id) BILL_LEGAL_NAME --todo6927
       , (select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix
       , (select cbc.description from customerbillingcomment cbc where cbc.customer_id = a.billtocustomer_link_id) custbilltocomment
       , (select cbc.description from customerbillingcomment cbc where cbc.customer_id = a.deltocustomer_link_id) custdeltocomment
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),--501528
      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)
where a.currency_id = b.currency_id--      and a.documenttype = 1
      and a.documenttype in (1, 3) --501528
      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

/
create or replace view V_INVOICECLIENT_PAN
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS
, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE
, INTERNALVATNUMBER, VATNUMBER, CLIENT_LINK_ID, IHCLIENTNUMBER, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, IHCCLIENTTYPE, CLIENTINVOICETYPE, PAYMENTTERMSDUEDATE, BILL_LEGAL_NAME, LEGACYCUSTOMERNUMBER)
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, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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
       , ihc.clientinvoicetype--502813
       , ihextr.paymenttermsduedate
       , (SELECT c.legalname FROM customer c WHERE c.customer_id=a.billtocustomer_link_id) BILL_LEGAL_NAME --todo6927
       , (SELECT c.legacycustomernumber FROM customer c WHERE c.customer_id=a.billtocustomer_link_id) legacycustomernumber
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),--501528
      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)
where a.currency_id = b.currency_id
      and a.documenttype in (1, 3) --501528
      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

/
create or replace view V_INVOICECLIENT_PHS
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, ACTIVITYREFERENCE, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE
, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY
, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC
, INVOICELAYOUTCODE, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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
, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE
, INVOICEREMARKENDDATE, INTERNALVATNUMBER, VATNUMBER, CLIENT_LINK_ID, IHCLIENTNUMBER, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, IHCCLIENTTYPE, CLIENTINVOICETYPE, PAYMENTTERMSDUEDATE, BILL_LEGAL_NAME, PRINTTAXONAPPENDIX, CUSTDELTOCOMMENT, SENDINVOICEBY, POCOSTCENTRE)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       a.invoicenumber,a.activityreference, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, a.billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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
       , ihc.clientinvoicetype--502813
       , ihextr.paymenttermsduedate
       , (SELECT c.legalname FROM customer c WHERE c.customer_id=a.billtocustomer_link_id) BILL_LEGAL_NAME --todo6927
       , (select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix
       --, (select cbc.description from customerbillingcomment cbc where cbc.customer_id = a.billtocustomer_link_id) custbilltocomment
       , (select cbc.description from customerbillingcomment cbc where cbc.customer_id = a.deltocustomer_link_id) custdeltocomment
       , (select cbi.SENDINVOICEBY from customerbillinginfo cbi where a.billtocustomer_link_id=cbi.customer_id) sendinvoiceby
, (select max(cc.ponumber) from costcenter cc, costcenterinvoiceline ccil, invoiceline il where ccil.costcenter_link_id = cc.costcenter_id
   and ccil.invoiceline_id = il.invoiceline_id and il.invoiceheader_id = a.invoiceheader_id) POCOSTCENTRE
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),--501528
      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)
where a.currency_id = b.currency_id--      and a.documenttype = 1
      and a.documenttype in (1, 3) --501528
      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

/
create or replace view V_INVOICECLIENT_PRI
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, ACTIVITYREFERENCE, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE
, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY
, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC
, INVOICELAYOUTCODE, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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
, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE
, INVOICEREMARKENDDATE, INTERNALVATNUMBER, VATNUMBER, CLIENT_LINK_ID, IHCLIENTNUMBER, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, IHCCLIENTTYPE, CLIENTINVOICETYPE, PAYMENTTERMSDUEDATE, BILL_LEGAL_NAME, PRINTTAXONAPPENDIX, CUSTBILLTOCOMMENT, CUSTDELTOCOMMENT, LEGACYCODE, CUSTOMERBILLINGCOMMENT, TOTALREF, TOTALNOTENUMBER)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       a.invoicenumber,a.activityreference, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, a.billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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
       , /*cast(*/(SELECT pldesc.invoiceremark FROM plantinvoiceremark_desc pldesc
          where pldesc.plant_id = p.plant_id and pldesc.language_id = p.language_id) /*as varchar(50))*/ 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
			 , ihc.clientinvoicetype--502813
       , ihextr.paymenttermsduedate
       , (SELECT c.legalname FROM customer c WHERE c.customer_id=a.billtocustomer_link_id) BILL_LEGAL_NAME --todo6927
       , (select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix
       , (select cbc.description from customerbillingcomment cbc where cbc.customer_id = a.billtocustomer_link_id) custbilltocomment
       , (select cbc.description from customerbillingcomment cbc where cbc.customer_id = a.deltocustomer_link_id) custdeltocomment
       , (select c.legacycustomernumber from customer c where c.customer_id = a.billtocustomer_link_id) legacycode
       , /*cast(*/(select cbc.description from customerbillingcomment cbc where cbc.customer_id = a.billtocustomer_link_id and cbc.type=1) /*as varchar2(50))*/ customerbillingcomment
       , (select distinct count(dv.reference) from packingnote pn, packingnoteline pnl, deliveryvariations dv where pn.packingnote_id = pnl.packingnote_id and pn.packingnote_id = dv.packingnote_id and pnl.invoiceheader_id = a.invoiceheader_id and dv.reference is not null) TOTALREF
       , (select distinct count(pn.notenumber) from packingnote pn, packingnoteline pnl, deliveryvariations dv where pn.packingnote_id = pnl.packingnote_id and pn.packingnote_id = dv.packingnote_id and pnl.invoiceheader_id = a.invoiceheader_id) TOTALNOTENUMBER
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),--501528
      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)
where a.currency_id = b.currency_id--      and a.documenttype = 1
      and a.documenttype in (1, 3) --501528
      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

/
create or replace view V_INVOICECLIENT_RAS
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS
, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE
, INTERNALVATNUMBER, VATNUMBER, CLIENT_LINK_ID, IHCLIENTNUMBER, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, IHCCLIENTTYPE, CLIENTINVOICETYPE, PAYMENTTERMSDUEDATE, BILL_LEGAL_NAME, SENDINVOICEBY)
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, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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
			 , ihc.clientinvoicetype--502813
       , ihextr.paymenttermsduedate
       , (SELECT c.legalname FROM customer c WHERE c.customer_id=a.billtocustomer_link_id) BILL_LEGAL_NAME --todo6927
       , (select cbi.sendinvoiceby from customerbillinginfo cbi where cbi.customer_id = a.billtocustomer_link_id) sendinvoiceby
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),--501528
      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)
where a.currency_id = b.currency_id--      and a.documenttype = 1
      and a.documenttype in (1, 3) --501528
      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

/
create or replace view V_INVOICECLIENT_TEK
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS
, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE
, INTERNALVATNUMBER, VATNUMBER, CLIENT_LINK_ID, IHCLIENTNUMBER, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, IHCCLIENTTYPE, PAYMENTTERMSDUEDATE, BILL_LEGAL_NAME, SALESREPNAME, WO_REFNR)
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, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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 NUMBER) 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 c.legalname FROM customer c WHERE c.customer_id=a.billtocustomer_link_id) BILL_LEGAL_NAME --todo6927
,      ( select emp.name
         from   employee emp
         where  not emp.dateactive is null
            and emp.dateactive <= a.invoicedate
            and ( emp.dateinactive is null or
                  emp.dateinactive > a.invoicedate)
            and emp.employee_id in (select max(cpc.salesemployee_id)
                                     from   contractspercustomer cpc
                                     where  cpc.customer_id = a.billtocustomer_link_id
                                             and not cpc.dateactive is null      -- to avoid null from subselect
                                             and cpc.dateactive =  (select max(dateactive)
                                                                    from contractspercustomer cpc2
                                                                    where cpc2.customer_id = a.billtocustomer_link_id
                                                                    and not cpc2.salesemployee_id is null
                                                                    and not cpc2.dateactive is null
                                                                    and cpc2.dateactive <= a.invoicedate
                                                                    and ( cpc2.dateinactive is null or
                                                                            cpc2.dateinactive > a.invoicedate))
                                   )
       ) SalesRepName
, (select max(wo.referencenumber) from workorder wo where wo.invoiceheader_id = a.invoiceheader_id) WO_RefNr
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),--501528
      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)
where a.currency_id = b.currency_id--      and a.documenttype = 1
      and a.documenttype in (1, 3) --501528
      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

/
create or replace view V_INVOICECLIENT_TIL
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, ACTIVITYREFERENCE, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE
, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY
, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC
, INVOICELAYOUTCODE, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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
, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE
, INVOICEREMARKENDDATE, INTERNALVATNUMBER, VATNUMBER, CLIENT_LINK_ID, IHCLIENTNUMBER, IHCLIENTNAME, SENDINVOICETO, IHCROOMNUMBER, IHCCLIENTTYPE, CLIENTINVOICETYPE, PAYMENTTERMSDUEDATE, BILL_LEGAL_NAME, PRINTTAXONAPPENDIX, CUSTBILLTOCOMMENT, CUSTDELTOCOMMENT, KID, PONUMBER, OURCONTACT, OURMANAGER)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       a.invoicenumber,a.activityreference, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, a.billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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 NUMBER) 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
			 , ihc.clientinvoicetype--502813
       , ihextr.paymenttermsduedate
       , (SELECT c.legalname FROM customer c WHERE c.customer_id=a.billtocustomer_link_id) BILL_LEGAL_NAME --todo6927
       , (select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix
       , (select MAX(cbc.description) from customerbillingcomment cbc where cbc.customer_id = a.billtocustomer_link_id) custbilltocomment
       , (select MAX(cbc.description) from customerbillingcomment cbc where cbc.customer_id = a.deltocustomer_link_id) custdeltocomment
      , F_GetKIDFrom2Z( a.billtocustomernumber,a.invoicenumber) KID
      ,(select max(cpc.purchaseorder) from contractspercustomer cpc
      where cpc.customer_id = a.billtocustomer_link_id
      and  a.startdate >=  cpc.dateactive and a.enddate <= cpc.dateinactive) PONumber
      , ( select max(cp.name) from employee cp where cp.employee_id in  (select max(cpc.salesemployee_id) from contractspercustomer cpc
      where cpc.customer_id = a.billtocustomer_link_id
      and  a.startdate >=  cpc.dateactive and a.enddate <= cpc.dateinactive) )OurContact
      , ( select max(cp.name) from employee cp where cp.employee_id in  (select max(cpc.ACCOUNTMANAGER_ID) from contractspercustomer cpc
      where cpc.customer_id = a.billtocustomer_link_id
      and  a.startdate >=  cpc.dateactive and a.enddate <= cpc.dateinactive) )OurManager
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),--501528
      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)
where a.currency_id = b.currency_id--      and a.documenttype = 1
      and a.documenttype in (1, 3) --501528
      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

/
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_INVOICECOVERPAGE_SMG
 (INVOICEHEADER_ID, INVOICEDATE, INVOICENUMBER, BILLTOCUSTOMERNUMBER, BILLTOCOUNTRYCODE, DELTOCUSTOMERNUMBER, CUSTOMER_LINK_ID, CUSTOMER_ID, CUSTOMERNUMBER, USECOVERPAGE, NAME, EXTRANAME1, EXTRANAME2, CONTACTPERSON, STREET, STREET2, STATE, ZIPCODE, CITY, COUNTY, COUNTRYCODE, COUNTRY, BILLTOSENDINVOICETO, CUSTTYPE)
as select h.invoiceheader_id,
       h.invoicedate,
       h.invoicenumber,
       h.billtocustomernumber,
       (select co.code from country co, customer c
               where h.billtocustomer_link_id=c.customer_id and c.country_id=co.country_id) billtocountrycode,
       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,
       (select c.sendinvoiceto from customer c where h.deltocustomer_link_id = c.customer_id) billtosendinvoiceto
       ,F_GetCustType_smg(h.invoiceheader_id) custtype
  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_INVOICEDGARMENTLABELS
 (STATUS, PROCESSED, LABELTYPE, INVOICEHEADER_ID, CREATIONDATE, YEAR, WEEK, LABELCODE, LABELDESC, LABELLAYOUTTYPE, WEARERNUMBER, WEARERNAME, WEARERSEARCHNAME, DEPARTMENTNUMBER, DEPARTMENTDESC, 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.departmentnumber, dep.description departmentdesc,
       (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_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_INVOICEDISTRIBUTION_CBD
 (QTY, INVOICEHEADER_ID, STATUSQUODATE, EMPLOYERPERCENTAGE, INVOICENUMBER, INVOICEDATE, INVOICECOMMENTS, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, DELTOSTREET, DELTOZIPCODE, DELTOCITY, 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,
       IH.DelToStreet,
       IH.DelToZipCode,
       IH.DelToCity,
       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.deltocustomer_link_id),
           100) EmployerPercentage,
       IH.InvoiceNumber,
       IH.InvoiceDate,
       IH.InvoiceComments,
       IH.DelToCustomerNumber,
       IH.DelToCustomerName,
       IH.DelToStreet,
       IH.DelToZipCode,
       IH.DelToCity,
       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
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS
, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE
, INTERNALVATNUMBER, VATNUMBER, SETSPECIAL, CLUSTERCODE, DELTOCUSTLANG, PAYMENTTERMSDUEDATE, REFERENCE, ACTIVITYREFERENCE, PRINTTAXONAPPENDIX, WOREFNR)
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, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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,
       coalesce((select max(pa.packingnote_id) from packingnote pa, packingnoteline pl where pa.packingnote_id=pl.packingnote_id and pl.invoiceheader_id = a.invoiceheader_id and a.invoicefrequency_id = 0 and pa.origin = 5), 0) setspecial,       --0 is not based on special order, >0 is based on special order
(case when A.CLUSTER_ID is null then (select max(C.CODE)
	                                                 from CUSTOMERSPERCLUSTER CPC, CUSTOMERCLUSTER C
	                                                 where C.INVOICEFREQUENCY_ID = A.INVOICEFREQUENCY_ID
	                                                       and CPC.CLUSTER_ID = C.CLUSTER_ID and CPC.CUSTOMER_ID = a.billtocustomer_link_id)
	                                           else (select cc.code from customercluster cc where cc.cluster_id = a.cluster_id) end) clustercode,
(select languages.code from languages, customer c where a.deltocustomer_link_id = c.customer_id and languages.language_id = C.LANGUAGE_ID) deltocustlang
, ihextr.paymenttermsduedate, a.reference, a.activityreference,
(select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix
,(select max(wo.referencenumber)from workorder wo where wo.invoiceheader_id=a.invoiceheader_id group by wo.referencenumber) WORefNr
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),
      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)
where a.currency_id = b.currency_id
      and a.documenttype in (1, 8)
      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

/
create or replace view V_INVOICEHEADERCURRENCY_SMG
 (INVOICEHEADER_ID, PLANTCURRENCY_CODE, PLANTCURRENCY_DESC, EXCHANGERATE, EXCHANGERATEDATE, CREDITSQUEEZEAMOUNT, ROUNDINGAMOUNT, PREBILLAMOUNT, TOTALAMOUNTEXCLVAT, PAYTHISAMOUNT, PAIDAMOUNT, UNDERUSEAMOUNT, CUSTCURRENCY_CODE, INVCURRENCY_CODE, DECIMALS, INVOICEAMOUNTDECIMALS)
as select ihc.invoiceheader_id, cur.code Plantcurrency_code, cur.description Plantcurrency_desc,
       ihc.exchangerate, ihc.exchangeratedate, ihc.creditsqueezeamount, ihc.roundingamount,
       ihc.prebillamount, ihc.totalamountexclvat, ihc.paythisamount, ihc.paidamount, ihc.underuseamount
, (select cur0.code from invoiceheadercurrency ihc0, currency cur0 where cur0.currency_id = ihc0.currency_id
                   and ihc0.invoiceheader_id = ihc.invoiceheader_id and ihc0.invoicecurrencytype = 0) CustCurrency_code
, (select cur1.code from invoiceheadercurrency ihc1, currency cur1 where cur1.currency_id = ihc1.currency_id
                   and ihc1.invoiceheader_id = ihc.invoiceheader_id and ihc1.invoicecurrencytype = 1) InvCurrency_code
, cur.decimals, cur.invoiceamountdecimals
from invoiceheadercurrency ihc, currency cur
where cur.currency_id = ihc.currency_id and ihc.invoicecurrencytype = 2 -- Plant Currency
      and (ihc.currency_id not in (select ihc2.currency_id from invoiceheadercurrency ihc2
                          where ihc2.invoiceheader_id = ihc.invoiceheader_id and ihc2.invoicecurrencytype = 0)
          or
          ihc.currency_id not in (select ihc2.currency_id from invoiceheadercurrency ihc2
                          where ihc2.invoiceheader_id = ihc.invoiceheader_id and ihc2.invoicecurrencytype = 1))

/
create or replace view V_INVOICEHEADERSTATEMENT_AUJ
 (LINETYPE, INVOICEDATE, INVOICENUMBER, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, DELTOCUSTOMERNUMBER, INVOICEHEADER_ID, DELTOCUSTOMERNAME, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, TOTALAMOUNTEXCLVAT, COMMONCUSTOMER_NR, COMMONCUSTOMER_NAME, COMMONCUSTOMER_PNNUMBER)
as select 1 linetype, a.invoicedate,
       a.invoicenumber,
       a.billtocustomernumber, a.billtocustomername,
       a.deltocustomernumber, a.invoiceheader_id, a.deltocustomername,
       a.paythisamount, a.prebillamount, a.invoicefrequency_id invoicefrequencynumber,
       b.code currencycode, b.description currencydesc,
       a.totalamountexclvat,
       com1.customernumber commoncustomer_nr,
       com1.name commoncustomer_name,
       com1.pnnumber commoncustomer_pnnumber
from  invoiceheader a
        LEFT OUTER JOIN customer del
             LEFT OUTER JOIN customer com1 ON (com1.customer_id = coalesce(del.commoncustomer_id, del.debtor_id))
        ON (del.customer_id = a.deltocustomer_link_id),
      currency b
where a.currency_id = b.currency_id
      and a.documenttype = 1

/
create or replace view V_INVOICEHEADER_ARW
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS
, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE
, INTERNALVATNUMBER, VATNUMBER, SETSPECIAL, DUEDATE)
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, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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,
       coalesce((select max(pa.packingnote_id) from packingnote pa, packingnoteline pl where pa.packingnote_id=pl.packingnote_id and pl.invoiceheader_id = a.invoiceheader_id and a.invoicefrequency_id = 0 and pa.origin = 5), 0) setspecial
       --0 is not based on special order, >0 is based on special order
       , ihextr.paymenttermsduedate DueDate
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),
      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)
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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

/
create or replace view V_INVOICEHEADER_BDE
 (INVOICEDATE, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, HOUSENUMBER, HOUSENUMBEREXT, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER
, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE, DEFAULT_BU_CODE, SPLITUPCODE, SPLITUPDESCRIPTION, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER
, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, CONSOLIDATED_INVOICE_LAYOUT, DIVISION_CODE, INVOICENUMBERPREFIX, PAYBY_NO, PAYBY_NAME, DUEDATE, PROCBU_CODE, PROCBU_DESC, PLANT_PHONE, PLANT_FAX, CONTACTPERSON_NAME, SEQ, DELTOSTREET, DELTOZIPCODE, DELTOCITY, DELTOHOUSENUMBER, DELTOHOUSENUMBEREXT, DELTOEXTRANAME, DELTOCONTACTPERSONNAME, WEEKSDIFFERENCE, IS_IN_ADVANCE, IS_BDE_ADVANCE)
as SELECT A.INVOICEDATE, A.INVOICENUMBER, A.DOCUMENTTYPE, E.CODE INVOICEBUSINESSUNITCODE, E.DESCRIPTION INVOICEBUSINESSUNITDESC,
       A.BILLTOCUSTOMERNUMBER, A.BILLTOCUSTOMERNAME, A.EXTRANAME1, A.EXTRANAME2,
       A.DELTOCUSTOMERNUMBER, A.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.HOUSENUMBER,A.HOUSENUMBEREXT,
       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, A.INVOICEHEADER_ID,
       A.CREDITSQUEEZEAMOUNT, B.INVOICEAMOUNTDECIMALS, B.DESCRIPTION CURRENCYDESCRIPTION, A.TOTALAMOUNTEXCLVAT,
       B.DECIMALS, A.STARTDATE, A.ENDDATE,
       IHEXTR.BILLTOCOUNTRYDESCRIPTION, IHEXTR.DELTOCOUNTRYDESCRIPTION,
       IHEXTR.DELTOCUSTVATNUMBER,
       IHEXTR.CUSTOMERMARKINGGARMENT, IHEXTR.TAXABLE, IHEXTR.SICCODE, IHEXTR.INVOICECOPIES
       , IHEXTR.ATTACHINVOICECOPIES, IHEXTR.PAYMENTTERMSDESCRIPTION PAYMENTTERMS_DESC,
       IHEXTR.FORMLAYOUTCODE INVOICELAYOUTCODE,
       E.CODE DEFAULT_BU_CODE,
       A.SPLITUPCODE, A.SPLITUPDESCRIPTION
, CAST(FSGET_MIN_6_YEARWEEKS(A.INVOICEHEADER_ID, A.INVOICEFREQUENCY_ID) AS VARCHAR2(47)) MIN_YEAR_WEEKS
       , A.PARENTINVOICEHEADER_ID,
       (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,
       A.NEXTPERIODSTARTWEEK, A.NEXTPERIODENDWEEK,
       IHEXTR.PAYMENTTYPE, IHEXTR.DISCOUNTDAYS, IHEXTR.PAYMENTDISCOUNT, IHEXTR.DISCOUNTDAYS2, IHEXTR.PAYMENTDISCOUNT2
       , (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
, (SELECT FL.CODE FROM FORMLAYOUT FL, CUSTOMERBILLINGINFO CBI, INVOICEHEADER IE
   WHERE CBI.CUSTOMER_ID = IE.BILLTOCUSTOMER_LINK_ID AND
         IE.INVOICEHEADER_ID = A.PARENTINVOICEHEADER_ID AND
         CBI.CONSOLIDATEDINVOICELAYOUT_ID = FL.FORMLAYOUT_ID) CONSOLIDATED_INVOICE_LAYOUT
, (SELECT D.DESCRIPTION FROM DIVISION_DESC D WHERE PROCBU.DIVISION_ID = D.DIVISION_ID AND D.LANGUAGE_ID=PL.LANGUAGE_ID) DIVISION_CODE
, E.INVOICENUMBERPREFIX
, PBCUST.CUSTOMERNUMBER PAYBY_NO , PBCUST.NAME PAYBY_NAME
, IHEXTR.PAYMENTTERMSDUEDATE DUEDATE
, PROCBU.CODE PROCBU_CODE, PROCBU.DESCRIPTION PROCBU_DESC
, PL.PHONENO PLANT_PHONE, PL.FAXNO PLANT_FAX
--, (SELECT MAX(EMP.NAME) FROM EMPLOYEE EMP WHERE EXISTS (SELECT * FROM CUSTOMER CUST WHERE CUST.DEFAULTBUSINESSUNIT_ID = PROCBU.BUSINESSUNIT_ID AND CUST.SERVICEEMPLOYEE_ID = EMP.EMPLOYEE_ID)) CONTACTPERSON_NAME
, (SELECT MAX(EMP.NAME) FROM EMPLOYEE EMP WHERE DELTO.SERVICEEMPLOYEE_ID = EMP.EMPLOYEE_ID) CONTACTPERSON_NAME
, CAST(GETSUBSTRING(A.INVOICENUMBER, -3) AS VARCHAR2(3)) SEQ
, DX.STREET DELTOSTREET, DX.ZIPCODE DELTOZIPCODE, DX.CITY DELTOCITY, DX.HOUSENUMBER DELTOHOUSENUMBER, DX.HOUSENUMBEREXT DELTOHOUSENUMBEREXT
, DELTO.EXTRANAME2 DELTOEXTRANAME
, (SELECT CP.NAME FROM CONTACTPERSON CP WHERE CP.CUSTOMER_ID = DELTO.CUSTOMER_ID AND CP.INVOICECONTACTPERSON = 'Y') DELTOCONTACTPERSONNAME
, GETWEEKSDIFFERENCE_BDE(YEAR(A.NEXTPERIODSTARTDATE), A.NEXTPERIODSTARTWEEK, YEAR(A.NEXTPERIODENDDATE), A.NEXTPERIODENDWEEK) WEEKSDIFFERENCE
, (CASE WHEN A.NEXTPERIODSTARTDATE IS NOT NULL THEN 1
   ELSE 0 END) IS_IN_ADVANCE
, (SELECT count(IL.INVOICELINE_ID) FROM INVOICELINE IL
   WHERE IL.INVOICEHEADER_ID=A.INVOICEHEADER_ID AND IL.INVOICELINESUBTYPE=8) IS_BDE_ADVANCE
FROM  CURRENCY B,STATUS S,
      BUSINESSUNIT E,
      PLANT P,
      ADDRESS X,
      INVOICEHEADER A
        LEFT OUTER JOIN CUSTOMER DELTO
             LEFT OUTER JOIN BUSINESSUNIT PROCBU
                  LEFT OUTER JOIN PLANT PL ON (PROCBU.PLANT_ID = PL.PLANT_ID)
             ON (DELTO.DEFAULTBUSINESSUNIT_ID = PROCBU.BUSINESSUNIT_ID)
             LEFT OUTER JOIN ADDRESS DX ON (DELTO.VISITADDRESS_ID = DX.ADDRESS_ID)
        ON (A.DELTOCUSTOMER_LINK_ID = DELTO.CUSTOMER_ID),
      INVOICEHEADEREXTRAINFO IHEXTR
        LEFT OUTER JOIN CUSTOMER_LINK PBCUST ON (IHEXTR.PAYBYCUSTOMER_LINK_ID = PBCUST.CUSTOMER_LINK_ID)
WHERE A.CURRENCY_ID = B.CURRENCY_ID
      AND A.DOCUMENTTYPE = 1
      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 A.INVOICEHEADER_ID = IHEXTR.INVOICEHEADER_ID

/
create or replace view V_INVOICEHEADER_BNL
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, HOUSENUMBER, HOUSENUMBEREXT, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS
, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL
, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, M_SORT_US_ASC, M_SORT_US_DESC, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC
, INVOICELAYOUTCODE, DEFAULT_BU_CODE, ADJUSTMENT_REASONCODE, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS
, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, COLLECTIONRESPEMPLOYEE
, CONSOLIDATED_INVOICE_LAYOUT, DELTO_CONTACTPERSONNAME, CUSTOMER_LANGUAGECODE, GARMENTINSURANCE, INSURANCEPRICETYPE)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       a.invoicenumber, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, cast(a.billtocustomername as varchar2(63)) billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, cast(a.deltocustomername as varchar2(63)) 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.housenumber,a.housenumberext,
       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,
       ihextr.billtocountrydescription, ihextr.deltocountrydescription,
       ihextr.deltocustvatnumber,
       ihextr.customermarkinggarment, ihextr.taxable, ihextr.siccode, ihextr.invoicecopies
, 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
--, 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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
--       (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,
       rc.code Adjustment_ReasonCode
       , 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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,
       a.nextperiodstartweek, a.nextperiodendweek,
       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
       , (select empl.name from customerbillinginfo cbi, employee empl
          where cbi.customer_id = a.billtocustomer_link_id
                and empl.employee_id = cbi.collectionresponsible_id) collectionRespEmployee
, (CASE WHEN A.PARENTINVOICEHEADER_ID IS NOT NULL AND A.INVOICEHEADER_ID <> A.PARENTINVOICEHEADER_ID THEN
(SELECT IEXCONS.FORMLAYOUTCODE FROM INVOICEHEADEREXTRAINFO IEXCONS WHERE IEXCONS.INVOICEHEADER_ID = A.PARENTINVOICEHEADER_ID)
WHEN A.PARENTINVOICEHEADER_ID = A.INVOICEHEADER_ID THEN IHEXTR.FORMLAYOUTCODE --THIS SHOULD NOT HAPPEN
ELSE NULL
--(select fl.code from formlayout fl, customerbillinginfo cbi, invoiceheader ie
--   where cbi.customer_id = ie.billtocustomer_link_id and
--         ie.invoiceheader_id = a.parentinvoiceheader_id and
--         cbi.consolidatedinvoicelayout_id = fl.formlayout_id)
END )
consolidated_invoice_layout
, (select MIN(cp.name) from contactperson cp
   where cp.customer_id = a.deltocustomer_link_id
         and cp.contactpersonnumber = (select min(cpp.contactpersonnumber)
                                    from contactperson cpp where cpp.customer_id = a.deltocustomer_link_id)) delto_contactpersonname,
   lg.code customer_languagecode
, cu.garmentinsurance, cu.insurancepricetype
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),
      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),
      customer cu, languages lg
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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 a.deltocustomer_link_id = cu.customer_id
      and cu.language_id = lg.language_id

/
create or replace view V_INVOICEHEADER_BNL_EXTREF
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, HOUSENUMBER, HOUSENUMBEREXT, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS
, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL
, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, M_SORT_US_ASC, M_SORT_US_DESC, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC
, INVOICELAYOUTCODE, DEFAULT_BU_CODE, ADJUSTMENT_REASONCODE, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS
, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, COLLECTIONRESPEMPLOYEE
, CONSOLIDATED_INVOICE_LAYOUT, DELTO_CONTACTPERSONNAME, CUSTOMER_LANGUAGECODE, GARMENTINSURANCE, INSURANCEPRICETYPE, REFERENCENUMBER)
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, a.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.housenumber,a.housenumberext,
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,
ihextr.billtocountrydescription, ihextr.deltocountrydescription,
ihextr.deltocustvatnumber,
ihextr.customermarkinggarment, ihextr.taxable, ihextr.siccode, ihextr.invoicecopies
, 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
--, 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,
ihextr.formlayoutcode invoicelayoutcode,
e.code default_BU_code,
-- (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,
rc.code Adjustment_ReasonCode
, 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,
a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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,
a.nextperiodstartweek, a.nextperiodendweek,
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
, (select empl.name from customerbillinginfo cbi, employee empl
where cbi.customer_id = a.billtocustomer_link_id
and empl.employee_id = cbi.collectionresponsible_id) collectionRespEmployee
, (CASE WHEN A.PARENTINVOICEHEADER_ID IS NOT NULL AND A.INVOICEHEADER_ID <> A.PARENTINVOICEHEADER_ID THEN
(SELECT IEXCONS.FORMLAYOUTCODE FROM INVOICEHEADEREXTRAINFO IEXCONS WHERE IEXCONS.INVOICEHEADER_ID = A.PARENTINVOICEHEADER_ID)
WHEN A.PARENTINVOICEHEADER_ID = A.INVOICEHEADER_ID THEN IHEXTR.FORMLAYOUTCODE --THIS SHOULD NOT HAPPEN
ELSE NULL
--(select fl.code from formlayout fl, customerbillinginfo cbi, invoiceheader ie
-- where cbi.customer_id = ie.billtocustomer_link_id and
-- ie.invoiceheader_id = a.parentinvoiceheader_id and
-- cbi.consolidatedinvoicelayout_id = fl.formlayout_id)
END )
consolidated_invoice_layout
, (select MIN(cp.name) from contactperson cp
where cp.customer_id = a.deltocustomer_link_id
and cp.contactpersonnumber = (select min(cpp.contactpersonnumber)
from contactperson cpp where cpp.customer_id = a.deltocustomer_link_id)) delto_contactpersonname,
lg.code customer_languagecode
, cu.garmentinsurance, cu.insurancepricetype,
(select unique wo.referencenumber referencenumber from workorder wo where wo.invoiceheader_id=a.INVOICEHEADER_ID and rownum=1) referencenumber
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),
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),
customer cu, languages lg
where a.currency_id = b.currency_id
and a.documenttype = 1
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 a.deltocustomer_link_id = cu.customer_id
and cu.language_id = lg.language_id

/
create or replace view V_INVOICEHEADER_CONS_1_BDE
 (INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, HOUSENUMBER, HOUSENUMBEREXT, CONTACTPERSONNAME, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, CHILD_PREBILL, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION
, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, PAYMENTTERMS_DESC, INVOICELAYOUTCODE, DEFAULT_BU_CODE, SPLITUPCODE, SPLITUPDESCRIPTION, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, DIVISION_CODE, INVOICENUMBERPREFIX
, PAYBY_NO, PAYBY_NAME, DUEDATE, PROCBU_CODE, PROCBU_DESC, PLANT_PHONE, PLANT_FAX, CONTACTPERSON_NAME, SEQ, PREBILLAMOUNT, TOTALAMOUNTEXCLVAT, PARENT_NR, PARENT_TYPE, PARENT_DATE, MAX_PERCENTAGE, IS_IN_ADVANCE, IS_BDE_ADVANCE, WEEKSDIFFERENCE)
as SELECT E.CODE INVOICEBUSINESSUNITCODE, E.DESCRIPTION INVOICEBUSINESSUNITDESC,
       A.BILLTOCUSTOMERNUMBER, A.BILLTOCUSTOMERNAME, A.EXTRANAME1, A.EXTRANAME2,
       A.DELTOCUSTOMERNUMBER, A.DELTOCUSTOMERNAME,
       PI.CITY, PI.COUNTY, PI.STATE, PI.ZIPCODE,PI.STREET2, PI.STREET, PI.HOUSENUMBER,PI.HOUSENUMBEREXT,--A.CITY, A.COUNTY, A.STATE, A.ZIPCODE,A.STREET2, A.STREET, A.HOUSENUMBER,A.HOUSENUMBEREXT,
       A.CONTACTPERSONNAME, A.INVOICECOMMENTS, A.TOTALMINUSADJUSTMENT, A.TOTALPLUSADJUSTMENT, A.CASHCOLLECTED,
       A.PAYTHISAMOUNT, A.PREBILLAMOUNT CHILD_PREBILL,
       A.INVOICEFREQUENCY_ID INVOICEFREQUENCYNUMBER, B.CODE CURRENCYCODE, B.DESCRIPTION CURRENCYDESC,
       A.INVOICEHEADER_ID,
       A.CREDITSQUEEZEAMOUNT, B.INVOICEAMOUNTDECIMALS, B.DESCRIPTION CURRENCYDESCRIPTION,
       B.DECIMALS, A.STARTDATE, A.ENDDATE,
       IHEXTR.BILLTOCOUNTRYDESCRIPTION, IHEXTR.DELTOCOUNTRYDESCRIPTION,
       IHEXTR.PAYMENTTERMSDESCRIPTION PAYMENTTERMS_DESC,
       IHEXTR.FORMLAYOUTCODE INVOICELAYOUTCODE,
       E.CODE DEFAULT_BU_CODE
       , A.SPLITUPCODE, A.SPLITUPDESCRIPTION
, CAST(FSGET_MIN_6_YEARWEEKS_CONS(PI.INVOICEHEADER_ID, PI.INVOICEFREQUENCY_ID) AS VARCHAR2(47)) MIN_YEAR_WEEKS
       , A.PARENTINVOICEHEADER_ID, A.CONTRACTSTARTDATE, A.CONTRACTENDDATE,
       A.ROUNDINGAMOUNT, A.NEXTPERIODSTARTDATE, A.NEXTPERIODENDDATE, A.NEXTPERIODNOWEEKS,
       A.NEXTPERIODSTARTWEEK, A.NEXTPERIODENDWEEK
       , (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
, (SELECT D.DESCRIPTION FROM DIVISION_DESC D WHERE PROCBU.DIVISION_ID = D.DIVISION_ID AND D.LANGUAGE_ID = PL.LANGUAGE_ID) DIVISION_CODE
, E.INVOICENUMBERPREFIX
, PBCUST.CUSTOMERNUMBER PAYBY_NO , PBCUST.NAME PAYBY_NAME
, IHEXTR.PAYMENTTERMSDUEDATE DUEDATE
, PROCBU.CODE PROCBU_CODE, PROCBU.DESCRIPTION PROCBU_DESC
, PL.PHONENO PLANT_PHONE, PL.FAXNO PLANT_FAX--, (SELECT MAX(EMP.NAME) FROM EMPLOYEE EMP WHERE EXISTS (SELECT * FROM CUSTOMER CUST WHERE CUST.DEFAULTBUSINESSUNIT_ID = PROCBU.BUSINESSUNIT_ID AND CUST.SERVICEEMPLOYEE_ID = EMP.EMPLOYEE_ID)) CONTACTPERSON_NAME
, (SELECT MAX(EMP.NAME) FROM EMPLOYEE EMP WHERE DELTO.SERVICEEMPLOYEE_ID = EMP.EMPLOYEE_ID) CONTACTPERSON_NAME
, CAST(GETSUBSTRING(A.INVOICENUMBER, -3) AS VARCHAR2(3)) SEQ
, PI.PREBILLAMOUNT, PI.TOTALAMOUNTEXCLVAT, PI.INVOICENUMBER PARENT_NR, PI.INVOICETYPE PARENT_TYPE, PI.INVOICEDATE PARENT_DATE,
       (SELECT MAX(ILV.PERCENTAGE) FROM INVOICELINE IL, INVOICELINEVARIOUS ILV
               WHERE IL.INVOICEHEADER_ID = PI.INVOICEHEADER_ID AND
                     ILV.INVOICELINE_ID = IL.INVOICELINE_ID AND
                     IL.INVOICELINETYPE_ID = 18) MAX_PERCENTAGE
, (SELECT COUNT(CIH.INVOICEHEADER_ID) FROM INVOICEHEADER CIH
   WHERE CIH.PARENTINVOICEHEADER_ID = PI.INVOICEHEADER_ID AND CIH.PARENTINVOICEHEADER_ID <> CIH.INVOICEHEADER_ID
   AND CIH.NEXTPERIODSTARTDATE IS NOT NULL ) IS_IN_ADVANCE
, (SELECT count(IL.INVOICELINE_ID) FROM INVOICEHEADER CIH, INVOICELINE IL
   WHERE CIH.PARENTINVOICEHEADER_ID = PI.INVOICEHEADER_ID AND CIH.PARENTINVOICEHEADER_ID <> CIH.INVOICEHEADER_ID
   AND IL.INVOICEHEADER_ID=CIH.INVOICEHEADER_ID AND IL.INVOICELINESUBTYPE=8) IS_BDE_ADVANCE
, GETWEEKSDIFFERENCE_BDE(YEAR(A.NEXTPERIODSTARTDATE), A.NEXTPERIODSTARTWEEK, YEAR(A.NEXTPERIODENDDATE), A.NEXTPERIODENDWEEK) WEEKSDIFFERENCE
FROM  CURRENCY B, STATUS S,
      BUSINESSUNIT E,
      PLANT P,
      ADDRESS X, COUNTRY,
      INVOICEHEADER A
        LEFT OUTER JOIN CUSTOMER DELTO
             LEFT OUTER JOIN BUSINESSUNIT PROCBU
                  LEFT OUTER JOIN PLANT PL ON (PROCBU.PLANT_ID = PL.PLANT_ID)
             ON (DELTO.DEFAULTBUSINESSUNIT_ID = PROCBU.BUSINESSUNIT_ID)
        ON (A.DELTOCUSTOMER_LINK_ID = DELTO.CUSTOMER_ID),
      INVOICEHEADEREXTRAINFO IHEXTR
        LEFT OUTER JOIN CUSTOMER_LINK PBCUST ON (IHEXTR.PAYBYCUSTOMER_LINK_ID = PBCUST.CUSTOMER_LINK_ID),
     INVOICEHEADER PI
WHERE A.CURRENCY_ID = B.CURRENCY_ID
      AND A.DOCUMENTTYPE = 1
      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 PI.INVOICEHEADER_ID = IHEXTR.INVOICEHEADER_ID
      AND A.PARENTINVOICEHEADER_ID = PI.INVOICEHEADER_ID
      AND A.PARENTINVOICEHEADER_ID <> A.INVOICEHEADER_ID

/
create or replace view V_INVOICEHEADER_CONS_1_BNL
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, HOUSENUMBER, HOUSENUMBEREXT, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS
, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL
, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, ADJUSTMENT_REASONCODE, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET
, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, COLLECTIONRESPEMPLOYEE
, DELTO_CONTACTPERSONNAME, CUSTOMER_LANGUAGECODE)
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, a.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.housenumber,a.housenumberext,
       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,
       ihextr.billtocountrydescription, ihextr.deltocountrydescription,
       ihextr.deltocustvatnumber,
       ihextr.customermarkinggarment, ihextr.taxable, ihextr.siccode, ihextr.invoicecopies
       , ihextr.attachinvoicecopies, ihextr.paymenttermsdescription paymentterms_desc,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       rc.code Adjustment_ReasonCode
       , a.splitupcode, a.splitupdescription,
       ihs.personidentification, ihs.signature
       , 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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,
       a.nextperiodstartweek, a.nextperiodendweek,
       ihextr.paymenttype, ihextr.discountdays, ihextr.paymentdiscount, ihextr.discountdays2, ihextr.paymentdiscount2
       , cast(SS1.VALUE as numeric) WEIGHTDECIMALSMANUALINPUT
       , (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
       , (select empl.name from customerbillinginfo cbi, employee empl
          where cbi.customer_id = a.billtocustomer_link_id
                and empl.employee_id = cbi.collectionresponsible_id) collectionRespEmployee
, (select MIN(cp.name) from contactperson cp
   where cp.customer_id = a.deltocustomer_link_id
         and cp.contactpersonnumber = (select min(cpp.contactpersonnumber)
                                    from contactperson cpp where cpp.customer_id = a.deltocustomer_link_id)) delto_contactpersonname,
  lg.code customer_languagecode
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),
      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),
      customer cu, languages lg
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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 a.deltocustomer_link_id = cu.customer_id
      and cu.language_id = lg.language_id

/
create or replace view V_INVOICEHEADER_CONS_2_BDE
 (INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, HOUSENUMBER, HOUSENUMBEREXT, CONTACTPERSONNAME, AMOUNT, SPLITUPCODE, SPLITUPDESCRIPTION, INVOICEFREQUENCYNUMBER, CURRENCYCODE, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, PARENTINVOICEHEADER_ID, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, DIVISION_CODE, INVOICENUMBERPREFIX, PAYBY_NO, PAYBY_NAME, DUEDATE, PROCBU_CODE, PROCBU_DESC, PLANT_PHONE, PLANT_FAX, CONTACTPERSON_NAME, SEQ, PREBILLAMOUNT, TOTALAMOUNTEXCLVAT, PARENT_NR, PARENT_TYPE, PARENT_DATE, MAX_PERCENTAGE, IS_IN_ADVANCE)
as select e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       pi.billtocustomernumber, pi.billtocustomername, pi.extraname2,
       a.deltocustomernumber, a.deltocustomername,
       a.city, a.county, a.state, a.zipcode,a.street2, a.street, a.housenumber,a.housenumberext,
       pi.contactpersonname, a.totalamountexclvat amount, a.splitupcode, a.splitupdescription,
       a.invoicefrequency_id invoicefrequencynumber, b.code currencycode, a.invoiceheader_id,
       a.creditsqueezeamount, b.invoiceamountdecimals, b.description currencydescription,
       b.decimals, pi.startdate, pi.enddate,
       ihextr.billtocountrydescription,
       (select ihe.paymenttermsdescription from invoiceheaderextrainfo ihe where ihe.invoiceheader_id=pi.invoiceheader_id) paymentterms_desc,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code, a.parentinvoiceheader_id,
       pi.roundingamount, pi.NEXTPERIODSTARTDATE, pi.NEXTPERIODENDDATE, pi.NEXTPERIODNOWEEKS,
       pi.nextperiodstartweek, pi.nextperiodendweek,
       (select d.description from division_desc d where procbu.division_id = d.division_id and d.language_id = pl.language_id) Division_code
, e.invoicenumberprefix
, PBCust.Customernumber PayBy_No , PBCust.Name PayBy_Name
, (select ihe.paymenttermsduedate from invoiceheaderextrainfo ihe where ihe.invoiceheader_id=pi.invoiceheader_id) DueDate
, procbu.code procbu_code, procbu.description procbu_desc
, pl.phoneno plant_phone, pl.faxno plant_fax
--, (select max(emp.name) from employee emp where exists (select * from customer cust where cust.defaultbusinessunit_id = procbu.businessunit_id and cust.serviceemployee_id = emp.employee_id)) ContactPerson_name
, (select max(emp.name) from employee emp where delto.serviceemployee_id = emp.employee_id) ContactPerson_name
, cast(GETSUBSTRING(a.invoicenumber, -3) as varchar2(3)) Seq
, pi.prebillamount, pi.totalamountexclvat, pi.invoicenumber Parent_nr, pi.invoicetype Parent_type, pi.invoicedate Parent_date,
       (select MAX(ilv.percentage) from invoiceline il, invoicelinevarious ilv
               where il.invoiceheader_id = pi.invoiceheader_id and
                     ilv.invoiceline_id = il.invoiceline_id and
                     il.invoicelinetype_id = 18) max_percentage
, ( select count(cih.nextperiodstartdate) from invoiceheader cih
  where cih.parentinvoiceheader_id = pi.invoiceheader_id and cih.parentinvoiceheader_id <> cih.invoiceheader_id
        and cih.nextperiodstartdate is not null ) Is_in_advance
from  currency b, status s, businessunit e,
      invoiceheader a
        LEFT OUTER JOIN customer delto
             LEFT OUTER JOIN businessunit procbu
                  LEFT OUTER JOIN plant pl on (procbu.plant_id = pl.plant_id)
             ON (delto.defaultbusinessunit_id = procbu.businessunit_id)
        ON (a.deltocustomer_link_id = delto.customer_id),
      invoiceheaderextrainfo ihextr
        LEFT OUTER JOIN customer_link PBCust ON (ihextr.paybycustomer_link_id = PBCust.Customer_Link_Id),
     invoiceheader pi
where a.currency_id = b.currency_id
      and a.documenttype = 1
      and a.invoicebusinessunit_id = e.businessunit_id
      and a.status_id = s.status_id
      and a.invoiceheader_id = ihextr.invoiceheader_id
      and a.parentinvoiceheader_id = pi.invoiceheader_id
      and a.parentinvoiceheader_id <> a.invoiceheader_id

/
create or replace view V_INVOICEHEADER_CONS_2_BNL
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, HOUSENUMBER, HOUSENUMBEREXT, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS
, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL
, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, ADJUSTMENT_REASONCODE, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET
, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, COLLECTIONRESPEMPLOYEE
, CONSOLIDATED_INVOICE_LAYOUT, TOTALAMOUNTEXCLVAT_CONS, PREBILLAMOUNT_CONS, MAX_PERCENTAGE_CONS, INVOICENUMBER_CONS, INVOICEDATE_CONS, INVOICEAMOUNTDECIMALS_CONS, DECIMALS_CONS, ISCONSOLIDATEDINVOICE, DELTO_CONTACTPERSONNAME, INVOICECOMMENTS_CONS, CUSTOMER_LANGUAGECODE, GARMENTINSURANCE, INSURANCEPRICETYPE)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       a.invoicenumber, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, cast(a.billtocustomername as varchar2(63)) billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, cast(a.deltocustomername as varchar2(63)) 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.housenumber,a.housenumberext,
       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,
       ihextr.billtocountrydescription, ihextr.deltocountrydescription,
       ihextr.deltocustvatnumber,
       ihextr.customermarkinggarment, ihextr.taxable, ihextr.siccode, ihextr.invoicecopies
       , ihextr.attachinvoicecopies, ihextr.paymenttermsdescription paymentterms_desc,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       rc.code Adjustment_ReasonCode
       , a.splitupcode, a.splitupdescription,
       ihs.personidentification, ihs.signature
       , 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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,
       a.nextperiodstartweek, a.nextperiodendweek,
       ihextr.paymenttype, ihextr.discountdays, ihextr.paymentdiscount, ihextr.discountdays2, ihextr.paymentdiscount2
       , cast(SS1.VALUE as numeric) WEIGHTDECIMALSMANUALINPUT
       , (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
       , (select empl.name from customerbillinginfo cbi, employee empl
          where cbi.customer_id = a.billtocustomer_link_id
                and empl.employee_id = cbi.collectionresponsible_id) collectionRespEmployee
, (select fl.code from formlayout fl, customerbillinginfo cbi, invoiceheader ie
   where cbi.customer_id = ie.billtocustomer_link_id and
         ie.invoiceheader_id = a.parentinvoiceheader_id and
         cbi.consolidatedinvoicelayout_id = fl.formlayout_id) consolidated_invoice_layout
, (select ch.totalamountexclvat from invoiceheader ch
   where ch.parentinvoiceheader_id = a.parentinvoiceheader_id and
         ch.invoiceheader_id = a.parentinvoiceheader_id) totalamountexclvat_Cons
, (select ch.prebillamount from invoiceheader ch
   where ch.parentinvoiceheader_id = a.parentinvoiceheader_id and
         ch.invoiceheader_id = a.parentinvoiceheader_id) prebillamount_Cons
, (select MAX(ilv.percentage) from INVOICEHEADER CH, invoiceline il, invoicelinevarious ilv
   where il.invoiceheader_id = CH.invoiceheader_id and
         ilv.invoiceline_id = il.invoiceline_id and
         CH.PARENTINVOICEHEADER_ID = A.PARENTINVOICEHEADER_ID AND
         CH.INVOICEHEADER_ID = A.PARENTINVOICEHEADER_ID AND
         il.invoicelinetype_id = 18) MAX_PERCENTAGE_CONS
, (select pa.invoicenumber from invoiceheader pa
   where pa.invoiceheader_id = a.parentinvoiceheader_id) invoicenumber_cons
, (select pa.invoicedate from invoiceheader pa
   where pa.invoiceheader_id = a.parentinvoiceheader_id) invoicedate_cons
, (select cy.invoiceamountdecimals from invoiceheader pa, currency cy
   where pa.invoiceheader_id = a.parentinvoiceheader_id
         and cy.currency_id = pa.currency_id) invoiceamountdecimals_cons
, (select cy.decimals from invoiceheader pa, currency cy
   where pa.invoiceheader_id = a.parentinvoiceheader_id
         and cy.currency_id = pa.currency_id) decimals_cons
, (CASE WHEN (a.parentinvoiceheader_id = a.invoiceheader_id) THEN 0
	     ELSE 1 END) isConsolidatedInvoice
, (select MIN(cp.name) from contactperson cp
   where cp.customer_id = a.deltocustomer_link_id
         and cp.contactpersonnumber = (select min(cpp.contactpersonnumber)
                                    from contactperson cpp where cpp.customer_id = a.deltocustomer_link_id)) delto_contactpersonname
, (select pa.invoicecomments from invoiceheader pa
   where pa.invoiceheader_id = a.parentinvoiceheader_id) invoicecomments_cons,
  lg.code customer_languagecode
, cu.garmentinsurance, cu.insurancepricetype
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),
      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),
      customer cu, languages lg
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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 a.deltocustomer_link_id = cu.customer_id
      and cu.language_id = lg.language_id

/
create or replace view V_INVOICEHEADER_CONS_3_BNL
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, HOUSENUMBER, HOUSENUMBEREXT, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS
, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL
, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, ADJUSTMENT_REASONCODE, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET
, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, COLLECTIONRESPEMPLOYEE
, CONSOLIDATED_INVOICE_LAYOUT, TOTALAMOUNTEXCLVAT_CONS, PREBILLAMOUNT_CONS, MAX_PERCENTAGE_CONS, INVOICENUMBER_CONS, INVOICEDATE_CONS, INVOICEAMOUNTDECIMALS_CONS, DECIMALS_CONS, ISCONSOLIDATEDINVOICE, PAYMENTTERMS_DESC_CONS, DELTO_CONTACTPERSONNAME, CUSTOMER_LANGUAGECODE, GARMENTINSURANCE, INSURANCEPRICETYPE)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       a.invoicenumber, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, cast(a.billtocustomername as varchar2(63)) billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, cast(a.deltocustomername as varchar2(63)) 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.housenumber,a.housenumberext,
       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,
       ihextr.billtocountrydescription, ihextr.deltocountrydescription,
       ihextr.deltocustvatnumber,
       ihextr.customermarkinggarment, ihextr.taxable, ihextr.siccode, ihextr.invoicecopies
       , ihextr.attachinvoicecopies, ihextr.paymenttermsdescription paymentterms_desc,     --ihextr.formlayoutcode invoicelayoutcode,
       (SELECT ihe.formlayoutcode FROM invoiceheaderextrainfo ihe WHERE ihe.invoiceheader_id = a.parentinvoiceheader_id) invoicelayoutcode,
       e.code default_BU_code,
       rc.code Adjustment_ReasonCode
       , a.splitupcode, a.splitupdescription,
       ihs.personidentification, ihs.signature
       , 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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,
       a.nextperiodstartweek, a.nextperiodendweek,
       ihextr.paymenttype, ihextr.discountdays, ihextr.paymentdiscount, ihextr.discountdays2, ihextr.paymentdiscount2
       , cast(SS1.VALUE as numeric) WEIGHTDECIMALSMANUALINPUT
       , (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
       , (select empl.name from customerbillinginfo cbi, employee empl
          where cbi.customer_id = a.billtocustomer_link_id
                and empl.employee_id = cbi.collectionresponsible_id) collectionRespEmployee
, (select fl.code from formlayout fl, customerbillinginfo cbi, invoiceheader ie
   where cbi.customer_id = ie.billtocustomer_link_id and
         ie.invoiceheader_id = a.parentinvoiceheader_id and
         cbi.consolidatedinvoicelayout_id = fl.formlayout_id) consolidated_invoice_layout
, (select ch.totalamountexclvat from invoiceheader ch
   where ch.parentinvoiceheader_id = a.parentinvoiceheader_id and
         ch.invoiceheader_id = a.parentinvoiceheader_id) totalamountexclvat_Cons
, (select ch.prebillamount from invoiceheader ch
   where ch.parentinvoiceheader_id = a.parentinvoiceheader_id and
         ch.invoiceheader_id = a.parentinvoiceheader_id) prebillamount_Cons
, (select MAX(ilv.percentage) from INVOICEHEADER CH, invoiceline il, invoicelinevarious ilv
   where il.invoiceheader_id = CH.invoiceheader_id and
         ilv.invoiceline_id = il.invoiceline_id and
         CH.PARENTINVOICEHEADER_ID = A.PARENTINVOICEHEADER_ID AND
         CH.INVOICEHEADER_ID = A.PARENTINVOICEHEADER_ID AND
         il.invoicelinetype_id = 18) MAX_PERCENTAGE_CONS
, (select pa.invoicenumber from invoiceheader pa
   where pa.invoiceheader_id = a.parentinvoiceheader_id) invoicenumber_cons
, (select pa.invoicedate from invoiceheader pa
   where pa.invoiceheader_id = a.parentinvoiceheader_id) invoicedate_cons
, (select cy.invoiceamountdecimals from invoiceheader pa, currency cy
   where pa.invoiceheader_id = a.parentinvoiceheader_id
         and cy.currency_id = pa.currency_id) invoiceamountdecimals_cons
, (select cy.decimals from invoiceheader pa, currency cy
   where pa.invoiceheader_id = a.parentinvoiceheader_id
         and cy.currency_id = pa.currency_id) decimals_cons
, (CASE WHEN (a.parentinvoiceheader_id = a.invoiceheader_id) THEN 0
	     ELSE 1 END) isConsolidatedInvoice
, (select iex.paymenttermsdescription from invoiceheaderextrainfo iex
  where iex.invoiceheader_id = a.parentinvoiceheader_id ) paymentterms_desc_cons
, (select MIN(cp.name) from contactperson cp
   where cp.customer_id = a.deltocustomer_link_id
         and cp.contactpersonnumber = (select min(cpp.contactpersonnumber)
                                    from contactperson cpp where cpp.customer_id = a.deltocustomer_link_id)) delto_contactpersonname,
  lg.code customer_languagecode
, cu.garmentinsurance, cu.insurancepricetype
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),
      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),
      customer cu, languages lg
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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 a.deltocustomer_link_id = cu.customer_id
      and cu.language_id = lg.language_id

/
create or replace view V_INVOICEHEADER_CUS
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, DRIVINGDATE, DEPOTADDRESS, DEPOTPHONENO, DELTOTAXAUTHCODE, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC
, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, INTERNALVATNUMBER
, VATNUMBER, DELTOCUSTLANG, PAYMENTTERMSDUEDATE, REFERENCE, ACTIVITYREFERENCE, PRINTTAXONAPPENDIX)
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, a.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,
       (select rct.drivingdate from routecontrol rct where rct.routecontrol_id = a.routecontrol_id) drivingdate,
       (select adrs.street || ', ' || adrs.city || ', ' || adrs.state || ', ' || adrs.zipcode || ', ' || d.phoneno
        from routecontrol rc, route r, depot d, address adrs
        where a.routecontrol_id = rc.routecontrol_id
              and rc.route_id = r.route_id
              and r.depot_id = d.depot_id
              and d.address_id = adrs.address_id
       ) depotaddress,
       (select d.phoneno
        from routecontrol rc, route r, depot d
        where a.routecontrol_id = rc.routecontrol_id
              and rc.route_id = r.route_id
              and r.depot_id = d.depot_id
       ) depotphoneno,
       (select cc.taxauthoritycode
        from citycounty cc, customer c
        where a.deltocustomer_link_id = c.customer_id
        and c.citytaxauthority_id = cc.citycounty_id
       ) deltotaxauthcode,
       a.creditsqueezeamount, b.invoiceamountdecimals, b.description currencydescription, a.totalamountexclvat,
       b.decimals, a.startdate, a.enddate,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       --'08' invoicelayoutcode,
       e.code default_BU_code,
       --(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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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,
       --coalesce((select max(pa.packingnote_id) from packingnote pa, packingnoteline pl where pa.packingnote_id=pl.packingnote_id and pl.invoiceheader_id = a.invoiceheader_id and a.invoicefrequency_id = 0 and pa.origin = 5), 0) setspecial,       --0 is not based on special order, >0 is based on special order
--(case when A.CLUSTER_ID is null then (select max(C.CODE)
--	                                                 from CUSTOMERSPERCLUSTER CPC, CUSTOMERCLUSTER C
--	                                                 where C.INVOICEFREQUENCY_ID = A.INVOICEFREQUENCY_ID
--	                                                       and CPC.CLUSTER_ID = C.CLUSTER_ID and CPC.CUSTOMER_ID = a.billtocustomer_link_id)
--	                                           else (select cc.code from customercluster cc where cc.cluster_id = a.cluster_id) end) clustercode,
(select languages.code from languages, customer c where a.deltocustomer_link_id = c.customer_id and languages.language_id = C.LANGUAGE_ID) deltocustlang
, ihextr.paymenttermsduedate, a.reference, a.activityreference,
(select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix
--,(select max(wo.referencenumber)from workorder wo where wo.invoiceheader_id=a.invoiceheader_id group by wo.referencenumber) WORefNr
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),
      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)
where a.currency_id = b.currency_id
      and a.documenttype in (1, 8)
      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

/
create or replace view V_INVOICEHEADER_DN_NLI
 (NOTENUMBER, INVOICEHEADER_ID)
as select distinct pn.notenumber,
       pnl.invoiceheader_id
  from packingnote pn, packingnoteline pnl, invoiceline il
 where pn.packingnote_id = pnl.packingnote_id
   and pnl.invoiceheader_id = il.invoiceheader_id
   order by pn.notenumber

/
create or replace view V_INVOICEHEADER_HCO
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS
, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE
, INTERNALVATNUMBER, VATNUMBER, SETSPECIAL, CLUSTERCODE, DELTOCUSTLANG, PAYMENTTERMSDUEDATE, REFERENCE, ACTIVITYREFERENCE, PRINTTAXONAPPENDIX, CREATIONTIME, CREATORNAME)
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, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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,
       coalesce((select max(pa.packingnote_id) from packingnote pa, packingnoteline pl where pa.packingnote_id=pl.packingnote_id and pl.invoiceheader_id = a.invoiceheader_id and a.invoicefrequency_id = 0 and pa.origin = 5), 0) setspecial,       --0 is not based on special order, >0 is based on special order
(case when A.CLUSTER_ID is null then (select max(C.CODE)
                                                   from CUSTOMERSPERCLUSTER CPC, CUSTOMERCLUSTER C
                                                   where C.INVOICEFREQUENCY_ID = A.INVOICEFREQUENCY_ID
                                                         and CPC.CLUSTER_ID = C.CLUSTER_ID and CPC.CUSTOMER_ID = a.billtocustomer_link_id)
                                             else (select cc.code from customercluster cc where cc.cluster_id = a.cluster_id) end) clustercode,
(select languages.code from languages, customer c where a.deltocustomer_link_id = c.customer_id and languages.language_id = C.LANGUAGE_ID) deltocustlang
, ihextr.paymenttermsduedate, a.reference, a.activityreference,
(select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix
, a.timestamp CreationTime
, sysu.fullname CreatorName
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 JOIN systemuser sysu on sysu.systemuser_id=a.systemuser_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)
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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

/
create or replace view V_INVOICEHEADER_HHM
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS
, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE
, INTERNALVATNUMBER, VATNUMBER, SETSPECIAL, CLUSTERCODE, DELTOCUSTLANG, PAYMENTTERMSDUEDATE, DELIVERYDATE, BILLTO_PHONENO, BILLTO_FAXNO, BILLTO_EMAIL)
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, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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,
       coalesce((select max(pa.packingnote_id) from packingnote pa, packingnoteline pl where pa.packingnote_id=pl.packingnote_id and pl.invoiceheader_id = a.invoiceheader_id and a.invoicefrequency_id = 0 and pa.origin = 5), 0) setspecial,       --0 is not based on special order, >0 is based on special order
(case when A.CLUSTER_ID is null then (select  C.CODE
                                                   from CUSTOMERSPERCLUSTER CPC, CUSTOMERCLUSTER C
                                                   where C.INVOICEFREQUENCY_ID = A.INVOICEFREQUENCY_ID
                                                         and CPC.CLUSTER_ID = C.CLUSTER_ID and CPC.CUSTOMER_ID = a.billtocustomer_link_id)
                                             else (select cc.code from customercluster cc where cc.cluster_id = a.cluster_id) end) clustercode,
       (select languages.code from languages, customer c where a.deltocustomer_link_id = c.customer_id and languages.language_id = C.LANGUAGE_ID) deltocustlang
, ihextr.paymenttermsduedate
, coalesce ((select min(wo.completiondate) from workorder wo where wo.invoiceheader_id=a.invoiceheader_id),(select min(pn.deliverydate) from packingnote pn, packingnoteline pnl
where pn.packingnote_id=pnl.packingnote_id and pnl.invoiceheader_id=a.invoiceheader_id))deliverydate,
(select c.phoneno from customer c where c.customer_id=a.billtocustomer_link_id) billto_phoneno,
(select c.faxno from customer c where c.customer_id=a.billtocustomer_link_id) billto_faxno,
(select c.email from customer c where c.customer_id=a.billtocustomer_link_id) billto_email
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),
      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)
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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

/
create or replace view V_INVOICEHEADER_JWR
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS
, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE
, INTERNALVATNUMBER, VATNUMBER, SETSPECIAL, CLUSTERCODE, STMONTH, BILLTOSEARCH, DELTOSEARCH)
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, a.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,
       CASE WHEN a.street = COALESCE((SELECT max(ad.street) FROM customer bill, Address ad WHERE a.billtocustomer_link_id = bill.customer_id AND bill.mailaddress_id = ad.address_id), '')
         THEN CASE WHEN a.street = a.street2 then NULL
              else a.street2 end
			 ELSE NULL END 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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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,
       coalesce((select max(pa.packingnote_id) from packingnoteline pa where pa.invoiceheader_id = a.invoiceheader_id and a.invoicefrequency_id = 0 and pa.origin = 5), 0) setspecial,
       --0 is not based on special order, >0 is based on special order
       (select max(customercluster.code) from customerspercluster, customercluster where customerspercluster.customer_id = a.billtocustomer_link_id and customerspercluster.cluster_id = customercluster.cluster_id) clustercode,
        --WBO Extra for JWR
        to_char(a.nextperiodstartdate,'MM')stmonth,
        (select cubi.searchname from customer cubi where cubi.customer_id = a.billtocustomer_link_id) billtosearch,
        (select cudel.searchname from customer cudel where cudel.customer_id = a.deltocustomer_link_id ) deltosearch
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),
      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)
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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

/
create or replace view V_INVOICEHEADER_LGR
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE
, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE, DEFAULT_BU_CODE, NO_OF_SOILTICKETS
, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC
, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, INVOICEADDRESS_ID, CUSTOMER_ID, DEBTOR_ID, WEIGHTDECIMALSMANUALINPUT, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE
)
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, a.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,
       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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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
, dell.invoiceaddress_id, dell.customer_id, dell.debtor_id
       , cast(SS1.VALUE as numeric) WEIGHTDECIMALSMANUALINPUT
       , (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
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 customer dell on dell.customer_id = a.deltocustomer_link_id
        LEFT OUTER JOIN reasoncode rc ON (a.adjustmentreason_id = rc.reasoncode_id)
        LEFT OUTER JOIN invoicesignature ihs ON (ihs.invoiceheader_id = a.invoiceheader_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)
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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

/
create or replace view V_INVOICEHEADER_MER
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE
, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE, DEFAULT_BU_CODE, NO_OF_SOILTICKETS
, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC
, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, INVOICEADDRESS_ID, CUSTOMER_ID, DEBTOR_ID, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE)
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, a.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,
       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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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
, dell.invoiceaddress_id, dell.customer_id, dell.debtor_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 = (SELECT C.LANGUAGE_ID
                     FROM CUSTOMER C WHERE C.CUSTOMER_ID = A.DELTOCUSTOMER_LINK_ID)) GENERALINV_REMARK_CUSTOMER
       , p.invoiceremarkstartdate, p.invoiceremarkenddate
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'),
      address x, country,
      invoiceheader a
        left outer join customer dell on dell.customer_id = a.deltocustomer_link_id
        LEFT OUTER JOIN reasoncode rc ON (a.adjustmentreason_id = rc.reasoncode_id)
        LEFT OUTER JOIN invoicesignature ihs ON (ihs.invoiceheader_id = a.invoiceheader_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)
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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

/
create or replace view V_INVOICEHEADER_NAF
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, FAXNO, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE
, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE, DEFAULT_BU_CODE, SPLITUPCODE, SPLITUPDESCRIPTION, PARENTINVOICEHEADER_ID
, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE
, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, DELTO_MAIL_STREET, DELTO_MAIL_STREET2, DELTO_MAIL_ZIPCODE, DELTO_MAIL_CITY, DELTO_MAIL_STATE, DELTO_MAIL_COUNTY, DELTO_EXTRANAME1, DELTO_EXTRANAME2, PLANTDELTO22, PLANTDELTOCODE, PLANTDELTONAME, PLANTDELTOSTREET, PLANTDELTOZIP, PLANTDELTOCITY, PLANTDELTOPHONE, PLANTDELTOFAX, PLANTDELTOEMAIL, PLANTDELTOWEBSITE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE
, MIN_YEAR_WEEKS, WEIGHTDECIMALSMANUALINPUT, SETSPECIAL, DRIVERNAME, HASSIGNATURE, PLANTWEBSITE, M_SORT_US_ASC, M_SORT_US_DESC, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, CUST_LANGUAGECODE)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       a.invoicenumber, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, cast(a.billtocustomername as varchar2(60)) billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, cast(a.deltocustomername as varchar2(60)) 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,
       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,
       ihextr.billtocountrydescription, ihextr.deltocountrydescription,
       ihextr.deltocustvatnumber,
       ihextr.customermarkinggarment, ihextr.taxable, ihextr.siccode, ihextr.invoicecopies,
       ihextr.attachinvoicecopies, ihextr.paymenttermsdescription paymentterms_desc,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       a.splitupcode, a.splitupdescription,
       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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.deltostate,
       country.description PLANTCOUNTRYDESCRIPTION, cast(SS.VALUE as varchar2(60)) WEIGHTUNIT,
       a.roundingamount, A.NEXTPERIODSTARTDATE, A.NEXTPERIODENDDATE, A.NEXTPERIODNOWEEKS,
       DELTO_MAIL.STREET DELTO_MAIL_STREET, DELTO_MAIL.STREET2 DELTO_MAIL_STREET2, DELTO_MAIL.ZIPCODE DELTO_MAIL_ZIPCODE,
       DELTO_MAIL.CITY DELTO_MAIL_CITY, DELTO_MAIL.STATE DELTO_MAIL_STATE, DELTO_MAIL.COUNTY DELTO_MAIL_COUNTY,
       DELTO.Extraname1 DELTO_Extraname1, DELTO.Extraname2 DELTO_Extraname2,
       case when ((plantdelto.plantdeltocode is not null) and (a.invoicetype <> 2)) THEN plantdelto.plantdeltocode ELSE plantdelto2.code END plantdelto22,
       case when ((plantdelto.plantdeltocode is not null) and (a.invoicetype <> 2)) THEN plantdelto.plantdeltocode ELSE plantdelto2.code END plantdeltocode,
       case when ((plantdelto.plantdeltocode is not null) and (a.invoicetype <> 2)) THEN plantdelto.plantdeltoname ELSE plantdelto2.name END plantdeltoname,
       case when ((plantdelto.plantdeltocode is not null) and (a.invoicetype <> 2)) THEN plantdelto.plantdeltostreet ELSE plantadradelto2.street END plantdeltostreet,
       case when ((plantdelto.plantdeltocode is not null) and (a.invoicetype <> 2)) THEN plantdelto.plantdeltozip ELSE plantadradelto2.zipcode END plantdeltozip,
       case when ((plantdelto.plantdeltocode is not null) and (a.invoicetype <> 2)) THEN plantdelto.plantdeltocity ELSE plantadradelto2.city END plantdeltocity,
       case when ((plantdelto.plantdeltocode is not null) and (a.invoicetype <> 2)) THEN plantdelto.plantdeltophone ELSE plantdelto2.phoneno END plantdeltophone,
       case when ((plantdelto.plantdeltocode is not null) and (a.invoicetype <> 2)) THEN plantdelto.plantdeltofax ELSE plantdelto2.faxno END plantdeltofax   ,
       case when ((plantdelto.plantdeltocode is not null) and (a.invoicetype <> 2)) THEN plantdelto.plantdeltoemail ELSE plantdelto2.email END plantdeltoemail,
       case when ((plantdelto.plantdeltocode is not null) and (a.invoicetype <> 2)) THEN plantdelto.plantdeltowebsite ELSE plantdelto2.website END plantdeltowebsite,
       (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
       , cast(FSGET_MIN_5_YEARWEEKS(a.invoiceheader_id, a.invoicefrequency_id) as varchar2(39)) min_year_weeks
       , cast(SS1.VALUE as numeric) WEIGHTDECIMALSMANUALINPUT
       , CASE
       WHEN exists (select max(pa.packingnote_id) from packingnote pa, packingnoteline pl where pa.packingnote_id=pl.packingnote_id and pl.invoiceheader_id = a.invoiceheader_id and a.invoicefrequency_id = 0 and pa.origin = 5)
            Then 1
            Else 0
       END setspecial --todo 4718
      , (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
         , p.website plantwebsite --end todo 4718
, cast(GETSORTUSASC(a.routenumber, a.stopnumber, a.deltocustomernumber, a.invoicenumber) as varchar2(60)) as M_Sort_US_Asc
, cast(GETSORTUSDESC(a.routenumber, a.stopnumber, a.deltocustomernumber, a.invoicenumber) as varchar2(60)) as M_Sort_US_Desc,
ihextr.paymenttype, ihextr.discountdays, ihextr.paymentdiscount, ihextr.discountdays2, ihextr.paymentdiscount2
, (select lan.code from languages lan where lan.language_id = delto.language_id) cust_languagecode
   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 customer DELTO
             left outer join address DELTO_MAIL on (delto.mailaddress_id = delto_mail.address_id)
        ON (DELTO.CUSTOMER_ID = A.DELTOCUSTOMER_LINK_ID)
             JOIN businessunit budelto2
                 join plant plantdelto2
                      join address plantadradelto2 on plantdelto2.address_id = plantadradelto2.address_id
                 on budelto2.plant_id = plantdelto2.plant_id
            on (delto.defaultbusinessunit_id = budelto2.businessunit_id)
        LEFT OUTER JOIN invoicesignature ihs ON (ihs.invoiceheader_id = a.invoiceheader_id)
        LEFT OUTER JOIN (select il.invoiceheader_id,
                         p.code plantdeltocode, p.name plantdeltoname, adr.street plantdeltostreet, adr.zipcode plantdeltozip, adr.city plantdeltocity,
                         p.phoneno plantdeltophone, p.faxno plantdeltofax, p.email plantdeltoemail, p.website plantdeltowebsite
                         from invoiceline il, businessunit b, plant p, address adr
                         where il.processingbusinessunit_id = b.businessunit_id
                         and   il.processingbusinessunit_id = (select max(ili.processingbusinessunit_id)
                                                               from invoiceline ili
                                                               where il.invoiceheader_id = ili.invoiceheader_id)
                         and   b.plant_id = p.plant_id
                         and   p.address_id = adr.address_id
                         group by il.invoiceheader_id, p.code, p.name, adr.street, adr.zipcode, adr.city,
                                  p.phoneno, p.faxno, p.email, p.website) plantdelto
       on a.invoiceheader_id = plantdelto.invoiceheader_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)
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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

/
create or replace view V_INVOICEHEADER_NLI
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS
, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, NOOFWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE
, INVOICEREMARKENDDATE, INTERNALVATNUMBER, VATNUMBER, SETSPECIAL, CLUSTERCODE, DELTOCUSTLANG, PAYMENTTERMSDUEDATE, REFERENCE, ACTIVITYREFERENCE, PRINTTAXONAPPENDIX, WOREFNR)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       a.invoicenumber, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber,a.billtocustomername billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber,a.deltocustomername 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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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,
       round((to_date(a.enddate,'dd-mm-yy') - to_date(a.startdate,'dd-mm-yy'))/7) noofweeks,
       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,
       coalesce((select max(pa.packingnote_id) from packingnote pa, packingnoteline pl where pa.packingnote_id=pl.packingnote_id and pl.invoiceheader_id = a.invoiceheader_id and a.invoicefrequency_id = 0 and pa.origin = 5), 0) setspecial,       --0 is not based on special order, >0 is based on special order
(case when A.CLUSTER_ID is null then (select max(C.CODE)
	                                                 from CUSTOMERSPERCLUSTER CPC, CUSTOMERCLUSTER C
	                                                 where C.INVOICEFREQUENCY_ID = A.INVOICEFREQUENCY_ID
	                                                       and CPC.CLUSTER_ID = C.CLUSTER_ID and CPC.CUSTOMER_ID = a.billtocustomer_link_id)
	                                           else (select cc.code from customercluster cc where cc.cluster_id = a.cluster_id) end) clustercode,
(select languages.code from languages, customer c where a.deltocustomer_link_id = c.customer_id and languages.language_id = C.LANGUAGE_ID) deltocustlang
, ihextr.paymenttermsduedate, a.reference, a.activityreference,
(select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix
,(select max(wo.referencenumber)from workorder wo where wo.invoiceheader_id=a.invoiceheader_id group by wo.referencenumber) WORefNr
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),
      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)
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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

/
create or replace view V_INVOICEHEADER_PCO
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE
, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE
, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE
, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, RCDRIVINGDAY, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, DELTOPHONE)
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, a.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,
       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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode,
-- 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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 GETABSDAYNUMBER(rcntrl1.drivingdate) from routecontrol rcntrl1
          where rcntrl1.routecontrol_id = a.routecontrol_id) rcDrivingDay
       , (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
       , deltocust.phoneno DELTOPHONE
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 customer deltocust on (a.deltocustomer_link_id = deltocust.customer_id)
        LEFT OUTER JOIN reasoncode rc ON (a.adjustmentreason_id = rc.reasoncode_id)
        LEFT OUTER JOIN invoicesignature ihs ON (ihs.invoiceheader_id = a.invoiceheader_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)
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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

/
create or replace view V_INVOICEHEADER_PHS
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS
, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE
, INTERNALVATNUMBER, VATNUMBER, SETSPECIAL, CLUSTERCODE, DELTOCUSTLANG, PAYMENTTERMSDUEDATE, REFERENCE, ACTIVITYREFERENCE, PRINTTAXONAPPENDIX, WOREFNR, SALESNOTEREFNR)
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, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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,
       coalesce((select max(pa.packingnote_id) from packingnote pa, packingnoteline pl where pa.packingnote_id=pl.packingnote_id and pl.invoiceheader_id = a.invoiceheader_id and a.invoicefrequency_id = 0 and pa.origin = 5), 0) setspecial,       --0 is not based on special order, >0 is based on special order
(case when A.CLUSTER_ID is null then (select max(C.CODE)
                                                  from CUSTOMERSPERCLUSTER CPC, CUSTOMERCLUSTER C
                                                  where C.INVOICEFREQUENCY_ID = A.INVOICEFREQUENCY_ID
                                                        and CPC.CLUSTER_ID = C.CLUSTER_ID and CPC.CUSTOMER_ID = a.billtocustomer_link_id)
                                            else (select cc.code from customercluster cc where cc.cluster_id = a.cluster_id) end) clustercode,
(select languages.code from languages, customer c where a.deltocustomer_link_id = c.customer_id and languages.language_id = C.LANGUAGE_ID) deltocustlang
, ihextr.paymenttermsduedate, a.reference, a.activityreference,
(select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix
,(select max(wo.referencenumber)from workorder wo where wo.invoiceheader_id=a.invoiceheader_id group by wo.referencenumber) WORefNr
,(select max(wo.referencenumber) from workorder wo, packingnote pn, packingnoteline pnl where wo.workorder_id = pn.salesnote_id and pn.packingnote_id = pnl.packingnote_id and pnl.invoiceheader_id = a.invoiceheader_id) SalesNoteRefNr
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),
      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)
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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

/
create or replace view V_INVOICEHEADER_POS
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE
, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE, DEFAULT_BU_CODE, ADJUSTMENT_REASONCODE, SPLITUPCODE
, SPLITUPDESCRIPTION, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION
, WEIGHTUNIT, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, DRIVERNAME, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, SALESREP, CONTACTPERSON_NAME, DUEDATE)
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, a.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,
       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,
       ihextr.billtocountrydescription, ihextr.deltocountrydescription,
       ihextr.deltocustvatnumber,
       ihextr.customermarkinggarment, ihextr.taxable, ihextr.siccode, ihextr.invoicecopies
      , ihextr.attachinvoicecopies, ihextr.paymenttermsdescription paymentterms_desc,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
      rc.code Adjustment_ReasonCode
       , a.splitupcode, a.splitupdescription
       , 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.deltostate,
       country.description PLANTCOUNTRYDESCRIPTION, SS.VALUE WEIGHTUNIT,
       a.roundingamount, A.NEXTPERIODSTARTDATE, A.NEXTPERIODENDDATE, A.NEXTPERIODNOWEEKS,
       ihextr.paymenttype, ihextr.discountdays, ihextr.paymentdiscount, ihextr.discountdays2, ihextr.paymentdiscount2
       , (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
       , (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
/*, (select min(emp.name) from contractspercustomer cpc, employee emp where cpc.dateactive <= a.invoicedate and cpc.dateinactive > a.invoicedate
  and cpc.customer_id = a.deltocustomer_link_id and cpc.salesemployee_id = emp.employee_id
  and cpc.signdate in (select max(cpc1.signdate) from contractspercustomer cpc1
  where cpc1.dateactive <= a.invoicedate and cpc1.dateinactive > a.invoicedate and cpc1.customer_id = a.deltocustomer_link_id)) SalesRep*/
, (select min(dr.name) from route Ro, employee dr where a.route_id = ro.route_id and ro.driver_id = dr.employee_id ) SalesRep
, (select max(emp.name) from employee emp, customer delto where a.deltocustomer_link_id = delto.customer_id and delto.serviceemployee_id = emp.employee_id) ContactPerson_name
, ihextr.paymenttermsduedate DueDate
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'),
      address x, country,
      invoiceheader a
        LEFT OUTER JOIN reasoncode rc ON (a.adjustmentreason_id = rc.reasoncode_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)
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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

/
create or replace view V_INVOICEHEADER_REV
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS
, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE
, INTERNALVATNUMBER, VATNUMBER, SETSPECIAL, CLUSTERCODE, PAYMENTTERMSDUEDATE, REFERENCE, DIVISIONDESC, REGIONDESC, LANGUAGECODE)
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, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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_6_YEARWEEKS(a.invoiceheader_id, a.invoicefrequency_id) as varchar2(47)) 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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 NUMBER) 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,
       coalesce((select max(pa.packingnote_id) from packingnote pa, packingnoteline pl where pa.packingnote_id=pl.packingnote_id and pl.invoiceheader_id = a.invoiceheader_id and a.invoicefrequency_id = 0 and pa.origin = 5), 0) setspecial,       --0 is not based on special order, >0 is based on special order
(case when A.CLUSTER_ID is null then (select  C.CODE
	                                                 from CUSTOMERSPERCLUSTER CPC, CUSTOMERCLUSTER C
	                                                 where C.INVOICEFREQUENCY_ID = A.INVOICEFREQUENCY_ID
	                                                       and CPC.CLUSTER_ID = C.CLUSTER_ID and CPC.CUSTOMER_ID = a.billtocustomer_link_id)
	                                           else (select cc.code from customercluster cc where cc.cluster_id = a.cluster_id) end) clustercode
, ihextr.paymenttermsduedate, a.reference, --a.activityreference,
--(select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix,
 (select dd.description from division_desc dd where e.division_id = dd.division_id and dd.language_id = p.language_id) divisiondesc
, (select rd.description from region_desc rd where e.region_id = rd.region_id and rd.language_id = p.language_id) regiondesc,
(select languagecode from  customer_link cl where cl.customer_link_id = a.billtocustomer_link_id) languagecode
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),
      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)
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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

/
create or replace view V_INVOICEHEADER_RSS
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS
, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE
, INTERNALVATNUMBER, VATNUMBER, SETSPECIAL, CLUSTERCODE, DELTOCUSTLANG, PAYMENTTERMSDUEDATE, REFERENCE, ACTIVITYREFERENCE, PRINTTAXONAPPENDIX, CC_STREET, CC_ZIP, CC_CITY, EANNUMBER)
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, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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,
       coalesce((select max(pa.packingnote_id) from packingnote pa, packingnoteline pl where pa.packingnote_id=pl.packingnote_id and pl.invoiceheader_id = a.invoiceheader_id and a.invoicefrequency_id = 0 and pa.origin = 5), 0) setspecial,       --0 is not based on special order, >0 is based on special order
(case when A.CLUSTER_ID is null then (select max(C.CODE)
	                                                 from CUSTOMERSPERCLUSTER CPC, CUSTOMERCLUSTER C
	                                                 where C.INVOICEFREQUENCY_ID = A.INVOICEFREQUENCY_ID
	                                                       and CPC.CLUSTER_ID = C.CLUSTER_ID and CPC.CUSTOMER_ID = a.billtocustomer_link_id)
	                                           else (select cc.code from customercluster cc where cc.cluster_id = a.cluster_id) end) clustercode,
(select languages.code from languages, customer c where a.deltocustomer_link_id = c.customer_id and languages.language_id = C.LANGUAGE_ID) deltocustlang
, ihextr.paymenttermsduedate, a.reference, a.activityreference,
(select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix
,coalesce(ad.street,'') cc_street
,coalesce(ad.zipcode,'') cc_zip
,coalesce(ad.city,'') cc_city
,cc.eannumber
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 costcenter cc on (cc.code = a.splitupcode and cc.customer_id = a.billtocustomer_link_id)
        LEFT OUTER JOIN address ad on (cc.invoiceaddress_id = ad.address_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)
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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

/
create or replace view V_INVOICEHEADER_RS_AUJ
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, TOTALAMOUNTEXCLVAT, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION
, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE, DEFAULT_BU_CODE, SPLITUPCODE, SPLITUPDESCRIPTION, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, IBANNO, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS
, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, INTERNALVATNUMBER, VATNUMBER, PAYMENTTERMSDUEDATE, REFERENCE, ACTIVITYREFERENCE, DELTO_PNNUMBER, DELTO_PHONENO, DELTO_FAXNO, DELTO_SEARCHNAME, DELTO_LEGALNAME, SALESAREA_CODE, SALESAREA_DESC, DELTO_NAMEONLABEL, CHAIN_CODE, BILLTOCOMMENT, DELTO_DEPNR, BILLINGDAYNR, AR_BALANCEPASTDUE, PAYMENTTYPEPAYBY, PAYMENTTYPE, DUE_DATE_OLDEST_OPEN_INVOICE, DEBITOPEN)
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, a.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,
       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, a.totalamountexclvat, a.startdate, a.enddate,
       ihextr.billtocountrydescription, ihextr.deltocountrydescription, ihextr.deltocustvatnumber,
       ihextr.customermarkinggarment, ihextr.taxable, ihextr.siccode, ihextr.invoicecopies,
       ihextr.attachinvoicecopies, ihextr.paymenttermsdescription paymentterms_desc,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code, a.splitupcode, a.splitupdescription,
       a.parentinvoiceheader_id, a.contractstartdate, a.contractenddate,
       ihextr.bankaccount, ihextr.ibanno,
       a.paymentdiscountdays, a.creditsqueezeperc, a.netpaymentdays,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.deltostate,
       a.roundingamount, A.NEXTPERIODSTARTDATE, A.NEXTPERIODENDDATE, A.NEXTPERIODNOWEEKS,--ihextr.paymenttype,
       ihextr.discountdays, ihextr.paymentdiscount, ihextr.discountdays2, ihextr.paymentdiscount2
, e.internalvatnumber, e.vatnumber, ihextr.paymenttermsduedate, a.reference, a.activityreference
, del.pnnumber delto_pnnumber,del.phoneno delto_phoneno,del.faxno delto_faxno,del.searchname delto_searchname, del.legalname delto_legalname
, (select sa.code from salesarea sa where sa.salesarea_id = del.salesarea_id) salesarea_code
, (select sad.description from salesarea_desc sad where sad.salesarea_id = del.salesarea_id
          and sad.language_id = del.language_id) salesarea_desc
, del.customermarkinggarment DelTo_NameOnLabel
, (select ch.code from chain ch, customer bill where del.debtor_id = bill.customer_id and ch.chain_id = bill.chain_id) chain_code
, (select max(cbc.description) from customerbillingcomment cbc where cbc.customer_id = a.billtocustomer_link_id and cbc.type = 1
and cbc.startdate <= a.invoicedate and a.invoicedate <= cbc.enddate) BillToComment
, (select max(dep.departmentnumber) from department dep where dep.customer_id = del.customer_id) delto_depnr
, (select min(cdd.day_id) from CUSTOMERDELIVERYDAY cdd where a.deltocustomer_link_id = cdd.customer_id
and cdd.typeofmerchadise = 1 and cdd.deliverytype = 'B') BillingDayNr
, nvl((select sum(nvl(art.amount, 0) - art.totalappliedamount)
     from artransaction art, invoiceheaderextrainfo x, artransactiontype artt
    where art.invoiceheader_id = x.invoiceheader_id--and art.closingtransaction_id is null
      and x.paymenttermsduedate <= trunc(sysdate)
      and art.isopen_yn = 'Y' and art.debitcredit = 'D'
      and art.artransactiontype_id = artt.artransactiontype_id and artt.typenumber = 1
      and art.deltocustomer_link_id = a.deltocustomer_link_id), 0) AR_BalancePastDue
, coalesce((select cpb.paymenttype from customer cpb where cpb.customer_id=ihextr.PAYBYCUSTOMER_LINK_ID)
       , ihextr.paymenttype) paymenttypePayBy
, ihextr.paymenttype
, trunc(sysdate) - (select min(x.paymenttermsduedate) from artransaction art, invoiceheaderextrainfo x, artransactiontype artt
    where art.invoiceheader_id = x.invoiceheader_id --and art.closingtransaction_id is null
      and art.deltocustomer_link_id = a.deltocustomer_link_id
      and x.paymenttermsduedate <= trunc(sysdate)
      and art.isopen_yn = 'Y' and art.debitcredit = 'D'
      and art.artransactiontype_id = artt.artransactiontype_id and artt.typenumber = 1) Due_Date_Oldest_Open_Invoice
, (select count(1) from  artransaction art
    where art.invoiceheader_id = a.invoiceheader_id
      and art.closingtransaction_id is null
      and art.isopen_yn = 'Y'
      and art.debitcredit = 'D') debitopen
from  businessunit e, invoiceheader a
        LEFT OUTER JOIN customer del ON (del.customer_id = a.deltocustomer_link_id),
      invoiceheaderextrainfo ihextr
where a.documenttype = 1
      and a.invoicebusinessunit_id = e.businessunit_id
      and a.invoiceheader_id = ihextr.invoiceheader_id

/
create or replace view V_INVOICEHEADER_SBN
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS
, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE
, INTERNALVATNUMBER, VATNUMBER, SETSPECIAL, CLUSTERCODE, DELTOCUSTLANG, ACCEPTGIROLINE, ACCEPTCODELINE, SERVICEEMPLOYEE)
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, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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_6_YEARWEEKS(a.invoiceheader_id, a.invoicefrequency_id) as varchar2(47)) 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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 NUMBER) 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,
       coalesce((select max(pa.packingnote_id) from packingnote pa, packingnoteline pl where pa.packingnote_id=pl.packingnote_id and pl.invoiceheader_id = a.invoiceheader_id and a.invoicefrequency_id = 0 and pa.origin = 5), 0) setspecial,
       --0 is not based on special order, >0 is based on special order
(select cc.code from customercluster cc where cc.cluster_id = a.cluster_id) clustercode,
       (select languages.code from languages, customer c where a.deltocustomer_link_id = c.customer_id and languages.language_id = C.LANGUAGE_ID) deltocustlang
,cast(ihextr.acceptgiroreference as varchar(60)) acceptgiroline
,cast(ihextr.acceptgirocodeline as varchar(60)) acceptcodeline
,( select emp.name
   from   employee emp
   where  emp.employee_id = ( select btc.serviceemployee_id
                              from   customer btc
                              where  btc.customer_id = ( select cl.customer_id
                                                         from   customer_link cl
                                                         where  cl.customer_link_id = a.billtocustomer_link_id )
                            )
 ) serviceemployee
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),
      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)
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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

/
create or replace view V_INVOICEHEADER_SGS
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS
, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE
, INTERNALVATNUMBER, VATNUMBER, SETSPECIAL, CLUSTERCODE, DELTOCUSTLANG, PAYMENTTERMSDUEDATE, REFERENCE, ACTIVITYREFERENCE, PRINTTAXONAPPENDIX, WOREFNR, BILLTO_LEGACYNUMBER, BILLTO_VATNUMBER, NRWEEKS, PN_REMARK, PN_COUNT)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       a.invoicenumber, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, cast(a.billtocustomername as varchar2(63)) billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, cast(a.deltocustomername as varchar2(63)) 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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.deltostate,
       country.description PLANTCOUNTRYDESCRIPTION, cast(SS.VALUE as varchar2(63)) 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,
       coalesce((select max(pa.packingnote_id) from packingnote pa, packingnoteline pl where pa.packingnote_id=pl.packingnote_id and pl.invoiceheader_id = a.invoiceheader_id and a.invoicefrequency_id = 0 and pa.origin = 5), 0) setspecial,       --0 is not based on special order, >0 is based on special order
(case when A.CLUSTER_ID is null then (select max(C.CODE)
	                                                 from CUSTOMERSPERCLUSTER CPC, CUSTOMERCLUSTER C
	                                                 where C.INVOICEFREQUENCY_ID = A.INVOICEFREQUENCY_ID
	                                                       and CPC.CLUSTER_ID = C.CLUSTER_ID and CPC.CUSTOMER_ID = a.billtocustomer_link_id)
	                                           else (select cc.code from customercluster cc where cc.cluster_id = a.cluster_id) end) clustercode,
(select languages.code from languages, customer c where a.deltocustomer_link_id = c.customer_id and languages.language_id = C.LANGUAGE_ID) deltocustlang
, ihextr.paymenttermsduedate, a.reference, a.activityreference
, (select c.printtaxonappendix from customer c where c.customer_id = a.billtocustomer_link_id) printtaxonappendix
, (select max(wo.referencenumber)from workorder wo where wo.invoiceheader_id=a.invoiceheader_id group by wo.referencenumber) WORefNr
, billTo.Legacycustomernumber billTo_Legacynumber, billTo.Vatnumber billTo_Vatnumber,
TRUNC(getDateDiff(coalesce(a.nextperiodenddate, a.enddate), coalesce(a.nextperiodstartdate, a.startdate)) / 7 )  NrWeeks ,
(select max(pn.remark) from packingnote pn, packingnoteline pnl where pn.packingnote_id = pnl.packingnote_id
        and pnl.invoiceheader_id = a.invoiceheader_id ) PN_Remark,
(select count(distinct pnl.packingnote_id) from packingnoteline pnl where pnl.invoiceheader_id = a.invoiceheader_id ) PN_count
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, customer billTo,
      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),
      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)
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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 billTo.Customer_Id = a.billtocustomer_link_id

/
create or replace view V_INVOICEHEADER_SMG
 (INVOICEDATE, INVOICEDATESTR, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, DELTOCUSTNOLEGALNAME, PASSERBYCUSTOMER, CITY, ZIPCODE, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, INVOICECOMMENTS, INVOICETYPE, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, STATUSTYPE, STATUSCODE, ROUTECONTROL_ID, INVOICEHEADER_ID
, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, INVOICECOPIES, INVOICELAYOUTCODE, TAXABLE, PAYMENTTERMS_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PARENTINVOICEHEADER_ID, PARENTINVNR, CHILDNR, CREDITSQUEEZEPERC, DELTOSTREET, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, PLANTCOUNTRYDESCRIPTION, ROUNDINGAMOUNT, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER
, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, INTERNALVATNUMBER, VATNUMBER, SETSPECIAL, DELTOCOUNTRYID, DELTOCOUNTRYJOURNCODE, BILLTOCOUNTRYCODE, BILLTOSENDINVOICETO, INVCOUNTRY_ID, INVBUCOJURNALCODE, COSTCENTERPONUMBER, INVLNTYPEFIRSTLINE, CUSTTYPE, DELTOCUSTREMARK, PLANTDELREMARK, LEGALENTITY_LEGALNAME, PLANTLANGUAGE_ID, DELTOLANGUAGE_ID, LEGALENTITY_ID, BILLTOCUSTOMER_LINK_ID, DELTOCUSTOMER_LINK_ID, PLANT_STREET, PLANT_STREET2, PLANT_ZIPCODE, PLANT_CITY
, PLANT_STATE, PLANT_PHONENO, PLANT_FAXNO, PLANT_WEBSITE, PLANT_EMAIL, DEB_COCNUMBER, DEB_PNNUMBER, DEL_COCNUMBER, DEL_PNNUMBER, DEB_VATNUMBER, DEL_VATNUMBER, TAXFULLFIMENTDATE, LEGALENTITY_COCNR, LEGALENTITY_VATNR)
as select a.invoicedate, to_char(a.invoicedate,'DD-MON-YYYY') invoicedatestr, a.invoicedaynumber,
       a.invoicenumber, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber,
       (case when (del.sendinvoiceto = 0) then  a.deltocustomername
       else a.billtocustomername end) billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, cast((a.deltocustomername) as varchar2(40)) deltocustomername,
       (del.customernumber|| ' ' ||del.legalname) deltocustnolegalname, del.passerbycustomer,
       a.city, a.zipcode, a.street, a.routenumber, a.stopnumber,a.depotcode,a.invoicecomments,
       a.invoicetype,a.paythisamount, a.prebillamount, a.invoicefrequency_id invoicefrequencynumber,
       b.code currencycode,  s.statustype, s.code statuscode, a.routecontrol_id, a.invoiceheader_id,
       a.creditsqueezeamount, b.invoiceamountdecimals, b.description currencydescription, a.totalamountexclvat,
       b.decimals,  ihextr.billtocountrydescription, ihextr.deltocountrydescription,
       deb.vatnumber deltocustvatnumber, ihextr.invoicecopies, ihextr.formlayoutcode invoicelayoutcode, ihextr.taxable,--cast(
       ihextr.paymenttermsdescription --as varchar2(60))
       paymentterms_desc,
       a.splitupcode, a.splitupdescription,
       a.parentinvoiceheader_id, ( select ihp.invoicenumber from invoiceheader ihp where ihp.invoiceheader_id=a.parentinvoiceheader_id)parentinvnr,
       ( case when (a.parentinvoiceheader_id is null) then  ''
       else  substr(a.invoicenumber,-3) end) childnr,
       a.creditsqueezeperc,  a.deltostreet,  a.deltocounty, a.deltocity, a.deltozipcode,country.description PLANTCOUNTRYDESCRIPTION,
       a.roundingamount
, (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 = del.language_id) GENERALINV_REMARK_CUSTOMER
, p.invoiceremarkstartdate, p.invoiceremarkenddate, e.internalvatnumber, e.vatnumber
, coalesce((select max(pa.packingnote_id) from packingnote pa, packingnoteline pl where pa.packingnote_id=pl.packingnote_id and pl.invoiceheader_id = a.invoiceheader_id and a.invoicefrequency_id = 0 and pa.origin = 5), 0) setspecial--0 is not based on special order, >0 is based on special order
, (select co.country_id from country co where del.country_id = co.country_id) deltocountryid
, (select co.journalcode from country co where del.country_id = co.country_id) deltocountryJourncode
, (select billco.code from country billco where deb.country_id=billco.country_id) billtocountrycode
, del.sendinvoiceto billtosendinvoiceto -- ??why bill if is del ?
, country.country_id invcountry_id
, country.journalcode invbucoJurnalcode
,(select costc.ponumber from costcenter costc where costc.code = a.splitupcode and costc.customer_id = a.deltocustomer_link_id) costcenterponumber
,(select il.invoicelinetype_id from invoiceline il
         where il.invoiceline_id=(select min(il1.invoiceline_id) from invoiceline il1
               where il1.invoiceheader_id=a.invoiceheader_id  )) invlntypefirstline
, cast(F_GetCustType_smg(a.invoiceheader_id) as varchar2(10)) custtype
, (case when (del.sendinvoiceto = 1) then deb.remark else del.remark end) DelToCustRemark,
 (select pldesc.invoiceremark from plantinvoiceremark_desc pldesc, businessunit dbu where dbu.businessunit_id = deb.defaultbusinessunit_id
 and pldesc.plant_id = dbu.plant_id and pldesc.language_id = deb.language_id)  PlantDelRemark
, le.legalname LegalEntity_LegalName
, p.language_id PlantLanguage_ID, del.language_id DelToLanguage_ID, e.legalentity_id, a.billtocustomer_link_id, a.deltocustomer_link_id
, pad.street plant_street, pad.street2 plant_street2, pad.zipcode plant_zipcode, pad.city plant_city
, pad.state plant_state, coalesce(le.phone, p.phoneno) plant_phoneno, coalesce(le.fax, p.faxno) plant_faxno, coalesce(le.website, p.website) plant_website, coalesce(le.email, p.email) plant_email
, deb.cocnumber deb_cocnumber, deb.pnnumber deb_pnnumber, del.cocnumber del_cocnumber, del.pnnumber del_pnnumber
, deb.vatnumber deb_vatnumber, del.vatnumber del_vatnumber
, case when country.code in ('CZ', 'PL') then a.invoicedate
       when country.code in ('RS', 'HR') then ihextr.paymenttermsduedate
       when country.code in ('SK') then a.enddate
       when country.code in ('HU') then
            case when (ihextr.paymenttermsduedate - a.invoicedate) > 60 then a.enddate
              else ihextr.paymenttermsduedate end
  else null end TaxFullfimentDate, le.cocnumber legalentity_cocnr, le.vatnumber legalentity_vatnr
from currency b, businessunit e
left outer join legalentity le on le.legalentity_id = e.legalentity_id
, status s, plant p, country, invoiceheader a, invoiceheaderextrainfo ihextr
, customer deb, customer del, address pad
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.country_id = country.country_id
      and a.invoiceheader_id = ihextr.invoiceheader_id
      and a.deltocustomer_link_id = del.customer_id
      and a.billtocustomer_link_id = deb.customer_id
      and pad.address_id = p.address_id

/
create or replace view V_INVOICEHEADER_SNG
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, PNNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, FREQ_MW, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, HOUSENUMBER, HOUSENUMBEREXT, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS
, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE
, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, ADJUSTMENT_REASONCODE, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET
, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, COLLECTIONRESPEMPLOYEE
, CONSOLIDATED_INVOICE_LAYOUT, DELTO_CONTACTPERSONNAME, CUSTOMER_LANGUAGECODE, BILLTOLEGALNAME, LOGO, INTERNALVATNUMBER)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber, cu.pnnumber,
       a.invoicenumber, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, a.billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, a.deltocustomername,
       (case when a.invoicefrequency_id =10 then 'W'
             else 'M' end) freq_MW,
       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.housenumber,a.housenumberext,
       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,
       ihextr.billtocountrydescription, ihextr.deltocountrydescription,
       e.vatnumber deltocustvatnumber,
       ihextr.customermarkinggarment, ihextr.taxable, ihextr.siccode, ihextr.invoicecopies
       , ihextr.attachinvoicecopies, ihextr.paymenttermsdescription paymentterms_desc,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       rc.code Adjustment_ReasonCode
       , a.splitupcode, a.splitupdescription,
       ihs.personidentification, ihs.signature
       , 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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,
       a.nextperiodstartweek, a.nextperiodendweek,
       ihextr.paymenttype, ihextr.discountdays, ihextr.paymentdiscount, ihextr.discountdays2, ihextr.paymentdiscount2
       , cast(SS1.VALUE as numeric) WEIGHTDECIMALSMANUALINPUT
       , (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
       , (select empl.name from customerbillinginfo cbi, employee empl
          where cbi.customer_id = a.billtocustomer_link_id
                and empl.employee_id = cbi.collectionresponsible_id) collectionRespEmployee
, (CASE WHEN A.PARENTINVOICEHEADER_ID IS NOT NULL AND A.INVOICEHEADER_ID <> A.PARENTINVOICEHEADER_ID THEN
(SELECT IEXCONS.FORMLAYOUTCODE FROM INVOICEHEADEREXTRAINFO IEXCONS WHERE IEXCONS.INVOICEHEADER_ID = A.PARENTINVOICEHEADER_ID)
WHEN A.PARENTINVOICEHEADER_ID = A.INVOICEHEADER_ID THEN IHEXTR.FORMLAYOUTCODE --THIS SHOULD NOT HAPPEN
ELSE NULL
END )
consolidated_invoice_layout
, (select MIN(cp.name) from contactperson cp
   where cp.customer_id = a.deltocustomer_link_id
         and cp.contactpersonnumber = (select min(cpp.contactpersonnumber)
                                    from contactperson cpp where cpp.customer_id = a.deltocustomer_link_id)) delto_contactpersonname,
   lg.code customer_languagecode
, (select bc.legalname from customer bc where a.billtocustomer_link_id = bc.customer_id) BillToLegalName, p.logo, e.internalvatnumber
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),
      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),
      customer cu, languages lg
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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 a.deltocustomer_link_id = cu.customer_id
      and cu.language_id = lg.language_id

/
create or replace view V_INVOICEHEADER_STE
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2, BILLTO_STATE, BILLTO_ZIPCODE
, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE, DEFAULT_BU_CODE, ADJUSTMENT_REASONCODE, SPLITUPCODE, SPLITUPDESCRIPTION
, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE
, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, INVOICEADDRESS_ID, CUSTOMER_ID, DEBTOR_ID, WEIGHTDECIMALSMANUALINPUT, ROUTE_NUMBER, ROUTE_DESC, DRIVINGDAY_ID, ROUTE_DAY_DESC)
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, a.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,
       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,
       ihextr.billtocountrydescription, ihextr.deltocountrydescription,
       ihextr.deltocustvatnumber,
       ihextr.customermarkinggarment, ihextr.taxable, ihextr.siccode, ihextr.invoicecopies,
       ihextr.attachinvoicecopies, ihextr.paymenttermsdescription paymentterms_desc,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       rc.code Adjustment_ReasonCode,
       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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.deltostate,
       country.description PLANTCOUNTRYDESCRIPTION, SS.VALUE WEIGHTUNIT,
       a.roundingamount, A.NEXTPERIODSTARTDATE, A.NEXTPERIODENDDATE, A.NEXTPERIODNOWEEKS,
       ihextr.paymenttype, ihextr.discountdays, ihextr.paymentdiscount, ihextr.discountdays2, ihextr.paymentdiscount2
, dell.invoiceaddress_id, dell.customer_id, dell.debtor_id
       , cast(SS1.VALUE as numeric) WEIGHTDECIMALSMANUALINPUT
--     NOT USED FOR STE layout
--       , (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,
--       (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,
--       , (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
      , route.routenumber route_number, route.description route_desc, route.drivingday_id
      , (Select day_desc.description from day_desc where route.drivingday_id = day_desc.day_id and
             day_desc.language_id = (SELECT C.LANGUAGE_ID FROM CUSTOMER C
             WHERE C.CUSTOMER_ID = A.DELTOCUSTOMER_LINK_ID)) route_day_desc
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 customer dell on dell.customer_id = a.deltocustomer_link_id
        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 route ON (route.route_id = a.route_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)
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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

/
create or replace view V_INVOICEHEADER_STI
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS
, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER
, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE, INTERNALVATNUMBER, VATNUMBER, SETSPECIAL, CLUSTERCODE, DELTOCUSTLANG, ACCEPTGIROLINE, ACCEPTCODELINE, SERVICEEMPLOYEE, KID, TAXRATE, PONUMBER, DELTODISPLAYNAME, SENDINVOICETO, SENDINVOICEBY, FAKTP_YN)
as select a.invoicedate, a.invoiceyear, a.invoiceweek, a.invoicedaynumber,
       a.invoicenumber, a.documenttype, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, CAST(a.billtocustomername AS VARCHAR2(40)) billtocustomername, a.extraname1, a.extraname2,
       a.deltocustomernumber, CAST(a.deltocustomername AS VARCHAR2(40)) 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, CAST(a.emailaddress AS VARCHAR2(40)) emailaddress, a.realcollectiontype, a.originalcollectiontype,
       a.invoicetype, a.exported, a.contractcode, a.purchaseorder,
       a.deliverinstructions, cast(a.invoicecomments as VARCHAR2(60)) 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, CAST(p.email AS VARCHAR(60)) 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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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_7_YEARWEEKS_4RENT(a.invoiceheader_id) as varchar2(55)) 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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,
       A.NEXTPERIODSTARTWEEK, A.NEXTPERIODENDWEEK ,
       ihextr.paymenttype, ihextr.discountdays, ihextr.paymentdiscount, ihextr.discountdays2, ihextr.paymentdiscount2
       , cast(SS1.VALUE as NUMBER) 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
       ,/*cast( */(SELECT pldesc.invoiceremark FROM plantinvoiceremark_desc pldesc
          where pldesc.plant_id = p.plant_id and pldesc.language_id = p.language_id) /*AS VARCHAR2(60)) */ GENERALINV_REMARK_PLANT
       ,/* CAST(*/(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)) /*AS VARCHAR2(60))*/  GENERALINV_REMARK_CUSTOMER
       , p.invoiceremarkstartdate, p.invoiceremarkenddate
       , e.internalvatnumber, e.vatnumber
,  coalesce((select max(pa.packingnote_id) from packingnote pa, packingnoteline pl where pa.packingnote_id=pl.packingnote_id and pl.invoiceheader_id = a.invoiceheader_id and a.invoicefrequency_id = 0 and pa.origin = 5), 0) setspecial --0 is not based on special order, >0 is based on special order
, (select cc.code from customercluster cc where cc.cluster_id = a.cluster_id) clustercode,
       (select languages.code from languages, customer c where a.deltocustomer_link_id = c.customer_id and languages.language_id = C.LANGUAGE_ID) deltocustlang
,cast(ihextr.acceptgiroreference as varchar(60)) acceptgiroline
,cast(ihextr.acceptgirocodeline as varchar(60)) acceptcodeline
,( select emp.name
   from   employee emp
   where  emp.employee_id = ( select btc.serviceemployee_id
                              from   customer btc
                              where  btc.customer_id = ( select cl.customer_id
                                                         from   customer_link cl
                                                         where  cl.customer_link_id = a.billtocustomer_link_id )
                            )
) serviceemployee
, (a.invoicenumber* 10 + F_MOD10DIM(a.invoicenumber, LENGTH(TO_CHAR(a.invoicenumber)))) KID
, (select MAX(TAXRATE) FROM  taxgroup t where t.code = 'MOMS') TAXRATE
,(select max(cpc.purchaseorder) from contractspercustomer cpc
where cpc.customer_id = a.billtocustomer_link_id
and  a.startdate >=  cpc.dateactive and a.enddate <= cpc.dateinactive) PONumber
,cu.name deltoDisplayName
,cu.SENDINVOICETO
,(select cbi.sendinvoiceby from customerbillinginfo cbi where cu.customer_id=cbi.customer_id) sendinvoiceby
,(select count(1) from invoiceline il where il.invoiceheader_id = a.invoiceheader_id and il.invoicelinetype_id = 16
  and il.code = 'FAKTP') faktp_YN
 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),
      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)
        ,customer cu
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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 a.deltocustomer_link_id = cu.customer_id

/
create or replace view V_INVOICEHEADER_VEN
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS
, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE
, INTERNALVATNUMBER, VATNUMBER, SETSPECIAL, CLUSTERCODE, DELTOCUSTLANG)
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, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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 = C.LANGUAGE_ID) GENERALINV_REMARK_CUSTOMER
       , p.invoiceremarkstartdate, p.invoiceremarkenddate
       , e.internalvatnumber, e.vatnumber,
       coalesce((select max(pa.packingnote_id) from packingnote pa, packingnoteline pl where pa.packingnote_id=pl.packingnote_id and pl.invoiceheader_id = a.invoiceheader_id and a.invoicefrequency_id = 0 and pa.origin = 5), 0) setspecial,
       --0 is not based on special order, >0 is based on special order
       (select cc.code from customercluster cc where cc.cluster_id = a.cluster_id) clustercode,
       (select languages.code from languages where languages.language_id = C.LANGUAGE_ID) deltocustlang
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 customer c on (A.DELTOCUSTOMER_LINK_ID = c.customer_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)
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

/
create or replace view V_INVOICEHEADER_WMA
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS
, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE
, PASSERBYCUSTOMER)
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, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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
, pass.passerbycustomer
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 customer pass on pass.customer_id = a.deltocustomer_link_id, --order 501566
      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)
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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

/
create or replace view V_INVOICEHEADER_WMU
 (INVOICEDATE, INVOICEYEAR, INVOICEWEEK, INVOICEDAYNUMBER, INVOICENUMBER, DOCUMENTTYPE, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, ROUTENUMBER, STOPNUMBER, DEPOTCODE, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE
, INVOICETYPE, EXPORTED, CONTRACTCODE, PURCHASEORDER, DELIVERINSTRUCTIONS, INVOICECOMMENTS, TOTALMINUSADJUSTMENT, TOTALPLUSADJUSTMENT, CASHCOLLECTED, PAYTHISAMOUNT, PREBILLAMOUNT, INVOICEFREQUENCYNUMBER, CURRENCYCODE, CURRENCYDESC, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, BILLTO_CITY, BILLTO_STREET, BILLTO_STREET2
, BILLTO_STATE, BILLTO_ZIPCODE, ROUTECONTROL_ID, ADJUSTMENTREASON_ID, SYSTEMUSER_ID, TIMESTAMP, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, TOTALAMOUNTEXCLVAT, DECIMALS, STARTDATE, ENDDATE, BILLTOCOUNTRYDESCRIPTION, DELTOCOUNTRYDESCRIPTION, DELTOCUSTVATNUMBER, CUSTOMERMARKINGGARMENT, TAXABLE, SICCODE, INVOICECOPIES, CUSTDELIVERYSCHEME, CUST_DELIVERY_DAYS, ATTACHINVOICECOPIES, PAYMENTTERMS_DESC, INVOICELAYOUTCODE
, DEFAULT_BU_CODE, NO_OF_SOILTICKETS, ADJUSTMENT_REASONCODE, M_SORT_US_ASC, M_SORT_US_DESC, SPLITUPCODE, SPLITUPDESCRIPTION, PERSONIDENTIFICATION, SIGNATURE, MIN_YEAR_WEEKS, PARENTINVOICEHEADER_ID, CONTRACTSTARTDATE, CONTRACTENDDATE, BANKACCOUNT, 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, PAYMENTDISCOUNTDAYS
, CREDITSQUEEZEPERC, NETPAYMENTDAYS, DELTOSTREET, DELTOSTREET2, DELTOCOUNTY, DELTOCITY, DELTOZIPCODE, DELTOSTATE, PLANTCOUNTRYDESCRIPTION, WEIGHTUNIT, MAX_PERCENTAGE, ROUNDINGAMOUNT, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PAYMENTTYPE, DISCOUNTDAYS, PAYMENTDISCOUNT, DISCOUNTDAYS2, PAYMENTDISCOUNT2, WEIGHTDECIMALSMANUALINPUT, DRIVERNAME, HASSIGNATURE, GENERALINV_REMARK_PLANT, GENERALINV_REMARK_CUSTOMER, INVOICEREMARKSTARTDATE, INVOICEREMARKENDDATE
, INTERNALVATNUMBER, VATNUMBER, GARMENTRENTSPECIFICATION, AMOUNT_CREDIT)
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, a.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,
       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,
       ihextr.formlayoutcode invoicelayoutcode,
       e.code default_BU_code,
       (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,
       rc.code Adjustment_ReasonCode
, 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,
       a.deltostreet, a.deltostreet2, a.deltocounty, a.deltocity, a.deltozipcode, a.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
, (select cus.garmentrentspecification from customer cus where a.deltocustomer_link_id = cus.customer_id) garmentrentspecification
,  (select sum(y.amount-y.totalappliedamount) from artransaction y, artransactiontype z
     where y.billtocustomer_link_id = a.billtocustomer_link_id       --and y.closingtransaction_id is null
       and y.debitcredit = 'C' and y.isopen_yn = 'Y'
       and y.artransactiontype_id = z.artransactiontype_id and z.typenumber <> 2) AMOUNT_CREDIT
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),
      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)
where a.currency_id = b.currency_id
      and a.documenttype = 1
      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

/
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_INVOICEJOURNAL_SMG
 (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,
  coalesce(ihc.TOTALAMOUNTEXCLVAT, A.TOTALAMOUNTEXCLVAT) NETAMOUNT, coalesce(ihc.paythisamount, A.PAYTHISAMOUNT) GROSSAMOUNT,
  coalesce(pcu.CODE, CURR.CODE) CURRENCYCODE, coalesce(pcu.INVOICEAMOUNTDECIMALS, CURR.INVOICEAMOUNTDECIMALS) INVOICEAMOUNTDECIMALS
  , LANGUAGES.CODE LANGUAGECODE, s.systemuser_id
FROM INVOICEHEADER A
	LEFT OUTER JOIN CUSTOMERCLUSTER E ON A.CLUSTER_ID = E.CLUSTER_ID
  left outer join invoiceheadercurrency ihc
       inner join currency pcu on pcu.currency_id = ihc.currency_id
  on ihc.invoiceheader_id = a.invoiceheader_id and ihc.invoicecurrencytype = 2 --Plant Currency
  , 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_INVOICELINE3_SMG
 (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, FMCODE, DELIVEREDAMOUNT, PACKINGNOTELINE_ID, WEIGHT, WEIGHTDECIMALS, PRICE, DISCOUNTPERCENTAGE, CURRENCYCODE, PRICEDECIMALS, INVOICEDECIMALS, PNNOTININVOICE, REMARK, REGUNIT
, LANGUAGECODE, DEP_NUMBER, DEP_DESCRIPTION, FREEOFCHARGEREASON_ID, PRICEFACTOR)
as select 1 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,
           (select prd.code
              from product prd
             where pnl.product_id = prd.product_id)) customcode,
       nvl(pnl.customdescription,
           (select product_desc.description
              from product_desc
             where product_desc.product_id = pnl.product_id
               and product_desc.language_id = languages.language_id)) customdesc,
       (select sz.code
          from sizedefinition sz
         where pnl.sizedefinition_id = sz.sizedefinition_id) sizecode,
         (select fm.code
          from finishingmethod fm
         where pnl.finishingmethod_id = fm.finishingmethod_id) fmcode,
       pnl.deliveredamount,
       pnl.packingnoteline_id,
       0 weight,
       2 weightdecimals,
       (select max(l.price)
             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 = '*'))) price,
       (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 = '*'))) discountpercentage, -- total, to be calculated in the report!
       currency.code currencycode,
       currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals,
       0 pnnotininvoice,
       pn.remark,
       (select ru.code from registrationunit ru where p.registrationunit_id=ru.registrationunit_id) regunit,
       languages.code languagecode,
       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
      from invoiceheader     ih,
       packingnoteline   pnl,
       product p,
       packingnote       pn,
       distributionpoint cons,
       department        dep,
       currency,
       status            statuspn,
       status            statusih,
       businessunit      processbu,
       plant,
       languages
 where ih.invoiceheader_id = pnl.invoiceheader_id
   and ih.documenttype in (1,3)
   and ih.status_id = statusih.status_id
   and statusih.statustype = 'IN'
   and pnl.packingnote_id = pn.packingnote_id
   and pnl.product_id=p.product_id
   and p.typeofmerchandise<> 3
   and pn.status_id = statuspn.status_id
   and statuspn.statustype = 'PN'
   and statuspn.code = '30'
   and pn.distributionpoint_id = cons.distributionpoint_id
   and cons.department_id = dep.department_id
   and ih.currency_id = currency.currency_id
   and pn.processbusinessunit_id = processbu.businessunit_id
   and processbu.plant_id = plant.plant_id
   and pn.showoninvoiceappendix='Y'
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,
       wg.code  customcode,
       ( select wgdesc.description from weighingcategory_desc wgdesc where wgdesc.weighingcategory_id=wg.weighingcategory_id
       and wgdesc.language_id=languages.language_id) customdesc,
       '' sizecode,'' fmcode,
       0 deliveredamount, 0 packingnoteline_id,
      (select sum( pnc.grossweight - pnc.tareweight) from packingnotecontainer ppc
        where ppc.packingnote_id=pn.packingnote_id
        and ppc.weighingcategory_id=wg.weighingcategory_id
        group by wg.weighingcategory_id) weight,
        (case
       when ( wg.weighinguse  =1) then
         ( select ru.decimals  from  registrationunit ru where wg.registrationunit_id=ru.registrationunit_id)
         else  pnc.weightdecimals  end )weightdecimals,
       coalesce((select il.price from invoiceline il, invoicelineproduct ilp
       where ih.invoiceheader_id=il.invoiceheader_id and il.invoiceline_id=ilp.invoiceline_id and
       ilp.weighingcategory_link_id=wg.weighingcategory_id),0) price,
       0 discountpercentage,
       currency.code currencycode, currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals, 0 pnnotininvoice, pn.remark,
       (case
       when ( wg.weighinguse  =1) then
         ( select ru.code  from  registrationunit ru where wg.registrationunit_id=ru.registrationunit_id)
         else
       (select ss.value from systemsetting ss where plant.plant_id = ss.plant_id and ss.name = 'WEIGHTUNIT')end)  regunit,
       languages.code languagecode, dep.departmentnumber dep_number,
       dep.description dep_description, pn.freeofchargereason_id,
       1 pricefactor
from   invoiceheader ih, packingnote pn, packingnotecontainer pnc, distributionpoint cons, department dep,
       currency, status statuspn, status statusih,weighingcategory wg,
       businessunit processbu, plant, languages
where  ih.invoiceheader_id = pnc.invoiceheader_id
and    pnc.packingnote_id = pn.packingnote_id
and    pnc.weighingcategory_id=wg.weighingcategory_id
and    ih.documenttype in (1,3)
and    ih.status_id = statusih.status_id
and    statusih.statustype = 'IN'
and    pn.status_id = statuspn.status_id
and    statuspn.statustype = 'PN'
and    statuspn.code = '30'
and    pn.distributionpoint_id = cons.distributionpoint_id
and    cons.department_id = dep.department_id
and    ih.currency_id = currency.currency_id
and    pn.processbusinessunit_id = processbu.businessunit_id
and    processbu.plant_id = plant.plant_id
and    pn.showoninvoiceappendix='Y'
--and not exists (select 1 from packingnoteline pnl where pnl.packingnote_id = pn.packingnote_id)
union all-- sales items
select 3 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,
           (select prd.code
              from product prd
             where pnl.product_id = prd.product_id)) customcode,
       nvl(pnl.customdescription,
           (select product_desc.description
              from product_desc
             where product_desc.product_id = pnl.product_id
               and product_desc.language_id = languages.language_id)) customdesc,
       (select sz.code
          from sizedefinition sz
         where pnl.sizedefinition_id = sz.sizedefinition_id) sizecode,
         (select fm.code
          from finishingmethod fm
         where pnl.finishingmethod_id = fm.finishingmethod_id) fmcode,
       pnl.deliveredamount,
       pnl.packingnoteline_id,
       (select sum(packingnotecontainer.grossweight -
                   packingnotecontainer.tareweight)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id
         group by pn.packingnote_id) weight,
       (select max(packingnotecontainer.weightdecimals)
          from packingnotecontainer
         where pn.packingnote_id = packingnotecontainer.packingnote_id) weightdecimals,
       (select max(l.price)
             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 = 5
              and (ilp.sizedefinition_link_id = pnl.sizedefinition_id or
                  ilp.sizedefinition_link_id =
                  (select sizedefinition.sizedefinition_id
                      from sizedefinition
                     where sizedefinition.code = '*'))) price,
       0 discountpercentage, -- total, to be calculated in the report!
       currency.code currencycode,
       currency.decimals pricedecimals,
       currency.invoiceamountdecimals invoicedecimals,
       0 pnnotininvoice,
       pn.remark,
        (select ru.code from registrationunit ru where p.registrationunit_id=ru.registrationunit_id)   regunit,
       languages.code languagecode,
       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
  from invoiceheader     ih,
       packingnoteline   pnl,
       product           p,
       packingnote       pn,
       distributionpoint cons,
       department        dep,
       currency,
       status            statuspn,
       status            statusih,
       businessunit      processbu,
       plant,
       languages
 where ih.invoiceheader_id = pnl.invoiceheader_id
   and ih.documenttype in (1,3)
   and ih.status_id = statusih.status_id
   and statusih.statustype = 'IN'
   and pnl.packingnote_id = pn.packingnote_id
   and pnl.product_id=p.product_id
   and p.typeofmerchandise = 3
   and pn.status_id = statuspn.status_id
   and statuspn.statustype = 'PN'
   and statuspn.code = '30'
   and pn.distributionpoint_id = cons.distributionpoint_id
   and cons.department_id = dep.department_id
   and ih.currency_id = currency.currency_id
   and pn.processbusinessunit_id = processbu.businessunit_id
   and processbu.plant_id = plant.plant_id
   and pn.showoninvoiceappendix='Y'

/
create or replace view V_INVOICELINEEXTRA_NAF
 (INVOICEHEADER_ID, INVOICELINE_ID, PRODUCT_LINK_ID, SIZEDEFINITION_LINK_ID, FINISHINGMETHOD_ID, BILLEDQTY, SALESPRICE, INSTRUCTIONS, MODIF_DESC1, MODIF_DESC2, MODIF_DESC3, LANGUAGE_CODE, LANGUAGE_ID, WORKORDERNUMBER, REFERENCENUMBER, ORDERDATE, NEEDEDDATE, TRANSPORTCOSTS, WODISCOUNTPERCENTAGE, EXTERNALREMARK, COMMMETHODDESCR, CONTACTPERSON, SYSTEMUSERUSERNAME, RESPEMPLOYEENAME, COLORDESC, DELIVERYTERMDESCR, SHIPMENTTYPEDESCR, WORKORDERLINE_ID)
as select DISTINCT vi.invoiceheader_id, vi.invoiceline_id,
       vip.product_link_id,
       vip.sizedefinition_link_id,
       vip.finishingmethod_id,
       vi.billedqty,
       gsh.salesprice, --cast(
       wol.instructions --as varchar2(60)) instructions
,(select md.description from workorderlinemodification wlm, modification_desc md where wlm.workorderline_id = gsh.workorderline_id
 and wlm.modification_id = md.modification_id and md.language_id = lan.language_id and wlm.sequencenumber = 1) Modif_desc1,
(select md.description from workorderlinemodification wlm, modification_desc md where wlm.workorderline_id = gsh.workorderline_id
 and wlm.modification_id = md.modification_id and md.language_id = lan.language_id and wlm.sequencenumber = 2) Modif_desc2,
(select md.description from workorderlinemodification wlm, modification_desc md where wlm.workorderline_id = gsh.workorderline_id
 and wlm.modification_id = md.modification_id and md.language_id = lan.language_id and wlm.sequencenumber = 3) Modif_desc3,
 lan.code language_code, lan.language_id
, wk.workordernumber,
coalesce((select castnumberasvarchar(wkCredit.Workordernumber) from workorder wkCredit where wk.creditworkorder_id = wkCredit.Workorder_Id)
                 , wk.referencenumber) referencenumber
, wk.requestdate orderDate, wk.neededdate, wk.transportcosts
, wk.discountpercentage WODiscountPercentage, cast(
wk.externalremark as varchar2(600)) externalremark
,(select cmdesc.description from communicationmethod_desc cmdesc where cmdesc.communicationmethod_id = wk.communicationmethod_id
                                                                      and cmdesc.language_id = lan.language_id) CommMethodDescr,
(select cp.name from contactperson cp where cp.contactperson_id = wk.contactperson_id) ContactPerson,
(select su.username from systemuser su where wk.creationuser_id=su.systemuser_id) systemuserusername,
(select e.name from employee e where e.employee_id = wk.resplaundryemployee_id) RespEmployeeName,
(select cd.description from color_desc cd, product pr where cd.color_id = pr.color_id
  and pr.product_id = vip.product_link_id and cd.language_id = lan.language_id) colorDesc,
(select dtdesc.description from deliveryterm_desc dtdesc where dtdesc.deliveryterm_id = wk.deliveryterm_id
                                                                      and dtdesc.language_id = lan.language_id) DeliveryTermDescr,
(select shiptdesc.description from shipmenttype_desc shiptdesc where shiptdesc.shipmenttype_id = wk.shipmenttype_id
                                                                      and shiptdesc.language_id = lan.language_id) ShipmentTypeDescr
, (select min(wl.workorderline_id) from workorderline wl where wl.workorder_id = wk.workorder_id and wl.product_link_id = wol.product_link_id) workorderline_id
from invoiceline vi, invoicelineproduct vip, garmentsaleshistory gsh, workorderline wol, workorder wk, LANGUAGES lan
where vip.invoiceline_id = vi.invoiceline_id
   and gsh.invoiceheader_id = vi.invoiceheader_id
   and gsh.product_link_id = vip.product_link_id
   and gsh.sizedefinition_link_id = vip.sizedefinition_link_id
   and wol.workorderline_id = gsh.workorderline_id
   and wol.product_link_id = vip.product_link_id
   and wol.sizedefinition_link_id = vip.sizedefinition_link_id
   and wol.finishingmethod_id = vip.finishingmethod_id
   and vi.invoicelinetype_id = 5
   and vi.invoicelinesubtype in (17, 18)
   and wol.workorder_id = wk.workorder_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_AMM
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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, DELIVERYSCHEMECODE, DELIVERYSCHEMEDESC, TYPEOFMERCHANDISE)
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.adjustmentpermited, 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.Code FROM PRODUCT_LINK pd WHERE pd.product_link_id = b.product_link_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
, b.deliveryschemecode
, (select dsd.description
   from   deliveryscheme_desc dsd
   where  dsd.language_id = LANGUAGES.LANGUAGE_ID and
          dsd.deliveryscheme_id = (select ds.deliveryscheme_id
                                   from   deliveryscheme ds
                                   where  ds.code = b.deliveryschemecode)
   ) DELIVERYSCHEMEDESC
, (SELECT pr.typeofmerchandise FROM PRODUCT pr WHERE pr.product_id = b.product_link_id ) typeofmerchandise
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_INVOICELINE_AUJ
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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, DELIVERYSCHEMECODE, TYPEOFMERCHANDISE)
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.adjustmentpermited,
       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
         where pilt.plant_id =bu.plant_id
           and pilt.invoicelinetype_id = a.invoicelinetype_id) InvoiceLine_SequenceNumber,
       (SELECT pilt.suppressprinting
          from plantinvoicelinetype pilt
         where pilt.plant_id =bu.plant_id
           and pilt.invoicelinetype_id = a.invoicelinetype_id) supressprinting --502161
, b.adjustmentdeliveredqty, b.pricefactor
, coalesce(b.deliveryschemecode, (select min(ds.code) from customerdeliveryscheme cds, deliveryscheme ds
where cds.customer_id = f.deltocustomer_link_id and cds.deliveryscheme_id = ds.deliveryscheme_id)) deliveryschemecode,
coalesce((SELECT pr.typeofmerchandise FROM PRODUCT pr
         WHERE pr.product_id = b.product_link_id), 0) typeofmerchandise
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, businessunit bu,
LANGUAGES
where a.invoicelinetype_id = e.invoicelinetype_id
   and a.invoiceheader_id = f.invoiceheader_id
   and f.invoicebusinessunit_id = bu.businessunit_id
   and f.documenttype = 1

/
create or replace view V_INVOICELINE_BDE
 (INVOICEDATE, INVOICENUMBER, PARENTINVOICEHEADER_ID, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, STARTWEEK, ENDWEEK, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PRICEFACTOR, FREQUENCY, MIN_WEEK, MIN_YEAR, MAX_WEEK, MAX_YEAR, CRI_WEEK, CRI_YEAR, CRI_QUANTITY, WEEKSDIFFERENCE, ILSUBTYPEDESC)
as select f.invoicedate, f.invoicenumber, f.parentinvoiceheader_id, a.linenumber,
/*(CASE WHEN e.TYPE = 1 AND a.invoicelinesubtype = 8
      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.adjustmentpermited, 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, b.adjustmentdeliveredqty
, F.NEXTPERIODSTARTWEEK, F.NEXTPERIODENDWEEK, F.STARTWEEK, F.ENDWEEK
, F.NEXTPERIODSTARTDATE, F.NEXTPERIODENDDATE, F.NEXTPERIODNOWEEKS
, b.pricefactor
--, (select dsc.frequency from deliveryscheme dsc, productlistpercustomer plpc where b.deliveryschemecode = dsc.code) Frequency
, (case
  when a.invoicelinetype_id = 1 and a.invoicelinesubtype in (0, 7, 8)--e.type = 1 and a.invoicelinesubtype = 0
  then FGET_BDE_FRECV(f.deltocustomer_link_id, b.product_link_id, b.sizedefinition_link_id, b.finishingmethod_id, f.invoicedate, b.deliveryschemecode)
  else -1
  end ) Frequency
--, (select min(cr.week) from costreportinfo cr
--where cr.invoiceline_id = a.invoiceline_id and cr.year in (select min(cri.year) from costreportinfo cri where cri.invoiceline_id = a.invoiceline_id))
, -1 Min_week
, -1 Min_year
--, (select max(cr.week) from costreportinfo cr
--where cr.invoiceline_id = a.invoiceline_id and cr.year in (select max(cri.year) from costreportinfo cri where cri.invoiceline_id = a.invoiceline_id))
, -1 Max_week
, -1 Max_year
, g.WEEK CRI_week
, g.YEAR CRI_year
, g.QUANTITY CRI_quantity
, -1 WeeksDifference--,
  --(select count (il.invoiceline_id) from invoiceline il, invoiceheader ih
    --   where ih.parentinvoiceheader_id<> ih.invoiceheader_id and il.invoiceheader_id=ih.invoiceheader_id
           --  and il.invoicelinesubtype=8) aaa
  , (select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = e.invoicelinetype_id and iltd.language_id = languages.language_id) ilsubtypedesc
from invoiceheader f, 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)
LEFT OUTER JOIN costreportinfo g ON (a.invoiceline_id = g.invoiceline_id),
invoicelinetype e, LANGUAGES
where a.invoicelinetype_id = e.invoicelinetype_id
and a.invoiceheader_id = f.invoiceheader_id
and f.documenttype = 1
and f.nextperiodstartdate is null
union all
select f.invoicedate, f.invoicenumber, f.parentinvoiceheader_id, a.linenumber,
/*(CASE WHEN e.TYPE = 1 AND a.invoicelinesubtype = 8
      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.adjustmentpermited, 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, b.adjustmentdeliveredqty
, F.NEXTPERIODSTARTWEEK, F.NEXTPERIODENDWEEK, F.STARTWEEK, F.ENDWEEK
, F.NEXTPERIODSTARTDATE, F.NEXTPERIODENDDATE, F.NEXTPERIODNOWEEKS
, b.pricefactor
--, (select dsc.frequency from deliveryscheme dsc, productlistpercustomer plpc where b.deliveryschemecode = dsc.code) Frequency
, (case
  when a.invoicelinetype_id = 1 and a.invoicelinesubtype in (0, 7, 8)--e.type = 1 and a.invoicelinesubtype = 0
  then FGET_BDE_FRECV(f.deltocustomer_link_id, b.product_link_id, b.sizedefinition_link_id, b.finishingmethod_id, f.invoicedate, b.deliveryschemecode)
  else -1
  end ) Frequency
, (select min(cr.week)
from costreportinfo cr
where cr.invoiceline_id = a.invoiceline_id and cr.year in (select min(cri.year) from costreportinfo cri where cri.invoiceline_id = a.invoiceline_id)) Min_week
, (select min(cri.year) from costreportinfo cri where cri.invoiceline_id = a.invoiceline_id) Min_year
, (select max(cr.week)--,
--(select count (il.invoiceline_id) from invoiceline il, invoiceheader ih
    --   where ih.parentinvoiceheader_id<> ih.invoiceheader_id and il.invoiceheader_id=ih.invoiceheader_id
          --   and il.invoicelinesubtype=8) aaa
from costreportinfo cr
where cr.invoiceline_id = a.invoiceline_id and cr.year in (select max(cri.year) from costreportinfo cri where cri.invoiceline_id = a.invoiceline_id)) Max_week
, (select max(cri.year) from costreportinfo cri where cri.invoiceline_id = a.invoiceline_id) Max_year
, -1 CRI_week
, -1 CRI_year
, -1 CRI_quantity
, GETWEEKSDIFFERENCE_BDE((select min(cri.year) from costreportinfo cri where cri.invoiceline_id = a.invoiceline_id)
  , (select min(cr.week) from costreportinfo cr where cr.invoiceline_id = a.invoiceline_id and cr.year in (select min(cri.year) from costreportinfo cri where cri.invoiceline_id = a.invoiceline_id))
  , (select max(cri.year) from costreportinfo cri where cri.invoiceline_id = a.invoiceline_id)
  , (select max(cr.week) from costreportinfo cr where cr.invoiceline_id = a.invoiceline_id and cr.year in (select max(cri.year) from costreportinfo cri where cri.invoiceline_id = a.invoiceline_id))) WeeksDifference
  , (select iltd.description from invoicelinetype_desc iltd where iltd.invoicelinetype_id = e.invoicelinetype_id and iltd.language_id = languages.language_id) ilsubtypedesc
from invoiceheader f, 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, LANGUAGES
where a.invoicelinetype_id = e.invoicelinetype_id
and a.invoiceheader_id = f.invoiceheader_id
and f.documenttype = 1
and f.nextperiodstartdate is not null

/
create or replace view V_INVOICELINE_BNL
 (INVOICEDATE, INVOICENUMBER, PARENTINVOICEHEADER_ID, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, STARTWEEK, ENDWEEK, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PRICEFACTOR)
as select f.invoicedate, f.invoicenumber, f.parentinvoiceheader_id, a.linenumber,
(CASE WHEN e.TYPE = 1 AND a.invoicelinesubtype = 8
      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
, case when e.type = 6 then (select ilstd.description from invoicelinesubtype ilst, invoicelinesubtype_desc ilstd where ilst.invoicelinetype_id = e.invoicelinetype_id
            and ilst.subtype=a.invoicelinesubtype and ilstd.invoicelinesubtype_id = ilst.invoicelinesubtype_id and ilstd.language_id = languages.language_id)
       else a.description end description,
a.adjustedamount, a.adjustedprice, a.adjustmentbilledqty, a.extend, a.amount, a.discountpercentage,
a.price, a.billedqty, a.adjustmentpermited, 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, b.adjustmentdeliveredqty
, F.NEXTPERIODSTARTWEEK, F.NEXTPERIODENDWEEK, F.STARTWEEK, F.ENDWEEK
, F.NEXTPERIODSTARTDATE, F.NEXTPERIODENDDATE, F.NEXTPERIODNOWEEKS
, b.pricefactor
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_INVOICELINE_CCG
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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.adjustmentpermited, 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_INVOICELINE_CSC
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, TAXGROUPCODE, TAXTYPE, SUBJECTTOMINIMUM, TURNOVERGROUPCODE, TURNOVERGROUPDESCRIPTION, INVOICELINESUBTYPE, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PRODUCTSHORTDESCRIPTION, 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
, DELSCHEMEFREQ, CHGPERWEEK)
as select f.invoicedate
,      f.invoicenumber
,      a.linenumber
,      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
,      a.description
,      a.adjustedamount
,      a.adjustedprice
,      a.adjustmentbilledqty
,      a.extend
,      a.amount
,      a.discountpercentage
,      a.price
,      a.billedqty
,      a.adjustmentpermited
,      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
,      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
,      b.adjustmentdeliveredqty
,      ( select ds.frequency
         from   deliveryscheme ds
         where  b.deliveryschemecode = ds.code) delschemefreq
,      ( select wi.changesperweek
         from   weareremployment we
                  left outer join wearerinventory wi
                  on (wi.weareremployment_id = we.weareremployment_id)
         where  we.weareremployment_id = b.weareremployment_link_id
           and  wi.product_id = b.product_link_id
           and  wi.sizedefinition_id = b.sizedefinition_link_id
           and  wi.finishingmethod_id = b.finishingmethod_id ) chgperweek
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_INVOICELINE_CUS
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, TAXGROUPCODE, TAXTYPE, SUBJECTTOMINIMUM, TURNOVERGROUPCODE, TURNOVERGROUPDESCRIPTION, INVOICELINESUBTYPE, INVLINESUBTYPE_DESC, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PRODUCTSHORTDESCRIPTION, PRODUCTTOM, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODCODE
, FINISHINGMETHODDESCRIPTION, INVOICEQTYCOLUMN, INVENTORYQTY, DELIVEREDQTY, ABUSEDQUANTITY, SOILQUANTITY, SOILCOUNTMETHOD, BILLINGMETHOD, WEARERNUMBER, WEARERNAME, WEARERADMINNR, WEARERBANK, WEARERLOCKER, SPECIALSIZEGROUPPRICE, WEARERREMARK, WEARERINVSTARTDATE, WEARERDEPT, WEARERDEPT_DESC, WEARERCONSPOINT, WEARERCONSPOINT_DESC, TRANSACTIONTYPE, TRANSACTIONDATE, PERCENTAGE, SYSTEMUSER_ID, TIMESTAMP, INVOICELINE_ID, REMARK, LANGUAGECODE, INVOICEHEADER_ID, OVERAMOUNT
, REPLACEMENTPRICE, PRODUCTDESCRIPTION, REGISTRATIONUNITDESCRIPTION, ADJUSTMENTREASON_CODE, INVOICELINE_SEQUENCENUMBER, SUPRESSPRINTING, ADJUSTMENTDELIVEREDQTY, DELSCHEMEFREQ)
as select f.invoicedate, f.invoicenumber, a.linenumber,
--(CASE WHEN e.TYPE = 1 AND a.invoicelinesubftype = 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.adjustmentpermited, 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,
(SELECT z.DESCRIPTION
 FROM invoicelinesubtype_DESC z , invoicelinesubtype ilsb
 WHERE z.invoicelinesubtype_id  = ilsb.invoicelinesubtype_id
       AND ilsb.invoicelinetype_id = e.invoicelinetype_id
       and a.invoicelinesubtype = ilsb.subtype
       AND z.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) invlinesubtype_desc,
b.productgroupcode, b.productgroupdescription,
b.productshortdescription,
--, cast(FSGET_CODE(f.invoicenumber, a.linenumber) as varchar2(255)) shortdescription
(select prd.typeofmerchandise
 from product prd
 where b.product_link_id = prd.product_id) producttom,
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, b.specialsizegroupprice,
(select w.remark from wearer w where w.customer_id = f.deltocustomer_link_id and w.wearernumber = b.wearernumber) wearerremark,
(select w.dateactive from wearer w where w.customer_id = f.deltocustomer_link_id and w.wearernumber = b.wearernumber) wearerinvstartdate,
 (select depl.departmentnumber
  from weareremployment we, distributionpoint_link dp, department_link depl
  where b.weareremployment_link_id = we.weareremployment_id
        and we.distributionpoint_id = dp.distributionpoint_id
        and dp.department_link_id = depl.department_link_id) wearerdept,
 (select depl.description
  from weareremployment we, distributionpoint_link dp, department_link depl
  where b.weareremployment_link_id = we.weareremployment_id
        and we.distributionpoint_id = dp.distributionpoint_id
        and dp.department_link_id = depl.department_link_id) wearerdept_desc,
 (select dp.distributionpointnumber
  from weareremployment we, distributionpoint_link dp
  where b.weareremployment_link_id = we.weareremployment_id
        and we.distributionpoint_id = dp.distributionpoint_id) wearerconspoint,
 (select dp.description
  from weareremployment we, distributionpoint_link dp
  where b.weareremployment_link_id = we.weareremployment_id
        and we.distributionpoint_id = dp.distributionpoint_id) wearerconspoint_desc,
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
   where pilt.plant_id = bu.plant_id and pilt.invoicelinetype_id = a.invoicelinetype_id) InvoiceLine_SequenceNumber,
 coalesce(( SELECT case when (coalesce(pilt.suppressprinting, 3) = 3) then e.supressprinting
          else pilt.suppressprinting end suppressprinting
         from plantinvoicelinetype pilt
         where pilt.plant_id = bu.plant_id and pilt.invoicelinetype_id = a.invoicelinetype_id), e.supressprinting) supressprinting
, b.adjustmentdeliveredqty
, coalesce((select ds.code from deliveryscheme ds where b.deliveryschemecode = ds.code)
, (select max(ds.code)
from standarddeliveryline sdl, productlistpercustomer plpc, deliveryscheme ds
where sdl.productlistpercustomer_id = plpc.productlistpercustomer_id
      and plpc.customer_id = f.deltocustomer_link_id
      and plpc.product_id = b.product_link_id
      and plpc.sizedefinition_id = b.sizedefinition_link_id
      and plpc.finishingmethod_id = b.finishingmethod_id
      and sdl.deliveryscheme_id = ds.deliveryscheme_id)) DelSchemeFreq
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, businessunit bu, LANGUAGES
where a.invoicelinetype_id = e.invoicelinetype_id
and a.invoiceheader_id = f.invoiceheader_id
and f.invoicebusinessunit_id = bu.businessunit_id
and f.documenttype in (1, 8)

/
create or replace view V_INVOICELINE_CVL
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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, CC_YEAR, CC_WEEK, CC_QUANTITY)
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.adjustmentpermited, 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,
( 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
, cc.year CC_YEAR
, cc.week CC_WEEK
, cc.quantity CC_QUANTITY
from invoiceline a
LEFT OUTER JOIN costreportinfo cc ON (a.invoiceline_id = cc.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)
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_INVOICELINE_FIS
 (INVOICEHEADER_ID, INVOICELINETYPE, INVOICELINETYPE_ID, INVOICELINESUBTYPE, SUPRESSPRINTING, INVOICELINETYPEDESC, LINENUMBER, ITEM, INCR, DECR, CF, DEL, STOCK, QTY, PRICE, AMOUNT, PERCENTAGE, OVERAMOUNT, PRODUCT_CODE, FINISHINGMETHODCODE, INVOICEQTYCOLUMN, BILLINGMETHOD)
as select /*+use_nl(h l) use_nl(l lp) index_rs(lp XPKINVOICELINEPRODUCT)
         use_nl(l v) index_rs(v XPKINVOICELINEVARIOUS)*/
       h.invoiceheader_id,
       coalesce(min((select min(pil.sequencenumber)
                     from   plantinvoicelinetype pil, businessunit bu
                     where  pil.invoicelinetype_id = l.invoicelinetype_id
                     and    bu.businessunit_id = h.invoicebusinessunit_id
                     and    pil.plant_id = bu.plant_id)), l.invoicelinetype_id) invoicelinetype,
       l.invoicelinetype_id, -1 invoicelinesubtype, 2 supressprinting,
       (select max(iltd.description)
         from   invoicelinetype_desc iltd,  customer bill
         where  bill.language_id = iltd.language_id
         and    bill.customer_id = h.billtocustomer_link_id
         and    iltd.invoicelinetype_id = l.invoicelinetype_id) invoicelinetypedesc,
       min(l.linenumber) linenumber, l.description item,
       case
         when h.splitupcode is not null then
          nvl((select sum(q.quantity)
              from   rentalqtyadjustment q, productlistperdistribpoint plpd, distributionpoint dp,
                     department t, costcenter cc
              where  q.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
              and    plpd.distributionpoint_id = dp.distributionpoint_id
              and    dp.department_id = t.department_id
              and    t.customer_id = h.deltocustomer_link_id
              and    lp.product_link_id = plpd.product_id
              and    lp.sizedefinition_link_id = plpd.sizedefinition_id
              and    lp.finishingmethod_id = plpd.finishingmethod_id
              and    q.adjustmentdate >= h.startdate
              and    q.adjustmentdate <= h.enddate
              and    dp.costcenter_id = cc.costcenter_id
              and    h.splitupcode = cc.code
              and    q.quantity > 0), 0)
         else
          nvl((select sum(q.quantity)
              from   rentalqtyadjustment q, productlistperdistribpoint plpd, distributionpoint dp,
                     department t
              where  q.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
              and    plpd.distributionpoint_id = dp.distributionpoint_id
              and    dp.department_id = t.department_id
              and    t.customer_id = h.deltocustomer_link_id
              and    lp.product_link_id = plpd.product_id
              and    lp.sizedefinition_link_id = plpd.sizedefinition_id
              and    lp.finishingmethod_id = plpd.finishingmethod_id
              and    q.adjustmentdate >= h.startdate
              and    q.adjustmentdate <= h.enddate
              and    q.quantity > 0), 0)
       end incr,
       case
         when h.splitupcode is not null then
          nvl((select sum(q.quantity)
              from   rentalqtyadjustment q, productlistperdistribpoint plpd, distributionpoint dp,
                     department t, costcenter cc
              where  q.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
              and    plpd.distributionpoint_id = dp.distributionpoint_id
              and    dp.department_id = t.department_id
              and    t.customer_id = h.deltocustomer_link_id
              and    lp.product_link_id = plpd.product_id
              and    lp.sizedefinition_link_id = plpd.sizedefinition_id
              and    lp.finishingmethod_id = plpd.finishingmethod_id
              and    q.adjustmentdate >= h.startdate
              and    q.adjustmentdate <= h.enddate
              and    dp.costcenter_id = cc.costcenter_id
              and    cc.code = h.splitupcode
              and    q.quantity < 0), 0)
         else
          nvl((select sum(q.quantity)
              from   rentalqtyadjustment q, productlistperdistribpoint plpd, distributionpoint dp,
                     department t
              where  q.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
              and    plpd.distributionpoint_id = dp.distributionpoint_id
              and    dp.department_id = t.department_id
              and    t.customer_id = h.deltocustomer_link_id
              and    lp.product_link_id = plpd.product_id
              and    lp.sizedefinition_link_id = plpd.sizedefinition_id
              and    lp.finishingmethod_id = plpd.finishingmethod_id
              and    q.adjustmentdate >= h.startdate
              and    q.adjustmentdate <= h.enddate
              and    q.quantity < 0), 0)
       end decr,
       case
         when l.invoicelinetype_id = 1 then
          max(lp.inventoryqty)
         else
          case
            when h.splitupcode is not null then
             nvl((select sum(q.quantity)
                 from   rentalqtyadjustment q, productlistperdistribpoint plpd, distributionpoint dp,
                        department t, costcenter cc
                 where  q.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
                 and    plpd.distributionpoint_id = dp.distributionpoint_id
                 and    dp.department_id = t.department_id
                 and    t.customer_id = h.deltocustomer_link_id
                 and    lp.product_link_id = plpd.product_id
                 and    lp.sizedefinition_link_id = plpd.sizedefinition_id
                 and    lp.finishingmethod_id = plpd.finishingmethod_id --         and    q.adjustmentdate >= h.startdate
                 and    q.adjustmentdate <= h.enddate
                 and    dp.costcenter_id = cc.costcenter_id
                 and    cc.code = h.splitupcode), 0)
            else
             nvl((select sum(q.quantity)
                 from   rentalqtyadjustment q, productlistperdistribpoint plpd, distributionpoint dp,
                        department t
                 where  q.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
                 and    plpd.distributionpoint_id = dp.distributionpoint_id
                 and    dp.department_id = t.department_id
                 and    t.customer_id = h.deltocustomer_link_id
                 and    lp.product_link_id = plpd.product_id
                 and    lp.sizedefinition_link_id = plpd.sizedefinition_id
                 and    lp.finishingmethod_id = plpd.finishingmethod_id --         and    q.adjustmentdate >= h.startdate
                 and    q.adjustmentdate <= h.enddate), 0)
          end
       end cf, max(lp.deliveredqty) del, max(lp.minimumquantity) stock, sum(l.billedqty) qty,
       l.price, sum(l.amount) amount, nvl(v.percentage, -1) percentage,
       nvl(v.overamount, -1) overamount,
       (select pr.code from product pr where lp.product_link_id = pr.product_id) product_code,
       (select fm.code from finishingmethod fm where lp.finishingmethod_id = fm.finishingmethod_id) finishingmethodcode,
       max(lp.invoiceqtycolumn) invoiceqtycolumn, max(lp.billingmethod) billingmethod
from   invoiceheader h, invoiceline l
       left outer join invoicelineproduct lp on lp.invoiceline_id = l.invoiceline_id
       left outer join invoicelinevarious v on v.invoiceline_id = l.invoiceline_id
where  h.invoiceheader_id = l.invoiceheader_id
group  by h.invoiceheader_id, l.invoicelinetype_id, h.splitupcode, h.startdate, h.enddate,
          h.deltocustomer_link_id, lp.product_link_id, lp.sizedefinition_link_id,
          lp.finishingmethod_id, h.billtocustomer_link_id, h.invoicebusinessunit_id,
          v.percentage, v.overamount, l.description, l.price

/
create or replace view V_INVOICELINE_HUE
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, TAXGROUPCODE, TAXTYPE, SUBJECTTOMINIMUM, TURNOVERGROUPCODE, TURNOVERGROUPDESCRIPTION, INVOICELINESUBTYPE, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PRODUCTSHORTDESCRIPTION, 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
)
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.adjustmentpermited, 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, b.adjustmentdeliveredqty
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_INVOICELINE_LAV
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, TAXGROUPCODE, TAXTYPE, SUBJECTTOMINIMUM, TURNOVERGROUPCODE, INVOICELINESUBTYPE, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PRODUCTSHORTDESCRIPTION, 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, INVOICELINE_SEQUENCENUMBER, SUPRESSPRINTING)
as select f.invoicedate, f.invoicenumber, a.linenumber,
(CASE WHEN e.TYPE = 1 AND a.invoicelinesubtype = 6
      THEN 1.5
	    ELSE e.TYPE
END)  invoicelinetype,
(CASE WHEN e.TYPE = 1 AND a.invoicelinesubtype = 6
      THEN  'Grundgebühr'
	    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, a.description,
    a.adjustedamount, a.adjustedprice, a.adjustmentbilledqty, a.extend, a.amount, a.discountpercentage,
    a.price, a.billedqty, a.adjustmentpermited, a.taxgroupcode, a.taxtype, a.subjecttominimum, d.code turnovergroupcode,
    a.invoicelinesubtype, b.productgroupcode, b.productgroupdescription,
    b.productshortdescription,
    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 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_INVOICELINE_LTB
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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, PRODUCTCUSTOMCODE, PRODUCTCODE)
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.adjustmentpermited,
       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
         where pilt.plant_id =bu.plant_id
           and pilt.invoicelinetype_id = a.invoicelinetype_id) InvoiceLine_SequenceNumber,
case (SELECT pilt.suppressprinting
         from plantinvoicelinetype pilt
         where bu.plant_id = pilt.plant_id
               and pilt.invoicelinetype_id = a.invoicelinetype_id)
  when 0 then 0
  when 1 then 1
  when 2 then 2
  else e.supressprinting
end supressprinting, --502161
       b.adjustmentdeliveredqty,
       b.pricefactor
, ( select plpc.customcode
    from   productlistpercustomer plpc
    where  plpc.product_id=b.product_link_id
       and plpc.sizedefinition_id=b.sizedefinition_link_id
       and plpc.finishingmethod_id=b.finishingmethod_id
       and plpc.customer_id=coalesce(f.deltocustomer_link_id,f.billtocustomer_link_id)
       and plpc.dateactive <= f.invoicedate and plpc.dateinactive > f.invoicedate
  ) productcustomcode
, ( select pr.code
    from   productlistpercustomer plpc
	,      product pr
    where  plpc.product_id=pr.product_id
       and plpc.product_id=b.product_link_id
       and plpc.sizedefinition_id=b.sizedefinition_link_id
       and plpc.finishingmethod_id=b.finishingmethod_id
       and plpc.customer_id=coalesce(f.deltocustomer_link_id,f.billtocustomer_link_id)
       and plpc.dateactive <= f.invoicedate and plpc.dateinactive > f.invoicedate
   ) productcode
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, businessunit bu,
 LANGUAGES
where a.invoicelinetype_id = e.invoicelinetype_id
   and a.invoiceheader_id = f.invoiceheader_id
   and f.invoicebusinessunit_id = bu.businessunit_id
   and f.documenttype = 1

/
create or replace view V_INVOICELINE_LTS
 (INVOICEDATE, INVOICENUMBER, PARENTINVOICEHEADER_ID, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, TAXGROUPCODE, TAXTYPE, SUBJECTTOMINIMUM, TURNOVERGROUPCODE, TURNOVERGROUPDESCRIPTION, INVOICELINESUBTYPE, INVLINESUBTYPEDESC, 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, ADJUSTMENTREASON_CODE, INVOICELINE_SEQUENCENUMBER
, SUPRESSPRINTING, ADJUSTMENTDELIVEREDQTY, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, STARTWEEK, ENDWEEK, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PRICEFACTOR, ACTIVITYDESC, ACTIVITYCODE, REGUNIT, REGISTRATIONUNITDESCRIPTION, TAXRATE, ACTIVITYREFERENCE, INVENTORYCATEGORYCODE, INVENTORYCATEGDESCR, CLIENTINV_CAPPEDAMOUNT, CLIENTCUSTINV_CAPPEDAMOUNT, CUST_CAPPEDAMOUNT, CUST_INSURANCENUMBER, ILCLIENT_CODE, ILCLIENT_DESCRIPTION, ILCLIENT_AMOUNT
, CLIENT_INVOICENUMBER, TOTALCAPPEDAMNT, ILCLIENT_TOTALCAPPEDAMNT)
as select f.invoicedate,
       f.invoicenumber,
       f.parentinvoiceheader_id,
       a.linenumber,
       (CASE
         WHEN e.TYPE = 1 AND a.invoicelinesubtype = 8 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.adjustmentpermited,
       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,
			 coalesce((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),
			          (select ils.factorydescription
			          from invoicelinesubtype ils
			          where ils.invoicelinetype_id = a.invoicelinetype_id
			          and ils.subtype = a.invoicelinesubtype)) invlinesubtypedesc,
			 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 rc.code
          FROM reasoncode rc
         WHERE rc.reasoncode_id = a.adjustmentreason_id) ADJUSTMENTREASON_CODE,
       (SELECT pilt.sequencenumber
          from plantinvoicelinetype pilt, businessunit bu
         where f.invoicebusinessunit_id = bu.businessunit_id
           and bu.plant_id = pilt.plant_id
           and pilt.invoicelinetype_id = a.invoicelinetype_id) InvoiceLine_SequenceNumber,
       e.supressprinting,
       b.adjustmentdeliveredqty,
       F.NEXTPERIODSTARTWEEK,
       F.NEXTPERIODENDWEEK,
       F.STARTWEEK,
       F.ENDWEEK,
       F.NEXTPERIODSTARTDATE,
       F.NEXTPERIODENDDATE,
       F.NEXTPERIODNOWEEKS,
       b.pricefactor,
       case
         when e.type in (6, 12, 23, 27, 28) then
          (select ad.description
             from activity_desc ad, activity ac
            where ac.code = '009'
              and ac.activity_id = ad.activity_id
              and ad.language_id = languages.language_id)
         when e.type in (7, 8, 9, 10, 11, 19, 20, 22, 24, 25) then
          (select ad.description
             from activity_desc ad, activity ac
            where ac.code = '008'
              and ac.activity_id = ad.activity_id
              and ad.language_id = languages.language_id)
         when e.type =15 then
          (select ad.description
             from activity_desc ad, activity ac
            where ac.code = '011'
              and ac.activity_id = ad.activity_id
              and ad.language_id = languages.language_id)
         else
          (select ad.description
             from activity_desc ad, productgroup pg
            where b.productgroupcode = pg.code
              and ad.activity_id = pg.activity_id
              and ad.language_id = languages.language_id)
       end ActivityDesc,
       case
         when e.type in (6, 12, 23, 27, 28) then
          '009'
         when e.type in (7, 8, 9, 10, 11, 19, 20, 22, 24, 25) then
          '008'
         when e.type =15 then
          '011'
         else
          (select ac.code
             from activity ac, productgroup pg
            where b.productgroupcode = pg.code
              and ac.activity_id = pg.activity_id)
       end ActivityCode,
       (select ru.code
          from product pr, registrationunit ru
         where b.product_link_id = pr.product_id
           and pr.registrationunit_id = ru.registrationunit_id) regunit,
       (select rud.description
          from product pr, registrationunit_desc rud
         where b.product_link_id = pr.product_id
           and pr.registrationunit_id = rud.registrationunit_id
           and rud.language_id = languages.language_id) REGISTRATIONUNITDESCRIPTION,
       /*(select tg.taxrate
          from productgrouptax pgt, taxgroup tg, product p, customer bill
         where p.productgroup_id = pgt.productgroup_id
           and pgt.taxgroup_id = tg.taxgroup_id
           and b.product_link_id = p.product_id
           and f.billtocustomer_link_id = bill.customer_id
           and pgt.country_id = bill.country_id) taxrate,*/
        (select case when f.invoicedate < tg.startdatetaxrate then tg.oldtaxrate
               else tg.taxrate
               end taxrate
         from taxgroup tg, customer bill
         where a.taxgroupcode = tg.code
               and bill.customer_id = f.billtocustomer_link_id
               and tg.country_id = bill.country_id) taxrate,
        case
         when e.type in (6, 12, 23, 27, 28) then
          (select ca.activityreference
             from customeractivities ca, activity ac
            where ac.code = '009'
              and ac.activity_id = ca.activity_id
              and ca.customer_id = f.deltocustomer_link_id
              and ca.separateinvoice = 'Y'
              and ca.processbusinessunit_id = a.processingbusinessunit_id)
         when e.type in (7, 8, 9, 10, 11, 19, 20, 22, 24, 25) then
          (select ca.activityreference
             from customeractivities ca, activity ac
            where ac.code = '008'
              and ac.activity_id = ca.activity_id
              and ca.customer_id = f.deltocustomer_link_id
              and ca.separateinvoice = 'Y'
              and ca.processbusinessunit_id = a.processingbusinessunit_id)
         else
          (select ca.activityreference
             from customeractivities ca, productgroup pg
            where pg.activity_id = ca.activity_id
              and ca.customer_id = f.deltocustomer_link_id
              and ca.separateinvoice = 'Y'
              and b.productgroupcode = pg.code
              and ca.processbusinessunit_id = a.processingbusinessunit_id)
       end activityreference,
       a.inventorycategorycode,
       coalesce((select ic.description from inventorycategory ic where ic.inventorycategory_id = a.inventorycategory_id)
       , (select ic.description from inventorycategory ic, invoiceline il where ilea_cust.invoiceline_id = il.invoiceline_id and ic.inventorycategory_id = il.inventorycategory_id)) inventorycategdescr,
       (select ilea.cappedamount from invoicelineexcessamount ilea where ilea.invoiceline_id = a.invoiceline_id) clientinv_cappedamount,
       (select ilea.cappedamount from invoicelineexcessamount ilea where ilea.invoiceline_id = ilea_cust.invoiceline_id) clientcustinv_cappedamount,
       ilea_cust.cappedamount cust_cappedamount,
       ilea_cust.insurancepolicynumber cust_insurancenumber,
       (select il.code from invoiceline il where il.invoiceline_id = ilea_cust.invoiceline_id) ilclient_code, --inventory category code for customer invoice details (invoice type = 7)
       (select il.description from invoiceline il where il.invoiceline_id = ilea_cust.invoiceline_id) ilclient_description, --inventory category description for customer invoice details (invoice type = 7)
       (select il.amount from invoiceline il where il.invoiceline_id = ilea_cust.invoiceline_id) ilclient_amount,
       (select ih.invoicenumber from invoiceheader ih, invoiceline il where il.invoiceheader_id = ih.invoiceheader_id and ilea_cust.invoiceline_id = il.invoiceline_id) client_invoicenumber,
       (select sum(invl.amount)
        from invoiceline invl
        where invl.invoiceheader_id = a.invoiceheader_id
              and invl.inventorycategorycode=a.inventorycategorycode
              and a.invoicelinetype_id=29) totalcappedamnt,
       (select sum(invl.amount)
        from invoiceline invl, invoiceline ilea_cust_il
        where invl.invoiceheader_id = ilea_cust_il.invoiceheader_id
              and invl.inventorycategorycode=ilea_cust_il.inventorycategorycode
              and ilea_cust_il.invoicelinetype_id=29
              and ilea_cust_il.invoiceline_id = ilea_cust.invoiceline_id) ilclient_totalcappedamnt
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)
left outer join invoicelineexcessamount ilea on ilea.invoiceline_id = a.invoiceline_id
left outer join invoicelineexcessamount ilea_cust on ilea_cust.customerinvoiceline_id = a.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_INVOICELINE_NAF
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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, PROD_LONG_DESC, SIZE_SEQUENCENR, REPAIRNUMBEROFMINUTES, REPAIRPRICEPERMINUTE)
as select f.invoicedate, f.invoicenumber, a.linenumber, 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.adjustmentpermited, 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
, (select pdesc.longdescription from product_desc pdesc
  where pdesc.product_id = b.product_link_id and pdesc.language_id = languages.language_id) prod_long_desc
, case when (select ps.sequencenumber from productsize ps where ps.product_id = b.product_link_id and ps.sizedefinition_id = b.sizedefinition_link_id) IS NULL THEN
  999 else (select ps.sequencenumber from productsize ps where ps.product_id = b.product_link_id and ps.sizedefinition_id = b.sizedefinition_link_id) end size_sequencenr
, a.repairnumberofminutes
, a.repairpriceperminute
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_INVOICELINE_NLI
 (INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPE_ID, INVOICELINETYPEDESC, CODE, DESCRIPTION, AMOUNT, PRICE, BILLEDQTY, TAXGROUPCODE, TAXTYPE, INVOICELINESUBTYPE, PRODUCTGROUPCODE, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODCODE, FINISHINGMETHODDESCRIPTION, INVOICEQTYCOLUMN, PERCENTAGE, SYSTEMUSER_ID, TIMESTAMP, REMARK, LANGUAGECODE, INVOICEHEADER_ID, OVERAMOUNT, REGISTRATIONUNITDESCRIPTION, INVOICELINE_SEQUENCENUMBER, SUPRESSPRINTING, PROCESSQTY, WASHPRICE, RENTQTY
, RENTPRICE)
as select f.invoicenumber, a.linenumber,
(CASE WHEN e.TYPE = 1 AND a.invoicelinesubtype = 8
      THEN 1.5
      --when e.type in (1,2) then 1.12
      ELSE e.TYPE
END)  invoicelinetype,
e.invoicelinetype_id,
(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
, a.description, a.amount,
nvl(a.price,0) price, a.billedqty, a.taxgroupcode, a.taxtype,
a.invoicelinesubtype, b.productgroupcode
, b.sizecode, b.sizedescription, b.finishingmethodcode, b.finishingmethoddescription, b.invoiceqtycolumn,
c.percentage,
a.systemuser_id, a.timestamp, /*a.invoiceline_id, */a.remark, LANGUAGES.CODE LANGUAGECODE,
a.invoiceheader_id, c.overamount,
 ( 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) InvoiceLine_SequenceNumber,
e.supressprinting,
coalesce((select sum(aw.billedqty) from invoiceline aw--, invoicelineproduct ilpw
 where aw.invoiceheader_id = a.invoiceheader_id
 and aw.code = a.code
 and a.invoicelinetype_id = 1
 and aw.invoicelinetype_id = 2
 ),0) processqty,
coalesce((select max(aw.price) from invoiceline aw--, invoicelineproduct ilpw
 where aw.invoiceheader_id = a.invoiceheader_id
 and aw.code = a.code
 and a.invoicelinetype_id = 1
 and aw.invoicelinetype_id = 2
 ),0) washprice,
coalesce((select sum(ar.billedqty) from invoiceline ar
 where ar.invoiceheader_id = a.invoiceheader_id
 and ar.code = a.code
 and ar.invoicelinetype_id = 1
 and ar.price = a.price),0) rentqty,
nvl((case when a.invoicelinetype_id = 1 then a.price
     else 0.00
end),0) rentprice
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_INVOICELINE_PCO
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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, DELIVERYSCHEMECODE, DELAYEDEVENEXCHANGE, LOSSWEEKSTOGO)
as select f.invoicedate, f.invoicenumber, a.linenumber,
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.adjustmentpermited, 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, b.adjustmentdeliveredqty,
B.DELIVERYSCHEMECODE, B.DELAYEDEVENEXCHANGE, A.LOSSWEEKSTOGO
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_INVOICELINE_POS
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, TAXGROUPCODE, TAXTYPE, SUBJECTTOMINIMUM, TURNOVERGROUPCODE, TURNOVERGROUPDESCRIPTION, INVOICELINESUBTYPE, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PRODUCTSHORTDESCRIPTION, 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
, DELSCHEMEFREQ)
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.adjustmentpermited, 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
   where pilt.plant_id = bu.plant_id and pilt.invoicelinetype_id = a.invoicelinetype_id) InvoiceLine_SequenceNumber,
 coalesce(( SELECT case when (coalesce(pilt.suppressprinting, 3) = 3) then e.supressprinting
          else pilt.suppressprinting end suppressprinting
         from plantinvoicelinetype pilt
         where pilt.plant_id = bu.plant_id and pilt.invoicelinetype_id = a.invoicelinetype_id), e.supressprinting) supressprinting
, b.adjustmentdeliveredqty
, (select ds.frequency from deliveryscheme ds where b.deliveryschemecode = ds.code) DelSchemeFreq
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, businessunit bu, LANGUAGES
where a.invoicelinetype_id = e.invoicelinetype_id
and a.invoiceheader_id = f.invoiceheader_id
and f.invoicebusinessunit_id = bu.businessunit_id
and f.documenttype = 1

/
create or replace view V_INVOICELINE_RAGS_PCO
 (INVOICEHEADER_ID, RAGREASON_CODE, AMOUNT, QUANTITY, WEARERNUMBER, WEARERNAME, WEARER_ID, CUSTOM_DESC, PRODUCT_LINK_CODE)
as select och.invoiceheader_id, rr.code ragreason_code, och.amount, och.quantity,
w.wearernumber, w.fullname wearername, w.wearer_id,
case
  when rr.code = '4' then 'DAMAGE'
    when rr.code = '42' then 'DAMAGE'
      when rr.code = 'BUY B' then 'BUY BACK'
        when rr.code = 'SHORT' then 'GARMENT SHORTAGE'
          when rr.code = '52' then 'MINIMUM WASHING'
  else rr.code end Custom_Desc,
(select prl.code from product_link prl where prl.product_link_id = och.product_link_id) product_link_code
from outofcirculationhistory och, weareremployment we, wearer w, ragreason rr
where och.ragreason_id = rr.ragreason_id and we.weareremployment_id = och.weareremployment_link_id and w.wearer_id = we.wearer_id
and chargeresidualvalue='Y'

/
create or replace view V_INVOICELINE_REV
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, DESCRIPTION, SUBTYPEDESC, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, TAXGROUPCODE, TAXTYPE, SUBJECTTOMINIMUM, TURNOVERGROUPCODE, INVOICELINESUBTYPE, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PRODUCTSHORTDESCRIPTION, 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, INVOICELINE_SEQUENCENUMBER, SUPRESSPRINTING, MIN_YEAR_WEEKS, NUMBEROFWEEKS)
as select f.invoicedate, f.invoicenumber, a.linenumber,
(case when e.type = 1 and a.invoicelinesubtype = 6
      then 1.5
      else e.type
end)  invoicelinetype,
(case when e.type = 1 and a.invoicelinesubtype = 6
      then  'grundgebã¼hr'
      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, a.description, (select coalesce(ild.description, ils.factorydescription) from invoicelinesubtype ils, invoicelinesubtype_desc ild where ils.invoicelinetype_id = a.invoicelinetype_id
    and ild.invoicelinesubtype_id=ils.invoicelinesubtype_id and a.invoicelinesubtype = ils.subtype
    and ild.language_id = languages.language_id) as subtypedesc,
    a.adjustedamount, a.adjustedprice, a.adjustmentbilledqty, a.extend, a.amount, a.discountpercentage,
    a.price, a.billedqty, a.adjustmentpermited, a.taxgroupcode, a.taxtype, a.subjecttominimum, d.code turnovergroupcode,
    a.invoicelinesubtype, b.productgroupcode, b.productgroupdescription,
    b.productshortdescription,
    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 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
, cast(fsget_min_6_yearweeks(a.invoiceheader_id, f.invoicefrequency_id) as varchar2(47)) min_year_weeks
, b.numberofweeks
    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_INVOICELINE_SGS
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, NOOFWEEKS, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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, RQAQUANTITY, PLPCPRICE, TYPEOFMERCHANDISE, MAXINVENTORY, PRODUCT_LINK_ID, SIZEDEFINITION_LINK_ID, WEAREREMPLOYMENT_LINK_ID, COUNTWEARERS)
as select f.invoicedate, f.invoicenumber, a.linenumber,
(CASE WHEN e.TYPE = 1 AND a.invoicelinesubtype = 8 --Additional
      THEN 1.5
      when e.type=1 and a.invoicelinesubtype <> 7 AND a.invoicelinesubtype <> 8 --and f.nextperiodstartdate is not null--Back charge
      then 1.4
      when e.type=1 and a.invoicelinesubtype=7-- and f.nextperiodstartdate is not null--Rent in Advance
      then 1.7
      ELSE e.TYPE
END)  invoicelinetype,
(CASE WHEN e.TYPE = 1 AND a.invoicelinesubtype = 8
      THEN   'Addition/Replacement'
      WHEN e.TYPE = 1 AND a.invoicelinesubtype <> 7 AND a.invoicelinesubtype <> 8 and f.nextperiodstartdate is not null
      THEN   'Back charge'
      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,
      (select count(1) from costreportinfo cri where cri.invoiceline_id=a.invoiceline_id) noofweeks
, 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.adjustmentpermited, 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,
nvl((select sum(q.quantity)
                 from   rentalqtyadjustment q, productlistperdistribpoint plpd, distributionpoint dp,
                        department t
                 where  q.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
                 and    plpd.distributionpoint_id = dp.distributionpoint_id
                 and    dp.department_id = t.department_id
                 and    t.customer_id = f.deltocustomer_link_id
                 and    b.product_link_id = plpd.product_id
                 and    b.sizedefinition_link_id = plpd.sizedefinition_id
                 and    b.finishingmethod_id = plpd.finishingmethod_id --         and    q.adjustmentdate >= h.startdate
                 and    q.adjustmentdate <= f.enddate
                 and    q.sampleitem = 'N'), 0) RQAquantity,
case when a.invoicelinetype_id = 2 then Pack_price.Rent_Price(f.deltocustomer_link_id, b.product_link_id, b.sizedefinition_link_id, b.finishingmethod_id, f.invoicedate)--rent
     when a.invoicelinetype_id = 1 then Pack_price.Wash_Price(f.deltocustomer_link_id, b.product_link_id, b.sizedefinition_link_id, b.finishingmethod_id, f.invoicedate, 1)--wash
      else 0 end PLPCprice,
(select prd.typeofmerchandise from product prd where prd.product_id = b.product_link_id) typeofmerchandise,
(select sum(winv.maxinventory) from wearerinventory winv, weareremployment were, distributionpoint dipo, department depa
        where winv.product_id = b.product_link_id
        and (winv.sizedefinition_id = b.sizedefinition_link_id or b.sizedefinition_link_id in (select sd.sizedefinition_id from sizedefinition sd where sd.code = '*'))
        and winv.finishingmethod_id = b.finishingmethod_id
        and winv.weareremployment_id = were.weareremployment_id and were.distributionpoint_id = dipo.distributionpoint_id
        and dipo.department_id = depa.department_id and depa.customer_id = f.deltocustomer_link_id
        ) maxinventory, b.product_link_id , b.sizedefinition_link_id, b.weareremployment_link_id,
(select count(winv.wearerinventory_id) from wearerinventory winv, weareremployment were, distributionpoint dipo, department depa
        where winv.product_id = b.product_link_id
        and (winv.sizedefinition_id = b.sizedefinition_link_id or b.sizedefinition_link_id in (select sd.sizedefinition_id from sizedefinition sd where sd.code = '*'))
        and winv.finishingmethod_id = b.finishingmethod_id
        and winv.weareremployment_id = were.weareremployment_id and were.distributionpoint_id = dipo.distributionpoint_id
        and dipo.department_id = depa.department_id and depa.customer_id = f.deltocustomer_link_id
        ) CountWearers
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_INVOICELINE_SMG
 (INVOICEDATE, INVOICENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, DESCRIPTION, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, SIZECODE, FINISHINGMETHODCODE, PERCENTAGE, INVOICELINE_ID, LANGUAGECODE, INVOICEHEADER_ID, OVERAMOUNT, REGISTRATIONUNITDESCRIPTION, INVOICELINE_SEQUENCENUMBER, SUPRESSPRINTING, PRICEFACTOR, PRODGRCODE)
as select f.invoicedate,
       f.invoicenumber,
       a.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,
       a.description,
       a.extend,
       a.amount,
       a.discountpercentage,
       a.price,
       a.billedqty,
       b.sizecode,
       b.finishingmethodcode,
       c.percentage,
       a.invoiceline_id,
       LANGUAGES.CODE LANGUAGECODE,
       a.invoiceheader_id,
       c.overamount,
      (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
         where pilt.plant_id =bu.plant_id
           and pilt.invoicelinetype_id = a.invoicelinetype_id) InvoiceLine_SequenceNumber,
       (SELECT pilt.suppressprinting
          from plantinvoicelinetype pilt--, businessunit bu, invoiceheader h
         where pilt.plant_id =bu.plant_id
           and pilt.invoicelinetype_id = a.invoicelinetype_id) supressprinting --502161
      , b.pricefactor,
     (case when b.product_link_id is not null then ( select pg.code from product p, productgroup pg
where p.productgroup_id=pg.productgroup_id and b.product_link_id=p.product_id)
          when  b.weighingcategory_link_id is not null
            then coalesce((select  min(ppg.code) from productgroup ppg,weighingcategory wg where wg.weighingcategory_id=b.weighingcategory_link_id and  ppg.code=wg.legacyweighingcategorycode),
              (select w.code from weighingcategory w where w.weighingcategory_id=b.weighingcategory_link_id))
               else '' end) Prodgrcode
       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)
  , invoiceheader f, businessunit bu,
 LANGUAGES
 where a.invoiceheader_id = f.invoiceheader_id
   and f.invoicebusinessunit_id = bu.businessunit_id
   and f.documenttype = 1

/
create or replace view V_INVOICELINE_SNG
 (INVOICEDATE, INVOICENUMBER, PARENTINVOICEHEADER_ID, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, TAXGROUPCODE, TAXTYPE, SUBJECTTOMINIMUM, TURNOVERGROUPCODE, TURNOVERGROUPDESCRIPTION, INVOICELINESUBTYPE, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PRODUCTSHORTDESCRIPTION, 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
, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, STARTWEEK, ENDWEEK, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, PRICEFACTOR, ACTIVITYDESC, ACTIVITYCODE, REGUNIT, COSTCENTER_CODE, COSTCENTER_DESCRIPTION, COSTCENTERINVOICELINE_QUANTITY, COSTCENTERINVOICELINE_AMOUNT, COSTCENTER_LINK_ID, TOTALAMOUNTEXCLVAT)
as select f.invoicedate, f.invoicenumber, f.parentinvoiceheader_id, a.linenumber,
(CASE WHEN e.TYPE = 1 AND a.invoicelinesubtype = 8
      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.adjustmentpermited, 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, b.adjustmentdeliveredqty
, F.NEXTPERIODSTARTWEEK, F.NEXTPERIODENDWEEK, F.STARTWEEK, F.ENDWEEK
, F.NEXTPERIODSTARTDATE, F.NEXTPERIODENDDATE, F.NEXTPERIODNOWEEKS
, b.pricefactor
, case when e.type in (6, 12, 23) then (select ad.description from activity_desc ad, activity ac where ac.code = '09' and ac.activity_id = ad.activity_id and ad.language_id = languages.language_id)
when e.type in (7, 8, 9, 10, 11, 19, 20, 22, 24, 25) then (select ad.description from activity_desc ad, activity ac where ac.code = '08' and ac.activity_id = ad.activity_id and ad.language_id = languages.language_id)
else (select ad.description from activity_desc ad, productgroup pg where b.productgroupcode = pg.code and ad.activity_id = pg.activity_id and ad.language_id = languages.language_id)
end ActivityDesc
, case when e.type in (6, 12, 23) then '09'
when e.type in (7, 8, 9, 10, 11, 19, 20, 22, 24, 25) then '08'
else (select ac.code from activity ac, productgroup pg where b.productgroupcode = pg.code and ac.activity_id = pg.activity_id)
end ActivityCode
, (select ru.code from product pr, registrationunit ru where b.product_link_id = pr.product_id and pr.registrationunit_id = ru.registrationunit_id) regunit,
(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 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
from invoiceline a
left outer join costcenterinvoiceline ccil on ccil.invoiceline_id = a.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)
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_INVOICELINE_STI
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, TAXGROUPCODE, TAXTYPE, SUBJECTTOMINIMUM, TURNOVERGROUPCODE, INVOICELINESUBTYPE, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PRODUCTSHORTDESCRIPTION, 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, INVOICELINE_SEQUENCENUMBER, SUPRESSPRINTING, FREQUENCY, WEEKSDIFFERENCE, CRI_MINWEEK, CRI_MAXWEEK, CRI_YEAR, CRI_WEEK
, CRI_QUANTITY)
as select f.invoicedate, f.invoicenumber, a.linenumber, 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, a.description,
    a.adjustedamount, a.adjustedprice, a.adjustmentbilledqty, a.extend, a.amount, a.discountpercentage,
    a.price, a.billedqty, a.adjustmentpermited, a.taxgroupcode, a.taxtype, a.subjecttominimum, d.code turnovergroupcode,
    a.invoicelinesubtype, b.productgroupcode, b.productgroupdescription,
    b.productshortdescription,
    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 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
    --, (select ds.frequency from deliveryscheme ds where b.deliveryschemecode = ds.code) DelSchemeFreq
    , (case
  when a.invoicelinetype_id = 1 -- and a.invoicelinesubtype in (0, 7, 8)--e.type = 1 and a.invoicelinesubtype = 0
  then FGET_BDE_FRECV(f.deltocustomer_link_id, b.product_link_id, b.sizedefinition_link_id, b.finishingmethod_id, f.invoicedate, b.deliveryschemecode)
  else -1
  end ) Frequency
  , GETWEEKSDIFFERENCE_BDE((select min(cri.year) from costreportinfo cri where cri.invoiceline_id = a.invoiceline_id)
  , (select min(cr.week) from costreportinfo cr where cr.invoiceline_id = a.invoiceline_id and cr.year in (select min(cri.year) from costreportinfo cri where cri.invoiceline_id = a.invoiceline_id))
  , (select max(cri.year) from costreportinfo cri where cri.invoiceline_id = a.invoiceline_id)
  , (select max(cr.week) from costreportinfo cr where cr.invoiceline_id = a.invoiceline_id and cr.year in (select max(cri.year) from costreportinfo cri where cri.invoiceline_id = a.invoiceline_id))) WeeksDifference
  , (select min(cr.week) from costreportinfo cr where cr.invoiceline_id = a.invoiceline_id and cr.year in (select min(cri.year) from costreportinfo cri where cri.invoiceline_id = a.invoiceline_id)) CRI_minweek
     , (select max(cr.week) from costreportinfo cr where cr.invoiceline_id = a.invoiceline_id and cr.year in (select min(cri.year) from costreportinfo cri where cri.invoiceline_id = a.invoiceline_id)) CRI_maxweek
   , g.YEAR CRI_year, g.WEEK CRI_week
   , g.QUANTITY CRI_quantity
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)
    LEFT OUTER JOIN costreportinfo g ON (a.invoiceline_id = g.invoiceline_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_INVOICELINE_STK
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, TAXGROUPCODE, TAXTYPE, SUBJECTTOMINIMUM, TURNOVERGROUPCODE, INVOICELINESUBTYPE, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PRODUCTSHORTDESCRIPTION, 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, INVOICELINE_SEQUENCENUMBER, SUPRESSPRINTING)
as select f.invoicedate, f.invoicenumber, a.linenumber,
(CASE WHEN e.TYPE = 1 AND a.invoicelinesubtype = 6
      THEN 1.5
      when e.type = 1 and ((a.price = 0) or (a.price is null)) then 1.6
	    ELSE e.TYPE
END)  invoicelinetype,
(CASE WHEN e.TYPE = 1 AND a.invoicelinesubtype = 6
      THEN  'Grundgebühr'
      when e.type = 1 and ((a.price = 0) or (a.price is null)) then 'Free Of Charge'
	    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, a.description,
    a.adjustedamount, a.adjustedprice, a.adjustmentbilledqty, a.extend, a.amount, a.discountpercentage,
    a.price, a.billedqty, a.adjustmentpermited, a.taxgroupcode, a.taxtype, a.subjecttominimum, d.code turnovergroupcode,
    a.invoicelinesubtype, b.productgroupcode, b.productgroupdescription,
    b.productshortdescription,
    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,
(case  when e.type = 1 and ((a.price = 0) or (a.price is null)) AND a.invoicelinesubtype <> 6 then
       -- display this group of invoice lines (free of charge lines)
       -- right before TAX lines
       -- (but not Grundgebühr invoice lines)
     ( 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 = 18) - 0.1
     else
     ( 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)
end)  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_INVOICELINE_VEN
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, CLIENTNAME, ROOMNUMBER, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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 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,
(select ihc.name from invoiceheaderclient ihc where ihc.invoiceheader_id = f.invoiceheader_id) clientname,
(select ihc.roomnumber from invoiceheaderclient ihc where ihc.invoiceheader_id = f.invoiceheader_id) roomnumber,
a.adjustedamount, a.adjustedprice, a.adjustmentbilledqty, a.extend, a.amount, a.discountpercentage,
a.price, a.billedqty, a.adjustmentpermited, 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,
        pilt.sequencenumber 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
  pilt.suppressprinting supressprinting
, b.adjustmentdeliveredqty, b.pricefactor
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, plantinvoicelinetype pilt, businessunit bu
where a.invoiceheader_id = f.invoiceheader_id
and a.invoicelinetype_id = e.invoicelinetype_id
and f.documenttype in (1, 3)
and f.invoicebusinessunit_id = bu.businessunit_id
               and bu.plant_id = pilt.plant_id
               and pilt.invoicelinetype_id = a.invoicelinetype_id

/
create or replace view V_INVOICELINE_WMU
 (INVOICEDATE, INVOICENUMBER, LINENUMBER, INVOICELINETYPE, INVOICELINETYPEDESC, CODE, TAXCODE, DESCRIPTION, ADJUSTEDAMOUNT, ADJUSTEDPRICE, ADJUSTMENTBILLEDQTY, EXTEND, AMOUNT, DISCOUNTPERCENTAGE, PRICE, BILLEDQTY, ADJUSTMENTPERMITED, 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, PRODUCT_DESC, WEARERFUNCTIONDESC)
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.adjustmentpermited, 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,
( 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 pd.description from product_desc pd where pd.product_id = b.product_link_id and pd.language_id = LANGUAGES.Language_Id) product_desc,
( select wfu.description
    from wearerfunction wfu, weareremployment wem
   where wem.weareremployment_id = b.weareremployment_link_id
     and wfu.wearerfunction_id = wem.wearerfunction_id) wearerfunctiondesc
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_INVOICEOBJCC_NOLINE_SMG
 (NOTE, DELDATE, INVOICEHEADER_ID, CCID)
as select distinct cast(pn.notenumber as varchar2(20)) note, pn.deliverydate deldate, ih.invoiceheader_id,
(select dp.costcenter_id from distributionpoint dp where pn.distributionpoint_id = dp.distributionpoint_id) ccid
from packingnote pn, packingnotecontainer pnc, invoiceheader ih
where pn.packingnote_id = pnc.packingnote_id
and pnc.invoiceheader_id = ih.invoiceheader_id
and pn.showoninvoiceappendix = 'Y'
and not exists (select 1 from packingnoteline l where pn.packingnote_id = l.packingnote_id)
and pnc.weighingcategory_id is null

/
create or replace view V_INVOICEOBJCC_SMG
 (NOTE, DELDATE, INVOICEHEADER_ID, CCID)
as select distinct (note), deldate, invoiceheader_id, ccid
from (
  select cast(pn.notenumber as varchar2(20)) note, pn.deliverydate deldate, ih.invoiceheader_id,
  (select dp.costcenter_id from distributionpoint dp where pn.distributionpoint_id = dp.distributionpoint_id) ccid
  from packingnote pn, packingnoteline pnl, invoiceheader ih
  where pn.packingnote_id = pnl.packingnote_id
  and pnl.invoiceheader_id = ih.invoiceheader_id
  and pn.showoninvoiceappendix = 'Y'
  union all
  select cast(pn.notenumber as varchar2(20)) note, pn.deliverydate deldate, ih.invoiceheader_id,
  (select dp.costcenter_id from distributionpoint dp where pn.distributionpoint_id = dp.distributionpoint_id) ccid
  from packingnote pn, packingnotecontainer pnc, invoiceheader ih
  where pn.packingnote_id = pnc.packingnote_id
  and pnc.invoiceheader_id = ih.invoiceheader_id
  and pn.showoninvoiceappendix = 'Y'
  and (exists (select 1 from packingnoteline l where pn.packingnote_id = l.packingnote_id)
       or not (pnc.weighingcategory_id is null))
  union all
  select cast(wt.ticketnumber as varchar2(20)) note, wt.weighingdate deldate, ih.invoiceheader_id,
  (select dp.costcenter_id from distributionpoint dp where wtl.distributionpoint_id = dp.distributionpoint_id) ccid
   from weighingticket wt, weighingticketline wtl, invoiceheader ih
  where wt.weighingticket_id = wtl.weighingticket_id
  and wtl.invoiceheader_id = ih.invoiceheader_id
  union all
  select cast('KA-'||wo.workordernumber as varchar2(20)) note, wo.completiondate deldate, ih.invoiceheader_id,
  (select dp.costcenter_id from distributionpoint dp where wo.distributionpoint_link_id = dp.distributionpoint_id) ccid
   from workorder wo, invoiceheader ih
   where wo.invoiceheader_id = ih.invoiceheader_id
   and wo.origin = 6)

/
create or replace view V_INVOICEOBJ_BDM
 (NOTE, DELDATE, INVOICEHEADER_ID, ORIGIN)
as select  distinct cast(pn.notenumber as varchar2(20)) note , pn.deliverydate deldate , ih.invoiceheader_id, pn.origin
from packingnote pn, packingnoteline pnl, invoiceheader ih
where pn.packingnote_id=pnl.packingnote_id
and pnl.invoiceheader_id=ih.invoiceheader_id--and pn.showoninvoiceappendix='Y'
and (pn.remark is null or pn.remark <> 'OVERUSE')
union
select  distinct cast(pn.notenumber as varchar2(20)) note , pn.deliverydate deldate , ih.invoiceheader_id, pn.origin
from packingnote pn, packingnotecontainer pnl, invoiceheader ih
where pn.packingnote_id=pnl.packingnote_id
and pnl.invoiceheader_id=ih.invoiceheader_id--and pn.showoninvoiceappendix='Y'
and (pn.remark is null or pn.remark <> 'OVERUSE')
union all
select distinct 'NV'||cast(wo.workordernumber as varchar2(20)) note,null, wo.invoiceheader_id, wo.origin
from workorder wo
where wo.origin=6

/
create or replace view V_INVOICEOBJ_ELI
 (NOTE, DELDATE, INVOICEHEADER_ID, COSTCENTER_ID)
as select distinct (note), deldate, invoiceheader_id, costcenter_id
from(
  select cast(pn.notenumber as varchar2(20)) note, pn.deliverydate deldate, ih.invoiceheader_id, dp.costcenter_id
  from packingnote pn, packingnoteline pnl, invoiceheader ih, distributionpoint dp
  where pn.packingnote_id = pnl.packingnote_id and dp.distributionpoint_id = pn.distributionpoint_id
  and pnl.invoiceheader_id = ih.invoiceheader_id and pn.showoninvoiceappendix = 'Y'
  union
  select cast(pn.notenumber as varchar2(20)) note, pn.deliverydate deldate , ih.invoiceheader_id, dp.costcenter_id
  from packingnote pn, packingnotecontainer pnl, invoiceheader ih, distributionpoint dp
  where pn.packingnote_id = pnl.packingnote_id and dp.distributionpoint_id = pn.distributionpoint_id
  and pnl.invoiceheader_id = ih.invoiceheader_id and pn.showoninvoiceappendix = 'Y'
  union all
  select cast(wt.ticketnumber as varchar2(20)) note, wt.weighingdate deldate, ih.invoiceheader_id, -1 costcenter_id
   from weighingticket wt, weighingticketline wtl, invoiceheader ih
  where wt.weighingticket_id=wtl.weighingticket_id
  and wtl.invoiceheader_id = ih.invoiceheader_id
  union all
  select cast('NV-'||wo.workordernumber as varchar2(20)) note, wo.completiondate deldate  , ih.invoiceheader_id, -1 costcenter_id
  from workorder wo, invoiceheader ih
  where wo.invoiceheader_id=ih.invoiceheader_id
  and wo.origin = 6
)

/
create or replace view V_INVOICEOBJ_NAF
 (NOTE, DELDATE, INVOICEHEADER_ID)
as select  distinct cast(pn.notenumber as varchar2(20)) note , pn.deliverydate deldate , ih.invoiceheader_id
from packingnote pn, packingnoteline pnl, invoiceheader ih
where pn.packingnote_id=pnl.packingnote_id
and pnl.invoiceheader_id=ih.invoiceheader_id--and pn.showoninvoiceappendix='Y'
union
select  distinct cast(pn.notenumber as varchar2(20)) note , pn.deliverydate deldate , ih.invoiceheader_id
from packingnote pn, packingnotecontainer pnl, invoiceheader ih
where pn.packingnote_id=pnl.packingnote_id
and pnl.invoiceheader_id=ih.invoiceheader_id--and pn.showoninvoiceappendix='Y'

/
create or replace view V_INVOICEOBJ_NOPNL_SMG
 (NOTE, DELDATE, INVOICEHEADER_ID)
as select distinct cast(pn.notenumber as varchar2(20)) note , pn.deliverydate deldate, ih.invoiceheader_id
from packingnote pn, packingnotecontainer pnc, invoiceheader ih
where pn.packingnote_id = pnc.packingnote_id
and pnc.invoiceheader_id = ih.invoiceheader_id
and pn.showoninvoiceappendix = 'Y'
and not exists (select 1 from packingnoteline l where pn.packingnote_id = l.packingnote_id)
and pnc.weighingcategory_id is null

/
create or replace view V_INVOICEOBJ_SMG
 (NOTE, DELDATE, INVOICEHEADER_ID)
as select distinct (note), deldate, invoiceheader_id
from (
  select cast(pn.notenumber as varchar2(20)) note, pn.deliverydate deldate , ih.invoiceheader_id
  from packingnote pn, packingnoteline pnl, invoiceheader ih
  where pn.packingnote_id = pnl.packingnote_id
  and pnl.invoiceheader_id = ih.invoiceheader_id
  and pn.showoninvoiceappendix = 'Y'
  union all
  select cast(pn.notenumber as varchar2(20)) note, pn.deliverydate deldate , ih.invoiceheader_id
  from packingnote pn, packingnotecontainer pnc, invoiceheader ih
  where pn.packingnote_id = pnc.packingnote_id
  and pnc.invoiceheader_id = ih.invoiceheader_id
  and pn.showoninvoiceappendix = 'Y'
  and (exists (select 1 from packingnoteline l where pn.packingnote_id = l.packingnote_id)
   or not (pnc.weighingcategory_id is null))
  union all
  select cast(wt.ticketnumber as varchar2(20)) note, wt.weighingdate deldate, ih.invoiceheader_id
  from weighingticket wt, weighingticketline wtl, invoiceheader ih
  where wt.weighingticket_id = wtl.weighingticket_id
  and wtl.invoiceheader_id = ih.invoiceheader_id
  union all
  select cast('KA-'||wo.workordernumber as varchar2(20)) note, wo.completiondate deldate, ih.invoiceheader_id
  from workorder wo, invoiceheader ih
  where wo.invoiceheader_id = ih.invoiceheader_id
  and wo.origin = 6 )

/
create or replace view V_INVOICEOBJ_STI
 (INVOICEHEADER_ID, NOTES)
as select  v.invoiceheader_id ,
  case  when (select max(cast(lpad(replace(pcv.version, '.', ''), 3) as numeric)) from product_component_version pcv) >= 112
  then
  ( CAST( listagg(v.note,',') within group(order by note) AS VARCHAR2(60)) )
  else ('Only for Oracle version 11.b' )
  end notes
  from (
  SELECT DISTINCT CAST(pn.notenumber AS VARCHAR2(20)) note ,
    pn.deliverydate deldate ,
    ih.invoiceheader_id, ih.invoicenumber
  FROM packingnote pn,
    packingnoteline pnl,
    invoiceheader ih,
    plantdepartment d
  WHERE pn.packingnote_id  =pnl.packingnote_id
  AND pnl.invoiceheader_id =ih.invoiceheader_id--and pn.showoninvoiceappendix='Y'
  AND d.plantdepartment_id = pn.plantdepartment_id
  AND d.code               = 'TY'
 )v
  group by v.invoiceheader_id

/
create or replace view V_INVOICESOUTSTANDING_RMI
 (BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, BILLTOCUSTOMER_LINK_ID, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, DELTOCUSTOMER_LINK_ID, INVOICEHEADER_ID, INVOICENUMBER, INVOICEDATE, PREBILLAMOUNT, TOTALAMOUNTEXCLVAT, PAYTHISAMOUNT, PAYMENTTERMSDUEDATE, OUTSTANDINGAMOUNT)
as select outst_ih.billtocustomernumber, outst_ih.billtocustomername, outst_ih.billtocustomer_link_id, outst_ih.deltocustomernumber, outst_ih.deltocustomername, outst_ih.deltocustomer_link_id,
       il.invoiceheader_id, il.code invoicenumber, outst_ih.invoicedate, outst_ih.prebillamount, outst_ih.totalamountexclvat, outst_ih.paythisamount,
       (select ihextr.paymenttermsduedate from invoiceheaderextrainfo ihextr where ihextr.invoiceheader_id = outst_ih.invoiceheader_id) paymenttermsduedate,
       il.amount OutstandingAmount
from invoiceline il, invoiceheader outst_ih
where il.code = to_char(outst_ih.invoicenumber) and il.invoicelinetype_id = 14--Cash Delay lines are where Outstanding Invoices are stored for RMI

/
create or replace view V_INVOICETAXCC_LTS
 (INVOICEDATE, INVOICENUMBER, BILLTOCUSTOMERNUMBER, PREBILLAMOUNT, INVOICELINETYPE, TAXCODE, TAXGROUPCODE, TAXTYPE, TAXRATE, AMOUNT, PRICE, PERCENTAGE, OVERAMOUNT, INVOICELINE_ID, INVOICEHEADER_ID, COSTCENTER_LINK_ID, COSTCENTER_CODE, COSTCENTERINVOICELINE_QUANTITY, COSTCENTERINVOICELINE_AMOUNT, TOTALAMOUNTEXCLVAT)
as select f.invoicedate, f.invoicenumber, f.billtocustomernumber, f.prebillamount,
       (select e.type from invoicelinetype e where a.invoicelinetype_id = e.invoicelinetype_id) invoicelinetype,
       cast(fsget_taxcode(f.invoicenumber, a.linenumber) as varchar2(255)) taxcode, a.taxgroupcode, a.taxtype,
       (select case when f.invoicedate < tg.startdatetaxrate then tg.oldtaxrate
               else tg.taxrate
               end taxrate
         from taxgroup tg, customer bill
         where a.taxgroupcode = tg.code
               and bill.customer_id = f.billtocustomer_link_id
               and tg.country_id = bill.country_id) taxrate,
       a.amount,
       a.price,
       c.percentage, c.overamount,
       a.invoiceline_id, a.invoiceheader_id,
       ccil.costcenter_link_id,
       (select cc.code from costcenter_link cc where ccil.costcenter_link_id = cc.costcenter_link_id) costcenter_code,
       ccil.quantity costcenterinvoiceline_quantity, ccil.amount costcenterinvoiceline_amount,
       (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
from   invoiceheader f, invoiceline a, costcenterinvoiceline ccil
left   outer join invoicelinevarious c on (ccil.invoiceline_id = c.invoiceline_id)
where  a.invoiceheader_id = f.invoiceheader_id
and    f.documenttype = 1
and    a.invoicelinetype_id = 18
and    ccil.invoiceline_id = a.invoiceline_id

/
create or replace view V_INVOICETAXCLIENTCOSTSPEC_LTS
 (LINETYPE, QUANTITY, SPECIALPRICE, IL_PRICE, PRICE, TAXRATE, INVOICEHEADER_ID, BILLTOCUSTOMERNUMBER, INVOICENUMBER)
as select 1 linetype, cdl.qtyscannedout + cdl.qtycountedout Quantity,
 (select wp.price
  from generalwashprice wp, generalpricelist g, customer cus, clientdeliverynote cdn
  where wp.generalpricelist_id = g.generalpricelist_id
    and g.code = to_char(cus.pnnumber)
    and cdl.clientdeliverinote_id = cdn.clientdeliverynote_id
    and cus.pnnumber <> '0'
    and cdn.customer_link_id = cus.customer_id
    and cdl.product_link_id = wp.product_id
    and cdl.sizedefinition_link_id = wp.sizedefinition_id
    and cdl.finishingmethod_id = wp.finishingmethod_id
    and wp.pricetype = 1
    and wp.startdate = ( select max(x.startdate)
      from generalwashprice x
      where x.generalpricelist_id  = wp.generalpricelist_id
        and x.startdate <= cdn.Deliverydate
        and x.product_id = wp.product_id
        and x.sizedefinition_id = wp.sizedefinition_id
        and x.finishingmethod_id = wp.finishingmethod_id
        and x.pricetype = wp.pricetype )) specialprice,
    il.price Il_Price, cdl.price,
         (select case when ih.enddate < tg.startdatetaxrate then tg.oldtaxrate
               else tg.taxrate
               end taxrate
         from taxgroup tg, customer bill
         where il.taxgroupcode = tg.code
               and bill.customer_id = ih.billtocustomer_link_id
               and tg.country_id = bill.country_id) taxrate
     , ih.invoiceheader_id, ih.billtocustomernumber, ih.invoicenumber
from clientdeliverynoteline cdl
     inner join invoiceline il
          join invoiceheader ih on (ih.invoiceheader_id=il.invoiceheader_id)
     on cdl.invoiceline_id=il.invoiceline_id
union all
select 2 linetype, cdc.quantity , null specialprice, il.price Il_Price, cdc.price,
         (select case when ih.enddate < tg.startdatetaxrate then tg.oldtaxrate
               else tg.taxrate
               end taxrate
         from taxgroup tg, customer bill
         where il.taxgroupcode = tg.code
               and bill.customer_id = ih.billtocustomer_link_id
               and tg.country_id = bill.country_id) taxrate, ih.invoiceheader_id, ih.billtocustomernumber, ih.invoicenumber
from clientdeliverynotespeccharge cdc
        inner join invoiceline il
             join invoiceheader ih on (ih.invoiceheader_id=il.invoiceheader_id)
        on cdc.invoiceline_id=il.invoiceline_id
union all
select 3 linetype, cdn.invoiceweight Quantity, null specialprice, il.price Il_Price, cdn.weightprice Price,
   (select tg.taxrate
   from taxgroup tg, weighingcategorytax wct
   where tg.taxgroup_id = wct.taxgroup_id
         and wct.weighingcategory_id = cdn.weighingcategory_link_id) taxrate
         , ih.invoiceheader_id, ih.billtocustomernumber, ih.invoicenumber
from clientdeliverynote cdn
        inner join invoiceline il
           join invoiceheader ih on (ih.invoiceheader_id=il.invoiceheader_id)
        on cdn.invoiceline_id=il.invoiceline_id
        left outer join clientdeliverynotetax ctx
             join taxgroup txg on (ctx.taxgroup_id = txg.taxgroup_id)
        ON ctx.CLIENTDELIVERINOTE_ID = cdn.ClientDeliveryNote_ID
union all
select 4 linetype, count(*) quantity , null specialprice, il.price Il_Price, pqr.price,
         (select case when ih.enddate < tg.startdatetaxrate then tg.oldtaxrate
               else tg.taxrate
               end taxrate
         from taxgroup tg, customer bill
         where il.taxgroupcode = tg.code
               and bill.customer_id = ih.billtocustomer_link_id
               and tg.country_id = bill.country_id) taxrate, ih.invoiceheader_id, ih.billtocustomernumber, ih.invoicenumber
from printqueueresidentialitem pqr
        inner join invoiceline il
             join invoiceheader ih on (ih.invoiceheader_id=il.invoiceheader_id)
        on pqr.invoiceline_id=il.invoiceline_id
group by pqr.labellayout_id, il.invoiceline_id, pqr.chargeable , pqr.preprinted
, ih.invoiceheader_id, ih.enddate, ih.invoicenumber, ih.billtocustomernumber, ih.billtocustomer_link_id, il.price, il.taxgroupcode, pqr.price

/
create or replace view V_INVOICETAXCOSTSPEC_LTS
 (INVOICEDATE, INVOICENUMBER, BILLTOCUSTOMERNUMBER, PREBILLAMOUNT, INVOICELINETYPE, TAXCODE, TAXGROUPCODE, TAXTYPE, TAXRATE, AMOUNT, PRICE, PERCENTAGE, OVERAMOUNT, INVOICELINE_ID, INVOICEHEADER_ID, COSTCENTER_LINK_ID, COSTCENTER_CODE, COSTCENTERINVOICELINE_QUANTITY, COSTCENTERINVOICELINE_AMOUNT, TOTALAMOUNTEXCLVAT, CCCODE, CCDESC)
as select f.invoicedate, f.invoicenumber, f.billtocustomernumber, f.prebillamount,
       (select e.type from invoicelinetype e where a.invoicelinetype_id = e.invoicelinetype_id) invoicelinetype,
       cast(fsget_taxcode(f.invoicenumber, a.linenumber) as varchar2(255)) taxcode, a.taxgroupcode, a.taxtype,
        (select case when f.invoicedate < tg.startdatetaxrate then tg.oldtaxrate
               else tg.taxrate
               end taxrate
         from taxgroup tg, customer bill
         where a.taxgroupcode = tg.code
               and bill.customer_id = f.billtocustomer_link_id
               and tg.country_id = bill.country_id) taxrate,
       a.amount,
       a.price,
       c.percentage, c.overamount,
       a.invoiceline_id, a.invoiceheader_id,
       ccil.costcenter_link_id,
       (select cc.code
          from costcenter_link cc
         where ccil.costcenter_link_id = cc.costcenter_link_id) costcenter_code,
       ccil.quantity costcenterinvoiceline_quantity, ccil.amount costcenterinvoiceline_amount,
       (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 ea.invoicelinetype_id
                  from invoicelinetype ea
                 where ea.type <> 18
                   and ab.invoicelinetype_id = ea.invoicelinetype_id
                   and ccilb.amount <> 0)
         group by a.invoiceheader_id, ccil.costcenter_link_id) totalamountexclvat,
       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)
where a.invoiceheader_id = f.invoiceheader_id
   and f.documenttype = 1
   and ccil.invoiceline_id = a.invoiceline_id

/
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
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)
group by osia.invoiceheader_id,osia.inventorydate, p.product_id ,sd.sizedefinition_id,fm.finishingmethod_id, d.customer_id

/
create or replace view V_INVOICEWASHDELIVERYNOTES_HOW
 (LINETYPE, NOTENUMBER, INVOICEHEADER_ID, QTY, DELIVERYDATE, PRODUCT_ID, SIZEDEFINITION_ID, FINISHINGMETHOD_ID, CUSTOMER_LINK_ID, BILLEDQTY, INVOICELINE_ID, CODE, INVOICELINETYPE_ID, INVOICELINESUBTYPE)
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
, il.billedqty, il.invoiceline_id, il.code, il.invoicelinetype_id, il.invoicelinesubtype
from packingnote pn, packingnoteline pnl, invoiceline il, invoicelineproduct ilp, product_link pl
, sizedefinition_link szl, invoiceheader ih
where pn.packingnote_id = pnl.packingnote_id
and il.invoiceheader_id=pnl.invoiceheader_id
and ilp.invoiceline_id=il.invoiceline_id
and pl.product_link_id=ilp.product_link_id
and pnl.product_id=pl.product_id
and pnl.sizedefinition_id=szl.sizedefinition_id
and szl.sizedefinition_link_id=ilp.sizedefinition_link_id
and ilp.finishingmethod_id=pnl.finishingmethod_id
and ih.invoiceheader_id=pnl.invoiceheader_id --and ih.invoicenumber=2488763001
and il.invoicelinetype_id=2
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
, il.billedqty, il.invoiceline_id, il.code, il.invoicelinetype_id, il.invoicelinesubtype
from onsiteinventoryadjustment osia, productlistperdistribpoint plpd, distributionpoint dp,
department d, product p, sizedefinition sd, finishingmethod fm, invoiceline il, invoicelineproduct ilp, product_link pl
, sizedefinition_link szl, invoiceheader ih
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 il.invoiceheader_id=osia.invoiceheader_id
and ilp.invoiceline_id=il.invoiceline_id
and pl.product_link_id=ilp.product_link_id
and plpd.product_id=pl.product_id
and plpd.sizedefinition_id=szl.sizedefinition_id
and szl.sizedefinition_link_id=ilp.sizedefinition_link_id
and ilp.finishingmethod_id=plpd.finishingmethod_id
and ih.invoiceheader_id=osia.invoiceheader_id --and ih.invoicenumber=2488763001
and il.invoicelinetype_id=2
and osia.origin in (4,6)
group by osia.invoiceheader_id,osia.inventorydate, p.product_id ,sd.sizedefinition_id,fm.finishingmethod_id, d.customer_id
, il.billedqty, il.invoiceline_id, il.code, il.invoicelinetype_id, il.invoicelinesubtype

/
create or replace view V_INVOICE_CNAPPENDIX_RAS
 (CONSIGNMENTNOTENUMBER, INVOICEHEADER_ID)
as select distinct cn.consignmentnotenumber, pnl.invoiceheader_id
from
  ConsignmentNote cn, packingnote pn, packingnoteline pnl, status st
where pn.consignmentnote_id = cn.consignmentnote_id and pnl.packingnote_id = pn.packingnote_id
and (pn.status_id = st.status_id and st.code not in ('40','60') and st.statustype = 'PN')

/
create or replace view V_INVOICE_CN_PLS
 (CONSIGNMENTNOTENUMBER, INVOICEHEADER_ID)
as select distinct cn.consignmentnotenumber, ih.invoiceheader_id
from invoiceheader ih,
     packingnote pn ,
     packingnoteline pnl,
     consignmentnote cn
where ih.invoiceheader_id = pnl.invoiceheader_id
      and pnl.packingnote_id = pn.packingnote_id
			and pn.consignmentnote_id = cn.consignmentnote_id
      order by cn.consignmentnotenumber

/
create or replace view V_INVOICE_CN_REI
 (INVOICELINETYPE_ID, INVOICEHEADER_ID, DELIVERYDATE, CONSIGNMENTNOTENUMBER, QUANTITY, QUANTITYPNL, PRICE, WEIGHTDECIMALS, WEIGHTUNIT)
as select il.invoicelinetype_id, ih.invoiceheader_id, cn.deliverydate, cn.consignmentnotenumber,
       sum (pnc.GrossWeight - pnc.TareWeight) quantity, 0 quantitypnl,
       il.price,
       pnc.weightdecimals,
       s.value weightunit
from invoiceheader ih,
     packingnote pn , PackingNoteContainer pnc,
     consignmentnote cn, invoiceline il, invoicelineproduct ilp,
     systemsetting s, businessunit bu
where pn.consignmentnote_id = cn.consignmentnote_id
      and pn.processbusinessunit_id = bu.businessunit_id
      and s.name = 'WEIGHTUNIT'
      and s.plant_id = bu.plant_id
      and ih.invoiceheader_id = il.invoiceheader_id
      and il.generated = 'Y'
      and pnc.packingnote_id = pn.packingnote_id
      and ih.invoiceheader_id = pnc.invoiceheader_id
      and il.invoicelinetype_id =4
      and il.invoiceline_id = ilp.invoiceline_id
      and pnc.weighingcategory_id = ilp.weighingcategory_link_id
group by il.invoicelinetype_id, ih.invoiceheader_id, cn.deliverydate, cn.consignmentnotenumber, pnc.GrossWeight, pnc.TareWeight, il.price, pnc.weightdecimals, s.value
union
select il.invoicelinetype_id, ih.invoiceheader_id, cn.deliverydate, cn.consignmentnotenumber, 0 quantity,
       sum(pnl.deliveredamount - pnl.nodeliveryamount - pnl.nochargefirstissuecog - pnl.nochargefirstissue - pnl.nochargeactiveseason) quantitypnl,
       il.price,
      -- pack_price.Wash_Price(ih.deltocustomer_link_id, ilp.product_link_id, ilp.sizedefinition_link_id, ilp.finishingmethod_id, ih.invoicedate, 1) price,
       0 weightdecimals,
       s.value weightunit
from invoiceheader ih,
     packingnote pn,
     consignmentnote cn, invoiceline il, invoicelineproduct ilp,
     packingnoteline pnl,
     systemsetting s, businessunit bu
where ih.invoiceheader_id = pnl.invoiceheader_id
      and pnl.packingnote_id = pn.packingnote_id
      and pn.consignmentnote_id = cn.consignmentnote_id
      and pn.processbusinessunit_id = bu.businessunit_id
      and s.name = 'WEIGHTUNIT'
      and s.plant_id = bu.plant_id
      and ih.invoiceheader_id = il.invoiceheader_id
      and il.generated = 'Y'
      and il.invoicelinetype_id = 2
      and il.invoiceline_id = ilp.invoiceline_id
      and pnl.product_id = ilp.product_link_id
      and pnl.sizedefinition_id = ilp.sizedefinition_link_id
      and pnl.finishingmethod_id = ilp.finishingmethod_id
group by il.invoicelinetype_id, ih.invoiceheader_id, cn.deliverydate, cn.consignmentnotenumber, ih.deltocustomer_link_id, ilp.product_link_id, ilp.sizedefinition_link_id, ilp.finishingmethod_id, ih.invoicedate,il.price, s.value

/
create or replace view V_INVOICE_DNAPPENDIX_HDM
 (INVOICEHEADER_ID, NOTENUMBER, NOTEREMARK, SHOWONINVOICEAPPENDIX)
as select distinct pl.invoiceheader_id, pn.notenumber, pn.remark noteremark, pn.showoninvoiceappendix
  from Packingnote pn, status statusPN, packingnoteline pl
  where pn.status_id = statusPN.status_id
    and statusPN.statustype = 'PN'
    and statusPN.code = '30'
    and pl.packingnote_id = pn.packingnote_id

/
create or replace view V_INVOICE_DNAPPENDIX_REO
 (INVOICEHEADER_ID, NOTENUMBER)
as select --ih.invoiceheader_id
       distinct pnl.invoiceheader_id, pn.notenumber
from Packingnote pn, status statusPN--, invoiceheader ih
     , Packingnoteline pnl
where pn.status_id = statusPN.status_id
    and statusPN.statustype = 'PN'
        and statusPN.code = '30'
and pn.packingnote_id = pnl.packingnote_id
--and pn.invoiceheader_id = ih.invoiceheader_id
/
create or replace view V_INVOICE_DN_YOR
 (INVOICEHEADER_ID, DELIVERYDATE, NOTENUMBER, TOTALAMOUNTEXCLUDINGVAT, QUANTITY, VAT, TOTALAMOUNT)
as select pnl.invoiceheader_id, pn.deliverydate, pn.notenumber, pn.totalamountexcludingvat,
       sum(pnl.deliveredamount) quantity
       , (select pnt.amount from packingnotetax pnt where pnt.packingnote_id = pn.packingnote_id) vat
       , pn.totalamount
from packingnoteline pnl, packingnote pn
where pnl.packingnote_id = pn.packingnote_id
group by pnl.invoiceheader_id,  pn.packingnote_id, pn.deliverydate, pn.notenumber, pn.totalamountexcludingvat, pn.totalamount

/
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_INVOICE_WTSAPPENDIX_RAS
 (INVOICEHEADER_ID, TICKETNUMBER)
as select distinct wtl.invoiceheader_id, wt.ticketnumber
from WEIGHINGTICKET wt, weighingticketline wtl
where wt.soilticket = 'Y' and wtl.weighingticket_id = wt.weighingticket_id

/
create or replace view V_INVUSAGEANALYSIS13W_POS
 (BUSINESSUNIT, BU_DESCRIPTION, CUSTOMERNUMBER, CUSTOMERNAME, STREET, STREET2, CITY, STATE, ZIPCODE, WEARERNUMBER, DATEACTIVE, DATEINACTIVE, PRODUCTCODE, PRODUCTDESCRIPTION, SIZECODE, TOTALQTYDELIVERED, CIRCINVENTADJUSTMENTS, CIRCULATINGINVENTORY, REPLACEMENTS, REPLACEMENTSLOGGED, REPAIRPRODUCT)
as select --l.language_id,
       bu.code businessunit, bu.description bu_description, c.customernumber, c.name customername, a.street,
       a.street2, a.city, a.state, a.zipcode, w.wearernumber, wi.dateactive, wi.dateinactive,
       p.code productcode,
       (select pd.description from product_desc pd where wi.product_id = pd.product_id and pd.language_id=c.language_id) productdescription
      , s.code sizecode,
       nvl((select count(1)
            from   uniqueitem u, uniqueitemnonpool un, deliveryscan ds, packingnote pn
            where  u.businessunit_id = c.defaultbusinessunit_id
            and    u.uniqueitem_id = un.uniqueitem_id
            and    un.weareremployment_id = wi.weareremployment_id
            and    u.product_id = wi.product_id
            and    u.sizedefinition_id = wi.sizedefinition_id
            and    u.finishingmethod_id = wi.finishingmethod_id
            and    ds.packingnote_id is not null
            and    ds.uniqueitem_link_id = u.uniqueitem_id
            and    ds.packingnote_id = pn.packingnote_id
            and    pn.deliverydate between trunc(sysdate) - (13 * 7) and trunc(sysdate)), 0) totalqtydelivered,
       (nvl((select sum(ih.quantity)
             from   issuehistory ih, scan sc
             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    ih.incircdate between trunc(sysdate) - (13 * 7) and trunc(sysdate)
             and sc.scantimestamp = (select max(sc2.scantimestamp) from scan sc2 where sc2.uniqueitem_link_id = ih.uniqueitem_link_id)
             and ih.uniqueitem_link_id = sc.uniqueitem_link_id), 0) -
        nvl((select sum(oh.quantity)
             from   outofcirculationhistory oh
             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    oh.outofcircdate between trunc(sysdate) - (13 * 7) and trunc(sysdate)), 0)) circinventadjustments,
       (wi.circinventory + wi.freeofchargeqty -
        nvl((select sum(ih.quantity)
             from   issuehistory ih
             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    ih.incircdate > trunc(sysdate)), 0) +
        nvl((select sum(oh.quantity)
             from   outofcirculationhistory oh
             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    oh.outofcircdate > trunc(sysdate)), 0)) circulatinginventory,
       nvl((select sum(ih.quantity)
            from   issuehistory ih, workorder wo
            where  ih.processbusinessunit_id = c.defaultbusinessunit_id
            and    ih.weareremployment_link_id = wi.weareremployment_id
            and    ih.product_link_id = wi.product_id
            and    ih.sizedefinition_link_id = wi.sizedefinition_id
            and    wo.workorder_id = ih.workorder_id
            and    wo.replacement = 'Y'
            and    ih.incircdate between trunc(sysdate) - (4 * 7) and trunc(sysdate)), 0) replacements,
       nvl((select count(1)
            from   uniqueitem u, uniqueitemnonpool un, uniqueitemflag uf, automaticflag af
            where  u.businessunit_id = c.defaultbusinessunit_id
            and    u.uniqueitem_id = un.uniqueitem_id
            and    un.weareremployment_id = wi.weareremployment_id
            and    u.product_id = wi.product_id
            and    u.sizedefinition_id = wi.sizedefinition_id
            and    u.finishingmethod_id = wi.finishingmethod_id
            and    u.uniqueitem_id = uf.uniqueitem_id
            and    uf.flag_id = af.flag_id
            and    af.automaticflag_id = 4
            and    uf.startdate between trunc(sysdate) - (4 * 7) and trunc(sysdate)), 0) replacementslogged,
       nvl((select count(1)
            from   repairhistory rh, uniqueitem u
            where  rh.weareremployment_link_id = wi.weareremployment_id
            and    rh.uniqueitem_link_id = u.uniqueitem_id
            and    u.product_id = wi.product_id
            and    u.sizedefinition_id = wi.sizedefinition_id
            and    rh.product_link_id = wi.product_id
            and    rh.repairdate between trunc(sysdate) - (13 * 7) and trunc(sysdate)), 0) repairproduct
from   wearerinventory wi, weareremployment we, wearer w, customer c, address a, --languages l,
       product p, sizedefinition s, businessunit bu
where  wi.weareremployment_id = we.weareremployment_id
and    we.wearer_id = w.wearer_id
and    w.customer_id = c.customer_id
and    c.defaultbusinessunit_id = bu.businessunit_id
and    c.visitaddress_id = a.address_id
and    wi.product_id = p.product_id
and    wi.sizedefinition_id = s.sizedefinition_id--order  by c.customernumber, p.code, s.code

/
create or replace view V_INVUSAGEANALYSIS26W_POS
 (BUSINESSUNIT, BU_DESCRIPTION, CUSTOMERNUMBER, CUSTOMERNAME, STREET, STREET2, CITY, STATE, ZIPCODE, WEARERNUMBER, DATEACTIVE, DATEINACTIVE, PRODUCTCODE, PRODUCTDESCRIPTION, SIZECODE, TOTALQTYDELIVERED, CIRCINVENTADJUSTMENTS, CIRCULATINGINVENTORY, REPLACEMENTS, REPLACEMENTSLOGGED, REPAIRPRODUCT)
as select --l.language_id,
       bu.code businessunit, bu.description bu_description, c.customernumber, c.name customername, a.street,
       a.street2, a.city, a.state, a.zipcode, w.wearernumber, wi.dateactive, wi.dateinactive,
       p.code productcode,
       (select pd.description from product_desc pd where wi.product_id = pd.product_id and pd.language_id=c.language_id) productdescription
      , s.code sizecode,
       nvl((select count(1)
            from   uniqueitem u, uniqueitemnonpool un, deliveryscan ds, packingnote pn
            where  u.businessunit_id = c.defaultbusinessunit_id
            and    u.uniqueitem_id = un.uniqueitem_id
            and    un.weareremployment_id = wi.weareremployment_id
            and    u.product_id = wi.product_id
            and    u.sizedefinition_id = wi.sizedefinition_id
            and    u.finishingmethod_id = wi.finishingmethod_id
            and    ds.packingnote_id is not null
            and    ds.uniqueitem_link_id = u.uniqueitem_id
            and    ds.packingnote_id = pn.packingnote_id
            and    pn.deliverydate between trunc(sysdate) - (26 * 7) and trunc(sysdate)), 0) totalqtydelivered,
       (nvl((select sum(ih.quantity)
             from   issuehistory ih, scan sc
             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    ih.incircdate between trunc(sysdate) - (26 * 7) and trunc(sysdate)
             and sc.scantimestamp = (select max(sc2.scantimestamp) from scan sc2 where sc2.uniqueitem_link_id = ih.uniqueitem_link_id)
             and ih.uniqueitem_link_id = sc.uniqueitem_link_id), 0) -
        nvl((select sum(oh.quantity)
             from   outofcirculationhistory oh
             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    oh.outofcircdate between trunc(sysdate) - (26 * 7) and trunc(sysdate)), 0)) circinventadjustments,
       (wi.circinventory + wi.freeofchargeqty -
        nvl((select sum(ih.quantity)
             from   issuehistory ih
             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    ih.incircdate > trunc(sysdate)), 0) +
        nvl((select sum(oh.quantity)
             from   outofcirculationhistory oh
             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    oh.outofcircdate > trunc(sysdate)), 0)) circulatinginventory,
       nvl((select sum(ih.quantity)
            from   issuehistory ih, workorder wo
            where  ih.processbusinessunit_id = c.defaultbusinessunit_id
            and    ih.weareremployment_link_id = wi.weareremployment_id
            and    ih.product_link_id = wi.product_id
            and    ih.sizedefinition_link_id = wi.sizedefinition_id
            and    wo.workorder_id = ih.workorder_id
            and    wo.replacement = 'Y'
            and    ih.incircdate between trunc(sysdate) - (26 * 7) and trunc(sysdate)), 0) replacements,
       nvl((select count(1)
            from   uniqueitem u, uniqueitemnonpool un, uniqueitemflag uf, automaticflag af
            where  u.businessunit_id = c.defaultbusinessunit_id
            and    u.uniqueitem_id = un.uniqueitem_id
            and    un.weareremployment_id = wi.weareremployment_id
            and    u.product_id = wi.product_id
            and    u.sizedefinition_id = wi.sizedefinition_id
            and    u.finishingmethod_id = wi.finishingmethod_id
            and    u.uniqueitem_id = uf.uniqueitem_id
            and    uf.flag_id = af.flag_id
            and    af.automaticflag_id = 4
            and    uf.startdate between trunc(sysdate) - (26 * 7) and trunc(sysdate)), 0) replacementslogged,
       nvl((select count(1)
            from   repairhistory rh, uniqueitem u
            where  rh.weareremployment_link_id = wi.weareremployment_id
            and    rh.uniqueitem_link_id = u.uniqueitem_id
            and    u.product_id = wi.product_id
            and    u.sizedefinition_id = wi.sizedefinition_id
            and    rh.product_link_id = wi.product_id
            and    rh.repairdate between trunc(sysdate) - (26 * 7) and trunc(sysdate)), 0) repairproduct
from   wearerinventory wi, weareremployment we, wearer w, customer c, address a, --languages l,
       product p, sizedefinition s, businessunit bu
where  wi.weareremployment_id = we.weareremployment_id
and    we.wearer_id = w.wearer_id
and    w.customer_id = c.customer_id
and    c.defaultbusinessunit_id = bu.businessunit_id
and    c.visitaddress_id = a.address_id
and    wi.product_id = p.product_id
and    wi.sizedefinition_id = s.sizedefinition_id--order  by c.customernumber, p.code, s.code

/
create or replace view V_INVUSAGEANALYSIS52W_POS
 (BUSINESSUNIT, BU_DESCRIPTION, CUSTOMERNUMBER, CUSTOMERNAME, STREET, STREET2, CITY, STATE, ZIPCODE, WEARERNUMBER, DATEACTIVE, DATEINACTIVE, PRODUCTCODE, PRODUCTDESCRIPTION, SIZECODE, TOTALQTYDELIVERED, CIRCINVENTADJUSTMENTS, CIRCULATINGINVENTORY, REPLACEMENTS, REPLACEMENTSLOGGED, REPAIRPRODUCT)
as select --l.language_id,
       bu.code businessunit, bu.description bu_description, c.customernumber, c.name customername, a.street,
       a.street2, a.city, a.state, a.zipcode, w.wearernumber, wi.dateactive, wi.dateinactive,
       p.code productcode,
       (select pd.description from product_desc pd where wi.product_id = pd.product_id and pd.language_id=c.language_id) productdescription
      , s.code sizecode,
       nvl((select count(1)
            from   uniqueitem u, uniqueitemnonpool un, deliveryscan ds, packingnote pn
            where  u.businessunit_id = c.defaultbusinessunit_id
            and    u.uniqueitem_id = un.uniqueitem_id
            and    un.weareremployment_id = wi.weareremployment_id
            and    u.product_id = wi.product_id
            and    u.sizedefinition_id = wi.sizedefinition_id
            and    u.finishingmethod_id = wi.finishingmethod_id
            and    ds.packingnote_id is not null
            and    ds.uniqueitem_link_id = u.uniqueitem_id
            and    ds.packingnote_id = pn.packingnote_id
            and    pn.deliverydate between trunc(sysdate) - (52 * 7) and trunc(sysdate)), 0) totalqtydelivered,
       (nvl((select sum(ih.quantity)
             from   issuehistory ih, scan sc
             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    ih.incircdate between trunc(sysdate) - (52 * 7) and trunc(sysdate)
             and sc.scantimestamp = (select max(sc2.scantimestamp) from scan sc2 where sc2.uniqueitem_link_id = ih.uniqueitem_link_id)
             and ih.uniqueitem_link_id = sc.uniqueitem_link_id), 0) -
        nvl((select sum(oh.quantity)
             from   outofcirculationhistory oh
             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    oh.outofcircdate between trunc(sysdate) - (52 * 7) and trunc(sysdate)), 0)) circinventadjustments,
       (wi.circinventory + wi.freeofchargeqty -
        nvl((select sum(ih.quantity)
             from   issuehistory ih
             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    ih.incircdate > trunc(sysdate)), 0) +
        nvl((select sum(oh.quantity)
             from   outofcirculationhistory oh
             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    oh.outofcircdate > trunc(sysdate)), 0)) circulatinginventory,
       nvl((select sum(ih.quantity)
            from   issuehistory ih, workorder wo
            where  ih.processbusinessunit_id = c.defaultbusinessunit_id
            and    ih.weareremployment_link_id = wi.weareremployment_id
            and    ih.product_link_id = wi.product_id
            and    ih.sizedefinition_link_id = wi.sizedefinition_id
            and    wo.workorder_id = ih.workorder_id
            and    wo.replacement = 'Y'
            and    ih.incircdate between trunc(sysdate) - (52 * 7) and trunc(sysdate)), 0) replacements,
       nvl((select count(1)
            from   uniqueitem u, uniqueitemnonpool un, uniqueitemflag uf, automaticflag af
            where  u.businessunit_id = c.defaultbusinessunit_id
            and    u.uniqueitem_id = un.uniqueitem_id
            and    un.weareremployment_id = wi.weareremployment_id
            and    u.product_id = wi.product_id
            and    u.sizedefinition_id = wi.sizedefinition_id
            and    u.finishingmethod_id = wi.finishingmethod_id
            and    u.uniqueitem_id = uf.uniqueitem_id
            and    uf.flag_id = af.flag_id
            and    af.automaticflag_id = 4
            and    uf.startdate between trunc(sysdate) - (52 * 7) and trunc(sysdate)), 0) replacementslogged,
       nvl((select count(1)
            from   repairhistory rh, uniqueitem u
            where  rh.weareremployment_link_id = wi.weareremployment_id
            and    rh.uniqueitem_link_id = u.uniqueitem_id
            and    u.product_id = wi.product_id
            and    u.sizedefinition_id = wi.sizedefinition_id
            and    rh.product_link_id = wi.product_id
            and    rh.repairdate between trunc(sysdate) - (52 * 7) and trunc(sysdate)), 0) repairproduct
from   wearerinventory wi, weareremployment we, wearer w, customer c, address a, --languages l,
       product p, sizedefinition s, businessunit bu
where  wi.weareremployment_id = we.weareremployment_id
and    we.wearer_id = w.wearer_id
and    w.customer_id = c.customer_id
and    c.defaultbusinessunit_id = bu.businessunit_id
and    c.visitaddress_id = a.address_id
and    wi.product_id = p.product_id
and    wi.sizedefinition_id = s.sizedefinition_id --order  by c.customernumber, p.code, s.code

/
create or replace view V_INV_APPENDIX_KAV_SMG
 (INVOICEDATE, INVOICENUMBER, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, TOTALAMOUNTEXCLVAT, TYPEGROUP, TYPEGROUPSORT, BILLEDQTY, AMOUNT, INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, STREET, ZIPCODE, CITY, BILLTOCOUNTRYDESCRIPTION, DELTOCUSTVATNR, BILLTOSENDINVOICETO, DELTOCUSTNOLEGALNAME, CUSTTYPE, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTDATE, ENDDATE, INVOICEFREQUENCY_ID, PLANTCOUNTRYDESCRIPTION, STARTYEAR
, ENDYEAR)
as select   ih.invoicedate
,        ih.invoicenumber
,        ih.billtocustomernumber
,        ih.billtocustomername
,        ih.extraname1
,        ih.extraname2
,        ih.deltocustomernumber
,        ih.deltocustomername
,        ih.totalamountexclvat
,        pg.code TypeGroup
,        DECODE(pg.code, 'AK', 1, 'HRK', 1, 'OPK', 2, 'STEP', 3, 4) TypeGroupSort
,        il.billedqty
,        il.amount
,        ih.Invoiceheader_id
,        ih.ParentInvoiceheader_id
,        ih.street
,        ih.zipcode
,        ih.city
,        ( select ihextr.billtocountrydescription
           from   invoiceheaderextrainfo ihextr
           where  ihextr.invoiceheader_id = ih.invoiceheader_id) billtocountrydescription
,        ( select c.vatnumber
           from   customer c
           where  c.customer_id = ih.deltocustomer_link_id) deltocustvatnr
,        ( select c.sendinvoiceto
           from   customer c
	       where  ih.deltocustomer_link_id = c.customer_id) billtosendinvoiceto
,        ( select c.customernumber || ' ' || c.legalname
           from   customer c
           where  c.customer_id = ih.deltocustomer_link_id) deltocustnolegalname
,        F_GetCustType_smg(ih.invoiceheader_id) custtype
,        ih.startweek
,        ih.endweek
,        ih.startmonth
,        ih.endmonth
,        ih.startdate
,        ih.enddate
,        ih.invoicefrequency_id
,        ( select co.description
           from   businessunit bu
           ,      plant pl
		   ,      country co
           where  ih.invoicebusinessunit_id = bu.businessunit_id
		      and bu.plant_id = pl.plant_id
			  and pl.country_id = co.country_id ) PlantCountryDescription
,        ih.startyear
,        ih.endyear
from     invoiceheader ih
,        invoiceline il
,        product p
,        productgroup pg
,        productgroup_desc pgd
where    ih.invoiceheader_id = il.invoiceheader_id
     and p.code = il.code
     and p.productgroup_id = pg.productgroup_id
     and pg.productgroup_id = pgd.productgroup_id
     and pgd.language_id = 1
     and il.invoicelinetype_id <> 18 -- ohne Steuer
UNION ALL
select   ih.invoicedate
,        ih.invoicenumber
,        ih.billtocustomernumber
,        ih.billtocustomername
,        ih.extraname1
,        ih.extraname2
,        ih.deltocustomernumber
,        ih.deltocustomername
,        ih.totalamountexclvat
,        'Wiegen' TypeGroup
, 5 TypeGroupSort
,        il.billedqty
,        il.amount
,        ih.Invoiceheader_id
,        ih.ParentInvoiceheader_id
,        ih.street
,        ih.zipcode
,        ih.city
,        ( select ihextr.billtocountrydescription
           from   invoiceheaderextrainfo ihextr
           where  ihextr.invoiceheader_id = ih.invoiceheader_id) billtocountrydescription
,        ( select c.vatnumber
           from   customer c
           where  c.customer_id = ih.deltocustomer_link_id) deltocustvatnr
,        ( select c.sendinvoiceto
           from   customer c
	       where  ih.deltocustomer_link_id = c.customer_id) billtosendinvoiceto
,        ( select c.customernumber || ' ' || c.legalname
           from   customer c
           where  c.customer_id = ih.deltocustomer_link_id) deltocustnolegalname
,        F_GetCustType_smg(ih.invoiceheader_id) custtype
,        ih.startweek
,        ih.endweek
,        ih.startmonth
,        ih.endmonth
,        ih.startdate
,        ih.enddate
,        ih.invoicefrequency_id
,        ( select co.description
           from   businessunit bu
           ,      plant pl
		   ,      country co
           where  ih.invoicebusinessunit_id = bu.businessunit_id
		      and bu.plant_id = pl.plant_id
			  and pl.country_id = co.country_id ) PlantCountryDescription
,        ih.startyear
,        ih.endyear
from     invoiceheader ih
,        invoiceline il
where    ih.invoiceheader_id = il.invoiceheader_id
     and il.code NOT IN (select p.code from product p)
     and il.code IN (select w.code from weighingcategory w)
     and il.invoicelinetype_id <> 18 -- ohne Steuer
UNION ALL
select   ih.invoicedate
,        ih.invoicenumber
,        ih.billtocustomernumber
,        ih.billtocustomername
,        ih.extraname1
,        ih.extraname2
,        ih.deltocustomernumber
,        ih.deltocustomername
,        ih.totalamountexclvat
,        'Sonstiges'  TypeGroup
,        6 TypeGroupSort
,        il.billedqty
,        il.amount
,        ih.Invoiceheader_id
,        ih.ParentInvoiceheader_id
,        ih.street
,        ih.zipcode
,        ih.city
,        ( select ihextr.billtocountrydescription
           from   invoiceheaderextrainfo ihextr
           where  ihextr.invoiceheader_id = ih.invoiceheader_id) billtocountrydescription
,        ( select c.vatnumber
           from   customer c
           where  c.customer_id = ih.deltocustomer_link_id) deltocustvatnr
,        ( select c.sendinvoiceto
           from   customer c
	       where  ih.deltocustomer_link_id = c.customer_id) billtosendinvoiceto
,        ( select c.customernumber || ' ' || c.legalname
           from   customer c
           where  c.customer_id = ih.deltocustomer_link_id) deltocustnolegalname
,        F_GetCustType_smg(ih.invoiceheader_id) custtype
,        ih.startweek
,        ih.endweek
,        ih.startmonth
,        ih.endmonth
,        ih.startdate
,        ih.enddate
,        ih.invoicefrequency_id
,        ( select co.description
           from   businessunit bu
           ,      plant pl
		   ,      country co
           where  ih.invoicebusinessunit_id = bu.businessunit_id
		      and bu.plant_id = pl.plant_id
			  and pl.country_id = co.country_id ) PlantCountryDescription
,        ih.startyear
,        ih.endyear
from     invoiceheader ih
,        invoiceline il
where    ih.invoiceheader_id = il.invoiceheader_id
     and il.invoicelinetype_id <> 18
     and il.code NOT IN (select p.code from product p)
     and il.code NOT IN (select w.code from weighingcategory w)

/
create or replace view V_INV_COSTCENTER_VOES_SMG
 (INVOICENUMBER, INVOICEDATE, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, COSTCENTERDESC, INVOICELINECODE, INVOICELINEDESC, BILLEDQTY, AMOUNT, CHAINCODE, BILLTOCUSTOMERNUMBER, INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, PARENTINVOICENUMBER)
as select ih.invoicenumber
,      ih.invoicedate
,      ih.deltocustomernumber
,      (select cu.name from customer cu where cu.customer_id=ih.deltocustomer_link_id) deltocustomername
,      co.description Costcenterdesc
,      il.code InvoicelineCode
,      il.description InvoicelineDesc
,      il.billedqty
,      il.amount
,      ch.code ChainCode
,      ih.BilltoCustomernumber
,      ih.Invoiceheader_id
,      ih.ParentInvoiceheader_id
,      ( CASE WHEN (ih.parentinvoiceheader_id is null)
              THEN ih.invoicenumber
              ELSE ( select i.invoicenumber
                     from   invoiceheader i
		             where  i.invoiceheader_id = ih.parentinvoiceheader_id )
         END ) ParentInvoiceNumber
from   invoiceheader ih
,      invoiceline il
,      customer c
,      chain ch
,      costcenterinvoiceline ic
,      costcenter_link cl
,      costcenter co
where  ih.invoiceheader_id = il.invoiceheader_id
   and ih.billtocustomernumber = c.customernumber
   and ch.chain_id = c.chain_id
   and ic.invoiceline_id = il.invoiceline_id
   and ic.costcenter_link_id = cl.costcenter_link_id
   and co.costcenter_id = cl.costcenter_id
   and ch.code like 'VOES%'

/
create or replace view V_INV_GARMCHARGES_SMG
 (INVOICENUMBER, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, CITY, ZIPCODE, STREET, STREET2, CURRENCYCODE, INVOICEHEADER_ID, INVOICEAMOUNTDECIMALS, BILLTOCOUNTRYDESCRIPTION, PLANTCOUNTRYDESCRIPTION, DELTOCUSTNOLEGALNAME, DELTOCUSTVATNR, BILLTOSENDINVOICETO, CUSTTYPE, PARENTINVOICEHEADER_ID, PRINTINVOICENUMBER, INVOICEDATE, BILLTOCUSTOMER_LINK_ID, BILTOCUSTVATNR, LEGALENTITY_LEGALNAME
, LEGALENTITY_ID, PLANT_STREET, PLANT_STREET2, PLANT_ZIPCODE, PLANT_CITY, PLANT_STATE, PLANT_PHONENO, PLANT_FAXNO, PLANT_WEBSITE, PLANT_EMAIL)
as select ih.invoicenumber
,      ih.billtocustomernumber
,      ih.billtocustomername
,      ih.extraname1
,      ih.extraname2
,      ih.deltocustomernumber
,      ih.deltocustomername
,      ih.startweek
,      ih.endweek
,      ih.startmonth
,      ih.endmonth
,      ih.city
,      ih.zipcode
,      ih.street
,      ih.street2
,      cur.code currencycode
,      ih.invoiceheader_id
,      cur.invoiceamountdecimals
,      ihextr.billtocountrydescription
,      co.description plantcountrydescription
,      ( select cu.customernumber || ' ' || cu.legalname
         from   customer cu
         where  cu.customer_id = ih.deltocustomer_link_id ) deltocustnolegalname
,      ( select cu.vatnumber
         from   customer cu
         where  cu.customer_id = ih.deltocustomer_link_id ) deltocustvatnr
,      ( select cu.sendinvoiceto
         from   customer cu
	     where  cu.customer_id = ih.deltocustomer_link_id ) billtosendinvoiceto
,      F_GetCustType_smg(ih.invoiceheader_id) custtype
,      ih.parentinvoiceheader_id
,      ( select ih2.invoicenumber
         from   invoiceheader ih2
         where  ih2.invoiceheader_id = coalesce(ih.parentinvoiceheader_id, ih.invoiceheader_id) ) printInvoiceNumber
, ih.invoicedate, ih.billtocustomer_link_id
, (select deb.vatnumber from customer deb where deb.customer_id = ih.billtocustomer_link_id) biltocustvatnr
, (select le.legalname from legalentity le where le.legalentity_id = bu.legalentity_id) LegalEntity_LegalName
, (select le.legalentity_id from legalentity le where le.legalentity_id = bu.legalentity_id) LegalEntity_ID
, pad.street plant_street, pad.street2 plant_street2, pad.zipcode plant_zipcode, pad.city plant_city
, pad.state plant_state, p.phoneno plant_phoneno, p.faxno plant_faxno, p.website plant_website, p.email plant_email
from   currency cur
,      businessunit bu
,      plant p
,      country co
,      invoiceheader ih
,      invoiceheaderextrainfo ihextr, address pad
where ih.currency_id = cur.currency_id
  and ih.documenttype = 1
  and ih.invoicebusinessunit_id = bu.businessunit_id
  and bu.plant_id = p.plant_id
  and p.country_id = co.country_id
  and ih.invoiceheader_id = ihextr.invoiceheader_id
  and pad.address_id = p.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_ISSUEHISTORYCC
 (YEAR, WEEK, DEPARTMENTNUMBER, DEPARTMENTDESC, WEARERNUMBER, WEARERNAME, PRODUCTCODE, PRODUCTDESC, SIZEDEFINITIONCODE, SIZEDEFINITIONDESC, QUANTITY, PREPCHARGE, INVOICEHEADER_ID, LANGUAGECODE, CC_CODE_DESC)
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,
(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_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_ITEMHISTORY_LLG
 (CUSTOMERNUMBER, SEARCHNAME, NAME, NOTENUMBER, PN_DELIVERYDATE, DV_DELIVERYDATE, PRODUCTCODE, PRODUCTDESCRIPTION, SIZECODE, DV_SOILCOUNT, DV_INCREASE_DECREASE, DELIVEREDAMOUNT, NOMINALQTY, LOANQTY, LANGUAGECODE, RC_CODE, BUCODE, BU_DESCRIPTION)
as select c.customernumber,
       c.searchname,
       c.name,
       pn.notenumber,
       pn.deliverydate pn_deliverydate,
       dv.deliverydate dv_deliverydate,
       p.code productcode,
       (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = l.language_id) productdescription,
       (select sd.code from sizedefinition sd where sd.sizedefinition_id = pnl.sizedefinition_id) sizecode,
       nvl((select sum(dv1.amount)
               from deliveryvariations dv1
               where dv1.origin = 1
               and dv1.product_id = pnl.product_id
               and dv1.sizedefinition_id = pnl.sizedefinition_id
               and dv1.finishingmethod_id = pnl.finishingmethod_id
               and dv1.packingnote_id = pn.packingnote_id
        ), 0) dv_soilcount,
       nvl((select sum(dv2.amount)
               from deliveryvariations dv2
               where dv2.origin <> 1
               and dv2.product_id = pnl.product_id
               and dv2.sizedefinition_id = pnl.sizedefinition_id
               and dv2.finishingmethod_id = pnl.finishingmethod_id
               and dv2.packingnote_id = pn.packingnote_id
        ),0) dv_increase_decrease,
        pnl.deliveredamount,
       nvl((select sum(rqa.quantity)
                   from rentalqtyadjustment rqa, productlistperdistribpoint plpd
                        where rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
                              and plpd.product_id = pnl.product_id
                              and plpd.sizedefinition_id = pnl.sizedefinition_id
                              and plpd.finishingmethod_id = pnl.finishingmethod_id
                              and plpd.distributionpoint_id = pn.distributionpoint_id
                              and rqa.origin <> 2
                              and rqa.adjustmentdate <= pn.deliverydate),0) nominalqty,
        nvl((select sum(rqa.quantity)
                   from rentalqtyadjustment rqa, productlistperdistribpoint plpd
                        where rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
                              and plpd.product_id = pnl.product_id
                              and plpd.sizedefinition_id = pnl.sizedefinition_id
                              and plpd.finishingmethod_id = pnl.finishingmethod_id
                              and plpd.distributionpoint_id = pn.distributionpoint_id
                              and rqa.origin = 2
                              and rqa.adjustmentdate <= pn.deliverydate),0) loanqty,
        l.code languagecode,
        (select rc.code from reasoncode rc where rc.reasoncode_id = dv.reasoncode_id) rc_code,
        bu.code bucode,
        bu.description bu_description
  from deliveryvariations dv,
       packingnote        pn,
       packingnoteline    pnl,
       customer c,
       department d,
       distributionpoint dp,
       product p,
       languages l,
       businessunit bu
 where dv.packingnote_id = pn.packingnote_id
   and pn.packingnote_id = pnl.packingnote_id
   and bu.businessunit_id = pn.processbusinessunit_id
   and pn.distributionpoint_id = dp.distributionpoint_id
   and dp.department_id = d.department_id
   and d.customer_id = c.customer_id
   and pnl.product_id = p.product_id
   and dv.product_id = pnl.product_id
   and dv.sizedefinition_id = pnl.sizedefinition_id
   and dv.finishingmethod_id = pnl.finishingmethod_id
   and pn.status_id = (select s.status_id from status s where s.statustype = 'PN' and s.code = 30)

/
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_KOSTENSTELLENAUFSTELLUNG_SMG
 (INVOICEHEADER_ID, STARTWEEK, ENDWEEK, INVOICENUMBER, CUSTOMEREMPLOYEENUMBER, WEEK, NETPRICE, CUSTTYPE, BILLTOSENDINVOICETO, BILLTOCUSTOMERNUMBER, DELTOCUSTOMERNUMBER, PARENTINVOICEHEADER_ID)
as select z.invoiceheader_id, z.startweek, z.endweek, z.invoicenumber, z.customeremployeenumber, z.week, sum(z.netprice) netprice, z.custtype, z.billtosendinvoiceto, z.billtocustomernumber, z.deltocustomernumber, z.parentinvoiceheader_id
from   ( --union for size = * for RENT
          select --+ INDEX(sq, TIDXSQITEMINCIRCULATION) INDEX(ilp, XPKINVOICELINEPRODUCT) INDEX(qh, XPKSTATUSQUOHEADER) INDEX(we, XPKWEAREREMPLOYMENT_LINK)
                 ih.invoiceheader_id, ih.startweek, ih.endweek, coalesce((select ihp.invoicenumber from invoiceheader ihp where ihp.invoiceheader_id = ih.parentinvoiceheader_id), ih.invoicenumber) invoicenumber,
        ( select w.customeremployeenumber from wearer w where w.wearernumber=we.wearernumber and w.customer_id=c.customer_id) customeremployeenumber, qh.week,
                sum(sq.qtyrentedperpiece * il.price) netprice --sum(sq.maxinv * il.price) netprice
                , F_GetCustType_smg(ih.invoiceheader_id) custtype,
                 c.sendinvoiceto billtosendinvoiceto, ih.billtocustomernumber, ih.deltocustomernumber, ih.parentinvoiceheader_id
         from   invoiceheader ih, invoiceline il, invoicelineproduct ilp, customer c, chain ch,
                 weareremployment_link we, statusquoheader qh, sqitemincirculation sq
         where  ih.invoiceheader_id = il.invoiceheader_id
         and    il.invoiceline_id = ilp.invoiceline_id
         and    ih.deltocustomer_link_id = c.customer_id
         and    il.invoicelinetype_id = 1 -- rent
         and    c.chain_id = ch.chain_id
         and    ch.code in ('CEME', 'CEMF')
         and    qh.statusquodate between ih.startdate and ih.enddate
         and    qh.statusquotype = 1
         and    sq.statusquoheader_id = qh.statusquoheader_id
         and    sq.weareremployment_link_id = we.weareremployment_link_id
         and    (( select d.customer_link_id from distributionpoint_link dp, department_link d where we.distributionpoint_link_id=dp.distributionpoint_id
                and dp.department_link_id=d.department_link_id)=c.customer_id)
         and    ih.deltocustomer_link_id = c.customer_id
         and    ilp.product_link_id = sq.product_link_id
         and    ilp.sizedefinition_link_id =
                (select sx.sizedefinition_id from sizedefinition sx where sx.code = '*')
         and    ilp.finishingmethod_id = sq.finishingmethod_id
         and   (ih.splitupcode is null or ih.splitupcode=(select cc.code from distributionpoint dp, costcenter cc
              where  we.distributionpoint_link_id=dp.distributionpoint_id and dp.costcenter_id = cc.costcenter_id))
         and    not exists (select 1
                 from   invoiceline ilz, invoicelineproduct ilpz
                 where  ilz.invoiceheader_id = ih.invoiceheader_id
                 and    ilz.invoiceline_id = ilpz.invoiceline_id
                 and    ilpz.product_link_id = ilp.product_link_id
                 and    ilpz.sizedefinition_link_id = sq.sizedefinition_link_id
                 and    ilpz.finishingmethod_id = sq.finishingmethod_id)
         group by ih.invoiceheader_id,ih.startweek, ih.endweek, ih.parentinvoiceheader_id, ih.invoicenumber,we.wearernumber,c.customer_id ,qh.week, c.sendinvoiceto, ih.billtocustomernumber, ih.deltocustomernumber, ih.parentinvoiceheader_id
         union all --union for size <> * for RENT
         select --+ INDEX(sq, TIDXSQITEMINCIRCULATION) INDEX(ilp, XPKINVOICELINEPRODUCT) INDEX(qh, XPKSTATUSQUOHEADER) INDEX(we, XPKWEAREREMPLOYMENT_LINK)
                ih.invoiceheader_id,ih.startweek, ih.endweek,  coalesce((select ihp.invoicenumber from invoiceheader ihp where ihp.invoiceheader_id = ih.parentinvoiceheader_id), ih.invoicenumber) invoicenumber,
              ( select w.customeremployeenumber from wearer w where w.wearernumber=we.wearernumber and w.customer_id=c.customer_id) customeremployeenumber, qh.week,
                sum(sq.qtyrentedperpiece * il.price) netprice, F_GetCustType_smg(ih.invoiceheader_id) custtype, c.sendinvoiceto billtosendinvoiceto, ih.billtocustomernumber, ih.deltocustomernumber, ih.parentinvoiceheader_id
         from   invoiceheader ih, invoiceline il, invoicelineproduct ilp, customer c, chain ch,
                weareremployment_link we, statusquoheader qh, sqitemincirculation sq
         where  ih.invoiceheader_id = il.invoiceheader_id
         and    il.invoiceline_id = ilp.invoiceline_id
         and    ih.deltocustomer_link_id = c.customer_id
         and    il.invoicelinetype_id = 1 -- rent
         and    c.chain_id = ch.chain_id
         and    ch.code in ('CEME', 'CEMF')
         and    qh.statusquodate between ih.startdate and ih.enddate
         and    qh.statusquotype = 1
         and    sq.statusquoheader_id = qh.statusquoheader_id
         and    sq.weareremployment_link_id = we.weareremployment_link_id
          and    (( select d.customer_link_id from distributionpoint_link dp, department_link d where we.distributionpoint_link_id=dp.distributionpoint_id
                and dp.department_link_id=d.department_link_id)=c.customer_id)
         and    ih.deltocustomer_link_id = c.customer_id
         and    ilp.product_link_id = sq.product_link_id
         and    ilp.sizedefinition_link_id = sq.sizedefinition_link_id
         and    ilp.sizedefinition_link_id <>
                (select sx.sizedefinition_id from sizedefinition sx where sx.code = '*')
         and    ilp.finishingmethod_id = sq.finishingmethod_id
         and   (ih.splitupcode is null or  ih.splitupcode=(select cc.code from distributionpoint dp, costcenter cc
              where  we.distributionpoint_link_id=dp.distributionpoint_id and dp.costcenter_id=cc.costcenter_id))
         group  by ih.invoiceheader_id,ih.startweek, ih.endweek,  ih.parentinvoiceheader_id, ih.invoicenumber,we.wearernumber,c.customer_id ,qh.week, c.sendinvoiceto, ih.billtocustomernumber, ih.deltocustomernumber, ih.parentinvoiceheader_id
       union all --union for WASH deliveryscan
        select  --+ INDEX(ilp, XPKINVOICELINEPRODUCT) INDEX(pk, XPKPACKINGNOTE)
                ih.invoiceheader_id,ih.startweek, ih.endweek,  coalesce((select ihp.invoicenumber from invoiceheader ihp where ihp.invoiceheader_id = ih.parentinvoiceheader_id), ih.invoicenumber) invoicenumber,
         ( select w.customeremployeenumber from wearer w where w.wearernumber=we.wearernumber and w.customer_id=c.customer_id) customeremployeenumber, pk.week,
                sum((select count(1)
                      from   deliveryscan ds, uniqueitem u, uniqueitemnonpool un
                      where  ds.uniqueitem_link_id = u.uniqueitem_id
                      and    ds.uniqueitem_link_id = un.uniqueitem_id
                      and    u.product_id = pkl.product_id
                      and    u.sizedefinition_id = pkl.sizedefinition_id
                      and    u.finishingmethod_id = pkl.finishingmethod_id
                      and    ds.weareremployment_link_id = we.weareremployment_link_id
                      and    pk.packingnote_id = ds.packingnote_id) * il.price) netprice, F_GetCustType_smg(ih.invoiceheader_id) custtype, c.sendinvoiceto billtosendinvoiceto, ih.billtocustomernumber, ih.deltocustomernumber, ih.parentinvoiceheader_id
         from   invoiceheader ih
         join   invoiceline il on (ih.invoiceheader_id = il.invoiceheader_id and il.invoicelinetype_id = 2) -- wash
         join   invoicelineproduct ilp on ilp.invoiceline_id = il.invoiceline_id
         join   customer c on ih.deltocustomer_link_id = c.customer_id
         join   chain ch on c.chain_id = ch.chain_id
         left outer  join weareremployment_link we on we.weareremployment_link_id = ilp.weareremployment_link_id,
         packingnote pk, packingnoteline pkl
         where  ch.code in ('CEME', 'CEMF')
         and    ih.invoiceheader_id = pkl.invoiceheader_id
         and    pk.packingnote_id = pkl.packingnote_id
         and    ilp.product_link_id = pkl.product_id
         and    ilp.sizedefinition_link_id = pkl.sizedefinition_id
         and    ilp.finishingmethod_id = pkl.finishingmethod_id
         and   (ih.splitupcode is null or  ih.splitupcode=(select cc.code from distributionpoint dp, costcenter cc
              where  we.distributionpoint_link_id=dp.distributionpoint_id and dp.costcenter_id=cc.costcenter_id))
         group  by ih.invoiceheader_id,ih.startweek, ih.endweek,  ih.parentinvoiceheader_id, ih.invoicenumber, c.customer_id,we.wearernumber ,pk.week, c.sendinvoiceto, ih.billtocustomernumber, ih.deltocustomernumber, ih.parentinvoiceheader_id
         having sum((select count(1)
                     from   deliveryscan ds, uniqueitem u, uniqueitemnonpool un
                     where  ds.uniqueitem_link_id = u.uniqueitem_id
                     and    ds.uniqueitem_link_id = un.uniqueitem_id
                     and    u.product_id = pkl.product_id
                     and    u.sizedefinition_id = pkl.sizedefinition_id
                     and    u.finishingmethod_id = pkl.finishingmethod_id
                     and    ds.weareremployment_link_id= we.weareremployment_link_id
                     and    pk.packingnote_id = ds.packingnote_id) * il.price) > 0) z
group  by z.invoiceheader_id,z.startweek, z.endweek, z.invoicenumber, z.customeremployeenumber, z.week, z.custtype, z.billtosendinvoiceto, z.billtocustomernumber, z.deltocustomernumber, z.parentinvoiceheader_id
order  by z.invoiceheader_id,z.startweek, z.endweek, z.invoicenumber, z.customeremployeenumber, z.week, z.custtype, z.billtosendinvoiceto, z.billtocustomernumber, z.deltocustomernumber, z.parentinvoiceheader_id

/
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, 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 CU.CUSTOMERNUMBER,
       CU.NAME customername,
       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 A.DESCRIPTION FROM PRODUCTGROUP_DESC A WHERE A.PRODUCTGROUP_ID = PG.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 = X.PRODUCT_LINK_ID
           AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
       PR.typeofmerchandise,
       SZL.CODE sizecode,
       (SELECT S.DESCRIPTION
          FROM SIZEDEFINITION_LINK_DESC S
         WHERE S.SIZEDEFINITION_LINK_ID = X.SIZEDEFINITION_LINK_ID
           AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) sizedescription,
       FM.CODE finishingmethodcode,
       (SELECT D.DESCRIPTION
          FROM FINISHINGMETHOD_DESC D
         WHERE D.FINISHINGMETHOD_ID = X.FINISHINGMETHOD_ID
           AND D.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODdescription,
       X.year * 100 + X.week YEARWEEK,
       X.WEEK, X.DELIVERYDATE,
       sum(X.AMOUNTDELIVERED) DELIVEREDQTY,
       LANGUAGES.CODE LANGUAGECODE,
       RP.REPORTPARAM_ID
FROM DELIVERYHISTORY X
  INNER JOIN DISTRIBUTIONPOINT_LINK DPL
        INNER JOIN DEPARTMENT_LINK DEL
              INNER JOIN CUSTOMER CU
                    INNER 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 X.DISTRIBUTIONPOINT_LINK_ID = DPL.DISTRIBUTIONPOINT_LINK_ID
  INNER JOIN PRODUCT PR
        INNER JOIN PRODUCTGROUP PG ON PR.PRODUCTGROUP_ID = PG.PRODUCTGROUP_ID
  ON X.PRODUCT_LINK_ID = PR.PRODUCT_ID
  INNER JOIN SIZEDEFINITION_LINK SZL ON X.SIZEDEFINITION_LINK_ID = SZL.SIZEDEFINITION_LINK_ID
  INNER JOIN FINISHINGMETHOD FM ON X.FINISHINGMETHOD_ID = FM.FINISHINGMETHOD_ID,
  LANGUAGES,
  REPORTPARAM RP
WHERE trunc(X.DELIVERYDATE) >= trunc(RP.DATE_VALUE1) AND trunc(X.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 LANGUAGES.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 X.PACKINDICATION IN (1, 2)
group by CU.CUSTOMERNUMBER, CU.NAME, VAD.STREET, VAD.STREET2, VAD.ZIPCODE, VAD.CITY,
       DEL.DEPARTMENTNUMBER, DEL.DESCRIPTION, DPL.DISTRIBUTIONPOINTNUMBER,
       DPL.DESCRIPTION, PG.CODE, PG.PRODUCTGROUP_ID, LANGUAGES.LANGUAGE_ID,
       PR.CODE, X.PRODUCT_LINK_ID, PR.typeofmerchandise, SZL.CODE, X.SIZEDEFINITION_LINK_ID,
       FM.CODE, X.FINISHINGMETHOD_ID, X.year, X.WEEK, X.DELIVERYDATE, LANGUAGES.CODE, RP.REPORTPARAM_ID

/
create or replace view V_LAST12WEEKS_LLG
 (CUSTOMERNUMBER, CUSTOMERNAME, STREET, ZIPCODE, CITY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PRODUCTCODE, PRODUCTDESCRIPTION, TYPEOFMERCHANDISE, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODCODE, FINISHINGMETHODDESCRIPTION, YEARWEEK, WEEK, DELIVERYDATE, DELIVEREDQTY, LANGUAGECODE, REPORTPARAM_ID, CHARGEABLE_CIRC_INVENTORY)
as SELECT CU.CUSTOMERNUMBER,
       CU.NAME customername,
       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 A.DESCRIPTION FROM PRODUCTGROUP_DESC A WHERE A.PRODUCTGROUP_ID = PG.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 = X.PRODUCT_LINK_ID
           AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
       PR.typeofmerchandise,
       SZL.CODE sizecode,
       (SELECT S.DESCRIPTION
          FROM SIZEDEFINITION_LINK_DESC S
         WHERE S.SIZEDEFINITION_LINK_ID = X.SIZEDEFINITION_LINK_ID
           AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) sizedescription,
       FM.CODE finishingmethodcode,
       (SELECT D.DESCRIPTION
          FROM FINISHINGMETHOD_DESC D
         WHERE D.FINISHINGMETHOD_ID = X.FINISHINGMETHOD_ID
           AND D.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODdescription,
       X.year * 100 + X.week YEARWEEK,
       X.WEEK, X.DELIVERYDATE,
       sum(X.AMOUNTDELIVERED) DELIVEREDQTY,
       LANGUAGES.CODE LANGUAGECODE,
       RP.REPORTPARAM_ID,
       nvl((select sum(rqa.quantity) from rentalqtyadjustment rqa, productlistperdistribpoint plpd
                 where rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
                       and plpd.distributionpoint_id = dpl.distributionpoint_id
                       and plpd.product_id = pr.product_id
                       and plpd.sizedefinition_id = szl.sizedefinition_id
                       and plpd.finishingmethod_id = fm.finishingmethod_id
                       and rqa.adjustmentdate <= sysdate
                       and rqa.origin <> 2
                       and rqa.sampleitem = 'N'),0) chargeable_circ_inventory
FROM DELIVERYHISTORY X
  INNER JOIN DISTRIBUTIONPOINT_LINK DPL
        INNER JOIN DEPARTMENT_LINK DEL
              INNER JOIN CUSTOMER CU
                    INNER 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 X.DISTRIBUTIONPOINT_LINK_ID = DPL.DISTRIBUTIONPOINT_LINK_ID
  INNER JOIN PRODUCT PR
        INNER JOIN PRODUCTGROUP PG ON PR.PRODUCTGROUP_ID = PG.PRODUCTGROUP_ID
  ON X.PRODUCT_LINK_ID = PR.PRODUCT_ID
  INNER JOIN SIZEDEFINITION_LINK SZL ON X.SIZEDEFINITION_LINK_ID = SZL.SIZEDEFINITION_LINK_ID
  INNER JOIN FINISHINGMETHOD FM ON X.FINISHINGMETHOD_ID = FM.FINISHINGMETHOD_ID,
  LANGUAGES,
  REPORTPARAM RP
WHERE X.DELIVERYDATE >= RP.DATE_VALUE1 AND X.DELIVERYDATE <= 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 LANGUAGES.CODE = RP.STRING_VALUE
   AND PG.CODE >= RP.STRING_VALUE1 AND PG.CODE <= RP.STRING_VALUE2
   AND FM.CODE >= RP.STRING_VALUE5 AND FM.CODE <= RP.STRING_VALUE6
   AND X.PACKINDICATION IN (1, 2)
group by CU.CUSTOMERNUMBER, CU.NAME, VAD.STREET, VAD.STREET2, VAD.ZIPCODE, VAD.CITY,
       DEL.DEPARTMENTNUMBER, DEL.DESCRIPTION, dpl.distributionpoint_id, DPL.DISTRIBUTIONPOINTNUMBER,
       DPL.DESCRIPTION, PG.CODE, PG.PRODUCTGROUP_ID, LANGUAGES.LANGUAGE_ID,
       pr.product_id, PR.CODE, X.PRODUCT_LINK_ID, PR.typeofmerchandise, szl.sizedefinition_id, SZL.CODE, X.SIZEDEFINITION_LINK_ID,
       FM.CODE, fm.finishingmethod_id, X.FINISHINGMETHOD_ID, X.year, X.WEEK, X.DELIVERYDATE, LANGUAGES.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_LEGALENTITYFLEXFIELDS_SMG
 (LEGALENTITY_ID, LEGALENTITY_CODE, LEGALENTITY_NAME, LEGALENTITY_LEGALNAME, LEGALENTITY_COCNR, LEGALENTITY_VATNR, PHONE, FAX, EMAIL, WEBSITE, STREET, STREET2, ZIPCODE, CITY, STATE, COUNTY, VAT_ID, TIN, REG_OFFICE, COURT, NOM_CAP, MANAGEMENT, INV_REMARK1, INV_REMARK2, PACKAGING_DI, DN_REMARK1, DN_REMARK2, COMM_REGISTR, COMPANYSTAMPS_INVOICE, COMPANYSTAMPS_DIRINVOICE, COMPANYSTAMPS_DELNOTE, BANKINST_NAME1, INTERNALIDCODE1, LAUNDRYBANKACCOUNT1, IBANNO1, BANKINST_NAME2, INTERNALIDCODE2, LAUNDRYBANKACCOUNT2
, IBANNO2)
as select le.legalentity_id, le.code legalentity_code, le.name legalentity_name, le.legalname legalentity_legalname, le.cocnumber legalentity_cocnr, le.vatnumber legalentity_vatnr,
le.phone, le.fax, le.email, le.website, ad.street, ad.street2, ad.zipcode, ad.city, ad.state, ad.county,
(select dff.stringvalue from  CharacteristicsTempLine chtl, characteristic ch, DialogFlexFields dff where 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 = le.legalentity_id and ch.code = 'VAT_ID') VAT_ID,
(select dff.stringvalue from  CharacteristicsTempLine chtl, characteristic ch, DialogFlexFields dff where 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 = le.legalentity_id and ch.code = 'TIN') TIN,
(select dff.stringvalue from  CharacteristicsTempLine chtl, characteristic ch, DialogFlexFields dff where 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 = le.legalentity_id and ch.code = 'REG_OFFICE') REG_OFFICE,
(select dff.stringvalue from  CharacteristicsTempLine chtl, characteristic ch, DialogFlexFields dff where 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 = le.legalentity_id and ch.code = 'COURT') COURT,
(select dff.stringvalue from  CharacteristicsTempLine chtl, characteristic ch, DialogFlexFields dff where 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 = le.legalentity_id and ch.code = 'NOM_CAP') NOM_CAP,
(select dff.stringvalue from  CharacteristicsTempLine chtl, characteristic ch, DialogFlexFields dff where 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 = le.legalentity_id and ch.code = 'MANAGEMENT') MANAGEMENT,
(select dff.stringvalue from  CharacteristicsTempLine chtl, characteristic ch, DialogFlexFields dff where 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 = le.legalentity_id and ch.code = 'INV_REMARK1') INV_REMARK1,
(select dff.stringvalue from  CharacteristicsTempLine chtl, characteristic ch, DialogFlexFields dff where 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 = le.legalentity_id and ch.code = 'INV_REMARK2') INV_REMARK2,
(select dff.stringvalue from  CharacteristicsTempLine chtl, characteristic ch, DialogFlexFields dff where 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 = le.legalentity_id and ch.code = 'PACKAGING_DI') PACKAGING_DI,
(select dff.stringvalue from  CharacteristicsTempLine chtl, characteristic ch, DialogFlexFields dff where 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 = le.legalentity_id and ch.code = 'DN_REMARK1') DN_REMARK1,
(select dff.stringvalue from  CharacteristicsTempLine chtl, characteristic ch, DialogFlexFields dff where 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 = le.legalentity_id and ch.code = 'DN_REMARK2') DN_REMARK2,
(select dff.stringvalue from  CharacteristicsTempLine chtl, characteristic ch, DialogFlexFields dff where 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 = le.legalentity_id and ch.code = 'COMM_REGISTR') COMM_REGISTR,
(select im1.image from image im1 where im1.image_id = le.csinvoiceimage_id) CompanyStamps_Invoice,
(select im2.image from image im2 where im2.image_id = le.csdirectinvoiceimage_id) CompanyStamps_DirInvoice,
(select im3.image from image im3 where im3.image_id = le.csdeliverynoteimage_id) CompanyStamps_DelNote,
bi1.description bankinst_name1, bi1.internalidcode internalidcode1, bi1.laundrybankaccount laundrybankaccount1, bi1.ibanno ibanno1,
bi2.description bankinst_name2, bi2.internalidcode internalidcode2, bi2.laundrybankaccount laundrybankaccount2, bi2.ibanno ibanno2
from dialogs dia, CharacteristicsTemplate cht, bankinstitution bi1, address ad, legalentity le
     left outer join bankinstitution bi2 on bi2.bankinstitution_id = le.bankinstitution2_id
where cht.dialog_id = dia.dialog_id and bi1.bankinstitution_id = le.bankinstitution_id
      and ad.address_id = le.address_id and dia.code = 'LegalEntity' and cht.code = 'LEGALREQ'

/
create or replace view V_LINENCUSTOMERVALUE_ECL
 (INVOICEDATE, INVOICENUMBER, CUSTOMERNUMBER, NAME, DELIVEREDAMOUNT, AMOUNT, REJECTED, FREEOFCHARGE, BILLEDQTY, UNDERUSE, CHAINCODE, CHAINNAME)
as select ih.invoicedate, ih.invoicenumber, c.customernumber, c.name, sum(pnl.deliveredamount) deliveredamount, il.amount amount, sum(pnl.nochargeprevrejected) rejected, sum( pnl.nochargeprevshortage) freeofcharge, sum(pnl.deliveredamount-pnl.nochargeprevrejected-pnl.nochargeprevshortage)billedqty,
il2.amount underuse, ch.code chaincode, ch.name chainname
from invoiceheader ih join invoiceline il on ih.invoiceheader_id=il.invoiceheader_id --and il.invoicelinetype_id=2
left outer join invoiceline il2 on( il2.invoiceheader_id=ih.invoiceheader_id and il2.invoicelinetype_id=1 and il2.invoicelinesubtype=6)
 join invoicelineproduct ilp on il.invoiceline_id=ilp.invoiceline_id
 join packingnoteline pnl on (pnl.invoiceheader_id=ih.invoiceheader_id and pnl.product_id=ilp.product_link_id)
join product p on pnl.product_id=p.product_id and p.typeofmerchandise=1
join customer c on c.customer_id= ih.deltocustomer_link_id
join chain ch on c.chain_id=ch.chain_id
group by ih.invoicedate, ih.invoicenumber, c.customernumber, c.name, il.amount, il.billedqty, il2.amount,  ch.code, ch.name

/
create or replace view V_LINENSTOCKANALYSISPRD_ECL
 (CUSTOMERNUMBER, PRODUCTCODE, PRD_DESC, CUSTOMERNAME, DELIVERYDATE, CHAINCODE, CHAINNAME, ACTUALUSAGE, CIRCINV, DELIVPERWEEK)
as select c.customernumber, p.code productcode,
(select pd.description from product_desc pd where pd.product_id=p.product_id and pd.language_id=l.language_id ) prd_desc,
          c.name customername, pn.deliverydate, ch.code chaincode, ch.name chainname,
          sum(pnl.deliveredamount) actualusage,
          (select sum(q.quantity)
             from rentalqtyadjustment q
             join productlistperdistribpoint plpd
               on q.productlistperdistribpoint_id =
                  plpd.productlistperdistribpoint_id
                  join product prd on plpd.product_id=prd.product_id
            where plpd.distributionpoint_id = dp.distributionpoint_id
              and q.adjustmentdate < sysdate and prd.product_id=p.product_id) circinv,
          (select count(rs.route_id)
             from routestop rs
            where rs.customer_id = c.customer_id) delivperweek
     from packingnote pn
     join packingnoteline pnl
       on pn.packingnote_id = pnl.packingnote_id
     join distributionpoint dp
       on pn.distributionpoint_id = dp.distributionpoint_id
     join department dep
       on dep.department_id = dp.department_id
     join customer c
       on dep.customer_id = c.customer_id
       join chain ch on c.chain_id=ch.chain_id
       join product p on p.product_id=pnl.product_id
       join productgroup pg on pg.productgroup_id=p.productgroup_id
                               and pg.code not in ('REJ', 'EXT', 'ADMIN', 'LAUBAG')
    cross join languages l where l.code='EN_GB'
    group by c.customernumber,
             c.name,
             dp.distributionpoint_id,
             c.customer_id,pn.deliverydate, ch.code,  ch.name, p.product_id, p.code, pg.code, l.language_id

/
create or replace view V_LINENSTOCKANALYSIS_ECL
 (CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, DELIVERYDATE, CHAINCODE, CHAINNAME, ACTUALUSAGE, CIRCINV, DELIVPERWEEK)
as select c.customer_id, c.customernumber,
          c.name customername, pn.deliverydate, ch.code chaincode, ch.name chainname,
          sum(pnl.deliveredamount) actualusage,
          (select sum(q.quantity)
             from rentalqtyadjustment q
             join productlistperdistribpoint plpd
               on q.productlistperdistribpoint_id =
                  plpd.productlistperdistribpoint_id
                  join product prd on plpd.product_id=prd.product_id
                   join productgroup pg on pg.productgroup_id=prd.productgroup_id
                               and pg.code not in ('REJ', 'EXT', 'ADMIN', 'LAUBAG')
            where plpd.distributionpoint_id = dp.distributionpoint_id
              and q.adjustmentdate < sysdate) circinv,
          (select count(rs.route_id)
             from routestop rs
            where rs.customer_id = c.customer_id) delivperweek
     from packingnote pn
     join packingnoteline pnl
       on pn.packingnote_id = pnl.packingnote_id
     join distributionpoint dp
       on pn.distributionpoint_id = dp.distributionpoint_id
     join department dep
       on dep.department_id = dp.department_id
     join customer c
       on dep.customer_id = c.customer_id
       join chain ch on c.chain_id=ch.chain_id
       join product p on p.product_id=pnl.product_id
       join productgroup pg on pg.productgroup_id=p.productgroup_id
                               and pg.code not in ('REJ', 'EXT', 'ADMIN', 'LAUBAG')
    group by c.customernumber,
             c.name,
             dp.distributionpoint_id,
             c.customer_id,pn.deliverydate, ch.code,  ch.name

/
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, CUSTOMERNUMBER, CUSTOMERNAME, CHANGESPERWEEKPRODDESC, MYCOUNT, SKIPPEDSECTIONS)
as select lr.locker, lr.customer_id, lr.lockerstatus,lr.bank, wr.wearernumber, wr.fullname, wr.firstname, wr.searchname
, 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) || '   ' || --coalesce(pr.legacyproductcode, pr.code) || ' ' ||
                    pr.shortdescription),', ')
               WITHIN GROUP (order by wi.changesperweek--, pr.code
                            , 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.code || ' ' ||
                    pr.shortdescription),', ')
               WITHIN GROUP (order by wi.changesperweek--, pr.code
                            , 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 outer join WearerEmployment WE
            inner join Wearer WR on wr.wearer_id = we.wearer_id
     on WE.Locker_ID = LR.Locker_ID
     join Customer C on LR.Customer_Id=C.Customer_Id ,
     (select rownum mycount
                  from invoiceheader--all_objects--
                 where rownum <= 100) x
union all
select ' ' locker, 0 customer_id, 0 lockerstatus, ' ' bank, 0 wearernumber, ' ' fullname, ' ' firstname, ' ' searchname
, 0 Customernumber, ' '  customername
, ' ' changesPerWeekProdDesc
, 0 mycount
, x.mycount skippedsections
from (select rownum mycount
                  from invoiceheader--all_objects--
                 where rownum <= 100) x

/
create or replace view V_LOCKERLABEL_CBD
 (CUSTOMER_ID, WEARERNUMBER, FULLNAME, FIRSTNAME, EMBLEMNAME, BANK, LOCKER, CUSTOMERNUMBER, CUSTOMERNAME, PLANTNAME, STREET, ZIPCODE, CITY, MYCOUNT, LOCKERSTATUS)
as select lr.customer_id
,      wr.wearernumber
,      wr.fullname
,      wr.firstname
,      wr.emblemname
,      LR.Bank
,      lr.locker
,      c.customernumber
,      c.name customername
,      p.name plantname
,      a.street
,      a.zipcode
,      a.city
,      x.mycount
,      lr.lockerstatus
from   Locker LR
          left outer join WearerEmployment WE
             inner join Wearer WR on wr.wearer_id = we.wearer_id
          on WE.Locker_ID = LR.Locker_ID
,      customer c
,      businessunit b
,      plant p
,      address a
,      ( select rownum mycount
         from   invoiceheader--all_objects--
         where rownum <= 100) x
where  wr.customer_id = c.customer_id
   and c.defaultbusinessunit_id=b.businessunit_id
   and b.plant_id=p.plant_id
   and p.address_id=a.address_id

/
create or replace view V_LOSSCHARGES
 (INVOICEDATE, BU_CODE, BU_DESC, SALESJOURNALGROUP_CODE, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, INVOICELINETYPE_ID, AMOUNT, INVOICEAMOUNTDECIMALS, SALESJOURNALGROUP_DESC, SYSTEMUSER_ID, LANGUAGECODE)
as SELECT ih.Invoicedate, bu.code BU_Code, bu.description BU_desc, sjg.code SalesJournalGroup_code,
       ilp.productgroupcode, ilp.productgroupdescription, il.invoicelinetype_id, il.amount,
       (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, su.systemuser_id,
       lan.code LanguageCode
FROM invoiceheader ih, invoiceline il, invoicelineproduct ilp, businessunit bu,
     turnovergroup tg, salesjournalgroup sjg, Systemuser su, languages lan
WHERE ih.invoiceheader_id = il.Invoiceheader_Id AND ilp.invoiceline_id = il.invoiceline_id AND
      il.turnovergroup_id = tg.turnovergroup_id AND tg.salesjournalgroup_id = sjg.salesjournalgroup_id
      AND ih.invoicebusinessunit_id = bu.businessunit_id AND ilp.productgroupcode IS NOT NULL
      AND ih.status_id IN (SELECT st.status_id FROM status st WHERE st.code = '2' AND st.statustype = 'IN')
      AND EXISTS (SELECT * FROM businessunitsperusergroup bug WHERE bug.usergroup_id = su.usergroup_id AND bug.businessunit_id = bu.businessunit_id)

/
create or replace view V_LOSSFORPOOLPERPRODCONS_ANG
 (CUSTOMERNUMBER, NAME, 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,
       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,
       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,
       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,
       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,
       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,
       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,
       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,
       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_LOSSFORPOOLPERPRODDEPT_ANG
 (CUSTOMERNUMBER, NAME, INVOICEHEADER_ID, DEPARTMENTNUMBER, DEP_DESC, CURRENCYCODE, INVOICENUMBER, INVOICEDATE, PERIODENDDATE, STARTDATE, ENDDATE, YEAR, PERIOD, DAYSINPERIOD, PRODUCTCODE, PRODUCTDESCRIPTION, CREDITQTY, CREDITPRICE, CREDITAMOUNT, DEBITQTY, DEBITPRICE, LOSSAMOUNT, SIZE_CODE, SIZE_DESC)
as select  c.customernumber,
       c.name,
       Q.invoiceheader_id,
       Q.departmentnumber, Q.dep_desc,
       (select c.code from currency c where c.currency_id = ih.currency_id) currencycode,
       ih.invoicenumber,
       ih.invoicedate,
       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=c.customer_id and plpc.product_id = q.product_id
                  and plpc.sizedefinition_id = Q.sizedefinition_id
                  and plpc.dateactive <= sysdate and plpc.dateinactive > sysdate )) daysinperiod,
       p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = Q.product_id
           and pd.language_id = c.language_id) productdescription,
 Q.creditqty, Q.creditprice, Q.creditamount, Q.lossqty debitqty, Q.lossprice debitprice, Q.lossamount,
 (select sd.code from sizedefinition sd where sd.sizedefinition_id = Q.sizedefinition_id) size_code,
       (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = Q.sizedefinition_id and sdd.language_id = c.language_id) size_desc
FROM
(select lossquery.invoiceheader_id, lossquery.product_id, lossquery.sizedefinition_id, lossquery.customer_id, lossquery.invoicefrequencylossperiod_id,
       lossquery.departmentnumber, lossquery.description dep_desc,
       sum(lossquery.creditqty) creditqty,  lossquery.creditprice, sum(lossquery.creditprice) creditamount,
       sum(lossquery.lossqty) lossqty,    lossquery.debitprice lossprice, sum(lossquery.debitprice) lossamount
         from
(select uil.lossinvoiceheader_id invoiceheader_id,
        ri.product_link_id product_id, ri.sizedefinition_link_id sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        dep.departmentnumber, dep.description,
        1 lossqty,
        0 creditqty,
        uil.lossamount DebitPrice,
        0 CreditPrice
from uniqueitemloss uil join  raggeditem ri on uil.uniqueitem_link_id = ri.raggeditem_id
join distributionpoint dp on uil.distributionpoint_link_id=dp.distributionpoint_id
join department dep on dep.department_id=dp.department_id
where uil.lossstatus <> 5
union all
select  uil.lossinvoiceheader_id invoiceheader_id,
        ui.product_id product_id, ui.sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        dep.departmentnumber, dep.description,
        1 lossqty,
        0 creditqty,
        uil.lossamount DebitPrice,
        0 CreditPrice
from uniqueitemloss uil join uniqueitem ui on uil.uniqueitem_link_id=ui.uniqueitem_id
join distributionpoint dp on uil.distributionpoint_link_id=dp.distributionpoint_id
join department dep on dep.department_id=dp.department_id
where uil.lossstatus <> 5) lossquery
where (
(select count(*)
from uniqueitemloss uil join  raggeditem ri on uil.uniqueitem_link_id = ri.raggeditem_id
where uil.lossstatus <> 5
   and uil.creditinvoiceheader_id=lossquery.invoiceheader_id--lossquery.invoiceheader_id
   and  ri.product_link_id= lossquery.product_id
     and round(lossquery.debitprice,2) = round(uil.creditamount,2) * -1)+
(select count(*)
from uniqueitemloss         uil join uniqueitem ui on uil.uniqueitem_link_id=ui.uniqueitem_id
where uil.lossstatus <> 5
and uil.creditinvoiceheader_id=lossquery.invoiceheader_id--lossquery.invoiceheader_id
   and uil.lossstatus <> 5
   and  ui.product_id= lossquery.product_id
 and round(lossquery.debitprice,2) = round(uil.creditamount,2) * -1)
)=0
group by lossquery.invoiceheader_id, lossquery.departmentnumber, lossquery.description, lossquery.creditprice, lossquery.debitprice, lossquery.product_id,lossquery.sizedefinition_id, lossquery.customer_id, lossquery.invoicefrequencylossperiod_id
UNION ALL
select creditquery.invoiceheader_id, creditquery.product_id, creditquery.sizedefinition_id, creditquery.customer_id, creditquery.invoicefrequencylossperiod_id,
       creditquery.departmentnumber, creditquery.description dept_desc,
       sum(creditquery.creditqty) creditqty,  creditquery.creditprice, sum(creditquery.creditprice) creditamount,
       sum(creditquery.lossqty) lossqty,    creditquery.debitprice lossprice, sum(creditquery.debitprice) lossamount
         from
(select  uil.creditinvoiceheader_id invoiceheader_id,
        ri.product_link_id product_id,ri.sizedefinition_link_id sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        dep.departmentnumber, dep.description,
        0 lossqty,
        1 creditqty,
        0 DebitPrice,
        uil.creditamount CreditPrice
from uniqueitemloss uil join  raggeditem ri on uil.uniqueitem_link_id = ri.raggeditem_id
join distributionpoint dp on uil.distributionpoint_link_id=dp.distributionpoint_id
join department dep on dep.department_id=dp.department_id
where uil.lossstatus <> 5
union all
select   uil.creditinvoiceheader_id invoiceheader_id,
        ui.product_id,ui.sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        dep.departmentnumber, dep.description,
        0 lossqty,
        1 creditqty,
        0 DebitPrice,
        uil.creditamount CreditPrice
from uniqueitemloss         uil join uniqueitem ui on uil.uniqueitem_link_id=ui.uniqueitem_id
join distributionpoint dp on uil.distributionpoint_link_id=dp.distributionpoint_id
join department dep on dep.department_id=dp.department_id
where uil.lossstatus <> 5) creditquery
where (
(select count(*)
from uniqueitemloss uil join  raggeditem ri on uil.uniqueitem_link_id = ri.raggeditem_id
where uil.lossstatus <> 5
   and uil.lossinvoiceheader_id= creditquery.invoiceheader_id--lossquery.invoiceheader_id
   and  ri.product_link_id= creditQuery.product_id
     and round(uil.lossamount,2) = round(creditQuery.creditprice,2) * -1)+
(select count(*)
from uniqueitemloss         uil join uniqueitem ui on uil.uniqueitem_link_id=ui.uniqueitem_id
where uil.lossstatus <> 5
and uil.lossinvoiceheader_id=creditquery.invoiceheader_id--lossquery.invoiceheader_id
   and  ui.product_id= creditQuery.product_id
 and round(uil.lossamount,2) = round(creditQuery.creditprice,2) * -1)
)=0
group by creditquery.invoiceheader_id, creditquery.departmentnumber, creditquery.description, creditquery.creditprice, creditquery.debitprice, creditquery.product_id, creditquery.sizedefinition_id, creditquery.customer_id, creditquery.invoicefrequencylossperiod_id
UNION ALL
select lossquery.invoiceheader_id, lossquery.product_id, creditquery.sizedefinition_id, creditquery.customer_id, creditquery.invoicefrequencylossperiod_id,
 creditquery.departmentnumber, creditquery.description,
 creditquery.creditqty, creditquery.creditprice, creditquery.creditamount, lossquery.lossqty, lossquery.lossprice, lossquery.lossamount from
(
select x.invoiceheader_id, x.product_id ,x.departmentnumber, x.description,  x.sizedefinition_id, x.customer_id, x.invoicefrequencylossperiod_id,
       sum(x.creditqty) creditqty,  x.creditprice, sum(x.creditprice) creditamount,
       sum(x.lossqty) lossqty,    x.debitprice lossprice, sum(x.debitprice) lossamount
  from
(select  uil.creditinvoiceheader_id invoiceheader_id,
        ri.product_link_id product_id,ri.sizedefinition_link_id sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        dep.departmentnumber, dep.description,
        0 lossqty,
        1 creditqty,
        0 DebitPrice,
        uil.creditamount CreditPrice
from uniqueitemloss uil join  raggeditem ri on uil.uniqueitem_link_id = ri.raggeditem_id
join distributionpoint dp on uil.distributionpoint_link_id=dp.distributionpoint_id
join department dep on dep.department_id=dp.department_id
where uil.lossstatus <> 5
union all
select   uil.creditinvoiceheader_id invoiceheader_id,
        ui.product_id ,ui.sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        dep.departmentnumber, dep.description,
        0 lossqty,
        1 creditqty,
        0 DebitPrice,
        uil.creditamount CreditPrice
from uniqueitemloss         uil join uniqueitem ui on uil.uniqueitem_link_id=ui.uniqueitem_id
join distributionpoint dp on uil.distributionpoint_link_id=dp.distributionpoint_id
join department dep on dep.department_id=dp.department_id
where uil.lossstatus <> 5
UNION ALL
select  uil.lossinvoiceheader_id invoiceheader_id,
        ri.product_link_id product_id,ri.sizedefinition_link_id sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
       dep.departmentnumber, dep.description,
        1 lossqty,
        0 creditqty,
        uil.lossamount DebitPrice,
        0 CreditPrice
from uniqueitemloss uil join  raggeditem ri on uil.uniqueitem_link_id = ri.raggeditem_id
join distributionpoint dp on uil.distributionpoint_link_id=dp.distributionpoint_id
join department dep on dep.department_id=dp.department_id
where uil.lossstatus <> 5
union all
select  uil.lossinvoiceheader_id invoiceheader_id,
        ui.product_id ,ui.sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        dep.departmentnumber, dep.description,
        1 lossqty,
        0 creditqty,
        uil.lossamount DebitPrice,
        0 CreditPrice
from uniqueitemloss         uil join uniqueitem ui on uil.uniqueitem_link_id=ui.uniqueitem_id
join distributionpoint dp on ui.uniqueitem_id=dp.distributionpoint_id
join department dep on dep.department_id=dp.department_id
where uil.lossstatus <> 5) x
group by x.invoiceheader_id, x.departmentnumber,x.description, x.debitprice, x.creditprice , x.product_id,  x.sizedefinition_id, x.customer_id, x.invoicefrequencylossperiod_id
) lossquery,
(
select x.invoiceheader_id,  x.product_id, x.sizedefinition_id, x.customer_id, x.invoicefrequencylossperiod_id,
       x.departmentnumber, x.description,
       sum(x.creditqty) creditqty,  x.creditprice, sum(x.creditprice) creditamount,
       sum(x.lossqty) lossqty,    x.debitprice lossprice, sum(x.debitprice) lossamount
  from
(select   uil.creditinvoiceheader_id invoiceheader_id,
        ri.product_link_id product_id, ri.sizedefinition_link_id sizedefinition_id,uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
       dep.departmentnumber, dep.description,
         0 lossqty,
        1 creditqty,
        0 DebitPrice,
        uil.creditamount CreditPrice
from uniqueitemloss uil join  raggeditem ri on uil.uniqueitem_link_id = ri.raggeditem_id
join distributionpoint dp on uil.distributionpoint_link_id=dp.distributionpoint_id
join department dep on dep.department_id=dp.department_id
where uil.lossstatus <> 5
union all
select  uil.creditinvoiceheader_id invoiceheader_id,
        ui.product_id ,ui.sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        dep.departmentnumber, dep.description,
        0 lossqty,
        1 creditqty,
        0 DebitPrice,
        uil.creditamount CreditPrice
from uniqueitemloss         uil join uniqueitem ui on uil.uniqueitem_link_id=ui.uniqueitem_id
join distributionpoint dp on uil.distributionpoint_link_id=dp.distributionpoint_id
join department dep on dep.department_id=dp.department_id
where uil.lossstatus <> 5
UNION ALL
select  uil.lossinvoiceheader_id invoiceheader_id,
        ri.product_link_id product_id, ri.sizedefinition_link_id sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        dep.departmentnumber, dep.description,
        1 lossqty,
        0 creditqty,
        uil.lossamount DebitPrice,
        0 CreditPrice
from uniqueitemloss uil join  raggeditem ri on uil.uniqueitem_link_id = ri.raggeditem_id
join distributionpoint dp on uil.distributionpoint_link_id=dp.distributionpoint_id
join department dep on dep.department_id=dp.department_id
where uil.lossstatus <> 5
union all
select  uil.lossinvoiceheader_id invoiceheader_id,
        ui.product_id ,ui.sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        dep.departmentnumber, dep.description,
        1 lossqty,
        0 creditqty,
        uil.lossamount DebitPrice,
        0 CreditPrice
from uniqueitemloss         uil join uniqueitem ui on uil.uniqueitem_link_id=ui.uniqueitem_id
join distributionpoint dp on uil.distributionpoint_link_id=dp.distributionpoint_id
join department dep on dep.department_id=dp.department_id
where uil.lossstatus <> 5) x
group by x.invoiceheader_id, x.departmentnumber, x.description, x.debitprice, x.creditprice, x.product_id, x.sizedefinition_id, x.customer_id, x.invoicefrequencylossperiod_id
) creditquery
where lossquery.invoiceheader_id = creditquery.invoiceheader_id
  and lossquery.product_id = creditquery.product_id
  and round(lossquery.lossprice,2) = round(creditquery.creditprice,2) * -1
  and lossquery.lossprice <> 0
)Q left outer join invoicefrequencylossperiod iflp on Q.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id
join invoiceheader ih on q.invoiceheader_id=ih.invoiceheader_id
join customer c on c.customer_id= q.customer_id
join product p on p.product_id=Q.product_id

/
create or replace view V_LOSSFORPOOLPERPRODUCT
 (CUSTOMERNUMBER, NAME, INVOICEHEADER_ID, CURRENCYCODE, INVOICENUMBER, INVOICEDATE, PERIODENDDATE, STARTDATE, ENDDATE, YEAR, PERIOD, DAYSINPERIOD, CHARGETYPE, PRODUCTCODE, PRODUCTDESCRIPTION, AMOUNT, QTY, LOSSSTATUS, SIZE_CODE, SIZE_DESC)
as select cl.customernumber,
       cl.name,
       ih.invoiceheader_id,
       (select c.code from currency c where c.currency_id = ih.currency_id) currencycode,
       ih.invoicenumber,
       ih.invoicedate,
       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
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,
       uniqueitem             ui,
       product                p
where uil.creditinvoiceheader_id = ih.invoiceheader_id
   and uil.customer_link_id = cl.customer_link_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.invoiceheader_id,
       ih.currency_id,
       ih.invoicenumber,
       ih.invoicedate,
       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
union all
select cl.customernumber,
       cl.name,
       ih.invoiceheader_id,
       (select c.code from currency c where c.currency_id = ih.currency_id) currencycode,
       ih.invoicenumber,
       ih.invoicedate,
       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
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,
       uniqueitem             ui,
       product                p
where uil.lossinvoiceheader_id = ih.invoiceheader_id
   and uil.customer_link_id = cl.customer_link_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.invoiceheader_id,
       ih.currency_id,
       ih.invoicenumber,
       ih.invoicedate,
       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
union all
select cl.customernumber,
       cl.name,
       ih.invoiceheader_id,
       (select c.code from currency c where c.currency_id = ih.currency_id) currencycode,
       ih.invoicenumber,
       ih.invoicedate,
       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.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,
       raggeditem             ri,
       product                p
where uil.creditinvoiceheader_id = ih.invoiceheader_id
   and uil.customer_link_id = cl.customer_link_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.invoiceheader_id,
       ih.currency_id,
       ih.invoicenumber,
       ih.invoicedate,
       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
union all
select cl.customernumber,
       cl.name,
       ih.invoiceheader_id,
       (select c.code from currency c where c.currency_id = ih.currency_id) currencycode,
       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,
       raggeditem             ri,
       product                p
where uil.lossinvoiceheader_id = ih.invoiceheader_id
   and uil.customer_link_id = cl.customer_link_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.invoiceheader_id,
       ih.currency_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.lossstatus, c.language_id

/
create or replace view V_LOSSFORPOOLPERPRODUCTDEPT
 (CUSTOMERNUMBER, NAME, CURRENCYCODE, DEPARTMENTNUMBER, DESCRIPTION, INVOICEHEADER_ID, INVOICENUMBER, INVOICEDATE, INVOICEBUSINESSUNIT_ID, 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,
       ih.invoiceheader_id,
       ih.invoicenumber,
       ih.invoicedate,
       ih.invoicebusinessunit_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
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
group by cl.customernumber,
       cl.name,
       ih.currency_id,
       dl.departmentnumber,
       dl.description,
       ih.invoiceheader_id,
       ih.invoicenumber,
       ih.invoicedate,
       ih.invoicebusinessunit_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
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,
       ih.invoiceheader_id,
       ih.invoicenumber,
       ih.invoicedate,
       ih.invoicebusinessunit_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
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
group by cl.customernumber,
       cl.name,
       ih.currency_id,
       dl.departmentnumber,
       dl.description,
       ih.invoiceheader_id,
       ih.invoicenumber,
       ih.invoicedate,
       ih.invoicebusinessunit_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
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,
       ih.invoiceheader_id,
       ih.invoicenumber,
       ih.invoicedate,
       ih.invoicebusinessunit_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.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
group by  cl.customernumber,
       cl.name,
       ih.currency_id,
       dl.departmentnumber,
       dl.description,
       ih.invoiceheader_id,
       ih.invoicenumber,
       ih.invoicedate,
       ih.invoicebusinessunit_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
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,
       ih.invoiceheader_id,
       ih.invoicenumber,
       ih.invoicedate,
       ih.invoicebusinessunit_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.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
group by cl.customernumber,
       cl.name,
       ih.currency_id,
       dl.departmentnumber,
       dl.description,
       ih.invoiceheader_id,
       ih.invoicenumber,
       ih.invoicedate,
       ih.invoicebusinessunit_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

/
create or replace view V_LOSSFORPOOLPERPRODUCT_ANG
 (CUSTOMERNUMBER, NAME, INVOICEHEADER_ID, CURRENCYCODE, INVOICENUMBER, INVOICEDATE, PERIODENDDATE, STARTDATE, ENDDATE, YEAR, PERIOD, DAYSINPERIOD, PRODUCTCODE, PRODUCTDESCRIPTION, CREDITQTY, CREDITPRICE, CREDITAMOUNT, DEBITQTY, DEBITPRICE, LOSSAMOUNT, SIZE_CODE, SIZE_DESC)
as select  c.customernumber,
       c.name,
       Q.invoiceheader_id,
       (select c.code from currency c where c.currency_id = ih.currency_id) currencycode,
       ih.invoicenumber,
       ih.invoicedate,
       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=c.customer_id and plpc.product_id = q.product_id
                  and plpc.sizedefinition_id = Q.sizedefinition_id
                  and plpc.dateactive <= sysdate and plpc.dateinactive > sysdate )) daysinperiod,
       p.code productcode,
       (select pd.description
          from product_desc pd
         where pd.product_id = Q.product_id
           and pd.language_id = c.language_id) productdescription,
 Q.creditqty, Q.creditprice, Q.creditamount, Q.lossqty debitqty, Q.lossprice debitprice, Q.lossamount,
 (select sd.code from sizedefinition sd where sd.sizedefinition_id = Q.sizedefinition_id) size_code,
       (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = Q.sizedefinition_id and sdd.language_id = c.language_id) size_desc
FROM
(select lossquery.invoiceheader_id, lossquery.product_id, lossquery.sizedefinition_id, lossquery.customer_id, lossquery.invoicefrequencylossperiod_id,
       sum(lossquery.creditqty) creditqty,  lossquery.creditprice, sum(lossquery.creditprice) creditamount,
       sum(lossquery.lossqty) lossqty,    lossquery.debitprice lossprice, sum(lossquery.debitprice) lossamount
         from
(select uil.lossinvoiceheader_id invoiceheader_id,
        ri.product_link_id product_id, ri.sizedefinition_link_id sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        1 lossqty,
        0 creditqty,
        uil.lossamount DebitPrice,
        0 CreditPrice
from uniqueitemloss uil join  raggeditem ri on uil.uniqueitem_link_id = ri.raggeditem_id
where uil.lossstatus <> 5
union all
select  uil.lossinvoiceheader_id invoiceheader_id,
        ui.product_id product_id, ui.sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        1 lossqty,
        0 creditqty,
        uil.lossamount DebitPrice,
        0 CreditPrice
from uniqueitemloss uil join uniqueitem ui on uil.uniqueitem_link_id=ui.uniqueitem_id
where uil.lossstatus <> 5) lossquery
where (
(select count(*)
from uniqueitemloss uil join  raggeditem ri on uil.uniqueitem_link_id = ri.raggeditem_id
where uil.lossstatus <> 5
   and uil.creditinvoiceheader_id=lossquery.invoiceheader_id--lossquery.invoiceheader_id
   and  ri.product_link_id= lossquery.product_id
     and round(lossquery.debitprice,2) = round(uil.creditamount,2) * -1)+
(select count(*)
from uniqueitemloss         uil join uniqueitem ui on uil.uniqueitem_link_id=ui.uniqueitem_id
where uil.lossstatus <> 5
and uil.creditinvoiceheader_id=lossquery.invoiceheader_id--lossquery.invoiceheader_id
   and uil.lossstatus <> 5
   and  ui.product_id= lossquery.product_id
 and round(lossquery.debitprice,2) = round(uil.creditamount,2) * -1)
)=0
group by lossquery.invoiceheader_id, lossquery.creditprice, lossquery.debitprice, lossquery.product_id,lossquery.sizedefinition_id, lossquery.customer_id, lossquery.invoicefrequencylossperiod_id
UNION ALL
select creditquery.invoiceheader_id, creditquery.product_id, creditquery.sizedefinition_id, creditquery.customer_id, creditquery.invoicefrequencylossperiod_id,
       sum(creditquery.creditqty) creditqty,  creditquery.creditprice, sum(creditquery.creditprice) creditamount,
       sum(creditquery.lossqty) lossqty,    creditquery.debitprice lossprice, sum(creditquery.debitprice) lossamount
         from
(select  uil.creditinvoiceheader_id invoiceheader_id,
        ri.product_link_id product_id,ri.sizedefinition_link_id sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        0 lossqty,
        1 creditqty,
        0 DebitPrice,
        uil.creditamount CreditPrice
from uniqueitemloss uil join  raggeditem ri on uil.uniqueitem_link_id = ri.raggeditem_id
where uil.lossstatus <> 5
union all
select   uil.creditinvoiceheader_id invoiceheader_id,
        ui.product_id,ui.sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        0 lossqty,
        1 creditqty,
        0 DebitPrice,
        uil.creditamount CreditPrice
from uniqueitemloss         uil join uniqueitem ui on uil.uniqueitem_link_id=ui.uniqueitem_id
where uil.lossstatus <> 5) creditquery
where (
(select count(*)
from uniqueitemloss uil join  raggeditem ri on uil.uniqueitem_link_id = ri.raggeditem_id
where uil.lossstatus <> 5
   and uil.lossinvoiceheader_id= creditquery.invoiceheader_id--lossquery.invoiceheader_id
   and  ri.product_link_id= creditQuery.product_id
     and round(uil.lossamount,2) = round(creditQuery.creditprice,2) * -1)+
(select count(*)
from uniqueitemloss         uil join uniqueitem ui on uil.uniqueitem_link_id=ui.uniqueitem_id
where uil.lossstatus <> 5
and uil.lossinvoiceheader_id=creditquery.invoiceheader_id--lossquery.invoiceheader_id
   and  ui.product_id= creditQuery.product_id
 and round(uil.lossamount,2) = round(creditQuery.creditprice,2) * -1)
)=0
group by creditquery.invoiceheader_id, creditquery.creditprice, creditquery.debitprice, creditquery.product_id, creditquery.sizedefinition_id, creditquery.customer_id, creditquery.invoicefrequencylossperiod_id
UNION ALL
select lossquery.invoiceheader_id, lossquery.product_id, creditquery.sizedefinition_id, creditquery.customer_id, creditquery.invoicefrequencylossperiod_id,
 creditquery.creditqty, creditquery.creditprice, creditquery.creditamount, lossquery.lossqty, lossquery.lossprice, lossquery.lossamount from
(
select x.invoiceheader_id, x.product_id ,  x.sizedefinition_id, x.customer_id, x.invoicefrequencylossperiod_id,
       sum(x.creditqty) creditqty,  x.creditprice, sum(x.creditprice) creditamount,
       sum(x.lossqty) lossqty,    x.debitprice lossprice, sum(x.debitprice) lossamount
  from
(select  uil.creditinvoiceheader_id invoiceheader_id,
        ri.product_link_id product_id,ri.sizedefinition_link_id sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        0 lossqty,
        1 creditqty,
        0 DebitPrice,
        uil.creditamount CreditPrice
from uniqueitemloss uil join  raggeditem ri on uil.uniqueitem_link_id = ri.raggeditem_id
where uil.lossstatus <> 5
union all
select   uil.creditinvoiceheader_id invoiceheader_id,
        ui.product_id ,ui.sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        0 lossqty,
        1 creditqty,
        0 DebitPrice,
        uil.creditamount CreditPrice
from uniqueitemloss         uil join uniqueitem ui on uil.uniqueitem_link_id=ui.uniqueitem_id
where uil.lossstatus <> 5
UNION ALL
select  uil.lossinvoiceheader_id invoiceheader_id,
        ri.product_link_id product_id,ri.sizedefinition_link_id sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        1 lossqty,
        0 creditqty,
        uil.lossamount DebitPrice,
        0 CreditPrice
from uniqueitemloss uil join  raggeditem ri on uil.uniqueitem_link_id = ri.raggeditem_id
where uil.lossstatus <> 5
union all
select  uil.lossinvoiceheader_id invoiceheader_id,
        ui.product_id ,ui.sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        1 lossqty,
        0 creditqty,
        uil.lossamount DebitPrice,
        0 CreditPrice
from uniqueitemloss         uil join uniqueitem ui on uil.uniqueitem_link_id=ui.uniqueitem_id
where uil.lossstatus <> 5) x
group by x.invoiceheader_id, x.debitprice, x.creditprice , x.product_id,  x.sizedefinition_id, x.customer_id, x.invoicefrequencylossperiod_id
) lossquery,
(
select x.invoiceheader_id,  x.product_id, x.sizedefinition_id, x.customer_id, x.invoicefrequencylossperiod_id,
       sum(x.creditqty) creditqty,  x.creditprice, sum(x.creditprice) creditamount,
       sum(x.lossqty) lossqty,    x.debitprice lossprice, sum(x.debitprice) lossamount
  from
(select   uil.creditinvoiceheader_id invoiceheader_id,
        ri.product_link_id product_id, ri.sizedefinition_link_id sizedefinition_id,uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        0 lossqty,
        1 creditqty,
        0 DebitPrice,
        uil.creditamount CreditPrice
from uniqueitemloss uil join  raggeditem ri on uil.uniqueitem_link_id = ri.raggeditem_id
where uil.lossstatus <> 5
union all
select  uil.creditinvoiceheader_id invoiceheader_id,
        ui.product_id ,ui.sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        0 lossqty,
        1 creditqty,
        0 DebitPrice,
        uil.creditamount CreditPrice
from uniqueitemloss         uil join uniqueitem ui on uil.uniqueitem_link_id=ui.uniqueitem_id
where uil.lossstatus <> 5
UNION ALL
select  uil.lossinvoiceheader_id invoiceheader_id,
        ri.product_link_id product_id, ri.sizedefinition_link_id sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        1 lossqty,
        0 creditqty,
        uil.lossamount DebitPrice,
        0 CreditPrice
from uniqueitemloss uil join  raggeditem ri on uil.uniqueitem_link_id = ri.raggeditem_id
where uil.lossstatus <> 5
union all
select  uil.lossinvoiceheader_id invoiceheader_id,
        ui.product_id ,ui.sizedefinition_id, uil.customer_link_id customer_id, uil.invoicefrequencylossperiod_id,
        1 lossqty,
        0 creditqty,
        uil.lossamount DebitPrice,
        0 CreditPrice
from uniqueitemloss         uil join uniqueitem ui on uil.uniqueitem_link_id=ui.uniqueitem_id
where uil.lossstatus <> 5) x
group by x.invoiceheader_id, x.debitprice, x.creditprice, x.product_id, x.sizedefinition_id, x.customer_id, x.invoicefrequencylossperiod_id
) creditquery
where lossquery.invoiceheader_id = creditquery.invoiceheader_id
  and lossquery.product_id = creditquery.product_id
  and round(lossquery.lossprice,2) = round(creditquery.creditprice,2) * -1
  and lossquery.lossprice <> 0
)Q left outer join invoicefrequencylossperiod iflp on Q.invoicefrequencylossperiod_id = iflp.invoicefrequencylossperiod_id
join invoiceheader ih on q.invoiceheader_id=ih.invoiceheader_id
join customer c on c.customer_id= q.customer_id
join product p on p.product_id=Q.product_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 cpc.customer_id, max(cpc.dateactive) dateactive, rp.reportparam_id
from contractspercustomer cpc
    left outer join competitor co on co.competitor_id = cpc.lostcompetitor_id
    left outer join gainlostreason gr on gr.gainlostreason_id = cpc.lostreason_id,
  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 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 outer join competitor co on plpc.lostcompetitor_id = co.competitor_id
    left outer join gainlostreason gl on plpc.lostreason_id = gl.gainlostreason_id,
  product pr, productgroup pg, customeractivities ca, businessunitsperusergroup bug, activity ac,
  languages l, reportparam rp
where pr.productgroup_id = pg.productgroup_id
  and plpc.product_id = pr.product_id
  and pg.activity_id = ca.activity_id
  and ca.customer_id = plpc.customer_id
  and ca.invoicebusinessunit_id = bug.businessunit_id
  and ca.activity_id = ac.activity_id
  and plpc.dateinactive >= rp.date_value1
  and plpc.dateinactive <= rp.date_value2
  and bug.usergroup_id = rp.number_value1
  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, 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
)
as SELECT
PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME,
ADDRESS.street CUSTOMERSTREET, ADDRESS.zipcode CUSTOMERZIP, ADDRESS.city CUSTOMERCITY,
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
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))

/
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_MATREQUIREMENTS
 (BUSINESSUNITCODE, BUSINEESUNITDESSC, ACTIVITYCODE, PRODUCTCODE, PRODUCTDESC, SIZECODE, PRODUCTGROUPCODE, PRODUCTGROUPDESC, LANGUAGECODE, REPORTPARAM_ID, PRODUCTLISTPERDISTRIBPOINT_ID, DATE_VALUE1, WEEKNR, QTYWEEK1, QTYWEEK2, QTYWEEK3, QTYWEEK4, QTYWEEK5, QTYWEEK6, QTYWEEK7, QTYWEEK8, QTYWEEK9, QTYWEEK10, QTYWEEK11, QTYWEEK12)
as select bu.code businessunitcode, bu.description busineesunitdessc, ac.code activitycode,
       pr.code productcode,-- ds.code DELIVERYSCHEMECODE,
       (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, 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,
       l.code languagecode, rp.reportparam_id,
       pldp.productlistperdistribpoint_id,
       rp.date_value1,
       getisoweek(rp.date_value1) weeknr,
       GET_REQMATS(rp.date_value1,pldp.productlistperdistribpoint_id) qtyweek1,
       GET_REQMATS(rp.date_value1+7,pldp.productlistperdistribpoint_id) qtyweek2,
       GET_REQMATS(rp.date_value1+14,pldp.productlistperdistribpoint_id) qtyweek3,
       GET_REQMATS(rp.date_value1+21,pldp.productlistperdistribpoint_id) qtyweek4,
       GET_REQMATS(rp.date_value1+28,pldp.productlistperdistribpoint_id) qtyweek5,
       GET_REQMATS(rp.date_value1+35,pldp.productlistperdistribpoint_id) qtyweek6,
       GET_REQMATS(rp.date_value1+42,pldp.productlistperdistribpoint_id) qtyweek7,
       GET_REQMATS(rp.date_value1+49,pldp.productlistperdistribpoint_id) qtyweek8,
       GET_REQMATS(rp.date_value1+56,pldp.productlistperdistribpoint_id) qtyweek9,
       GET_REQMATS(rp.date_value1+63,pldp.productlistperdistribpoint_id) qtyweek10,
       GET_REQMATS(rp.date_value1+70,pldp.productlistperdistribpoint_id) qtyweek11,
       GET_REQMATS(rp.date_value1+77,pldp.productlistperdistribpoint_id) qtyweek12
from   businessunit bu, department de, distributionpoint dp, product pr, productgroup pg,
       sizedefinition sz, activity ac, productlistperdistribpoint pldp, reportparam rp,
       languages l--, deliveryscheme ds, standarddeliveryline  sdl
where  de.department_id = dp.department_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 and
       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)
            --   and sdl.productlistperdistribpoint_id=pldp.productlistperdistribpoint_id
            --   and sdl.deliveryscheme_id=ds.deliveryscheme_id

/
create or replace view V_MATREQUIREMENTS_SMG
 (BUSINESSUNITCODE, BUSINEESUNITDESSC, ACTIVITYCODE, PRODUCTCODE, PRODUCTDESC, SIZECODE, PRODUCTGROUPCODE, PRODUCTGROUPDESC, LANGUAGECODE, REPORTPARAM_ID, PRODUCTLISTPERDISTRIBPOINT_ID, DATE_VALUE1, WEEKNR, QTYWEEK1, QTYWEEK2, QTYWEEK3, QTYWEEK4, QTYWEEK5, QTYWEEK6, QTYWEEK7, QTYWEEK8, QTYWEEK9, QTYWEEK10, QTYWEEK11, QTYWEEK12)
as select bu.code businessunitcode, bu.description busineesunitdessc, ac.code activitycode,
       pr.code productcode,-- ds.code DELIVERYSCHEMECODE,
       (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, 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,
       l.code languagecode, rp.reportparam_id,
       pldp.productlistperdistribpoint_id,
       rp.date_value1,
       getisoweekSMG(rp.date_value1) weeknr,
      -- getfirstdeliveryweekforyearSMG(year(rp.date_value1), ds.frequency, ds.offsetweek) firstdelweek,
     --  fdelweek(year(rp.date_value1), getisoweek(rp.date_value1), ds.frequency, ds.offsetweek)isdeliver,
       GET_REQMATS_SMG(rp.date_value1,pldp.productlistperdistribpoint_id) qtyweek1,
       GET_REQMATS_SMG(rp.date_value1+7,pldp.productlistperdistribpoint_id) qtyweek2,
       GET_REQMATS_SMG(rp.date_value1+14,pldp.productlistperdistribpoint_id) qtyweek3,
       GET_REQMATS_SMG(rp.date_value1+21,pldp.productlistperdistribpoint_id) qtyweek4,
       GET_REQMATS_SMG(rp.date_value1+28,pldp.productlistperdistribpoint_id) qtyweek5,
       GET_REQMATS_SMG(rp.date_value1+35,pldp.productlistperdistribpoint_id) qtyweek6,
       GET_REQMATS_SMG(rp.date_value1+42,pldp.productlistperdistribpoint_id) qtyweek7,
       GET_REQMATS_SMG(rp.date_value1+49,pldp.productlistperdistribpoint_id) qtyweek8,
       GET_REQMATS_SMG(rp.date_value1+56,pldp.productlistperdistribpoint_id) qtyweek9,
       GET_REQMATS_SMG(rp.date_value1+63,pldp.productlistperdistribpoint_id) qtyweek10,
       GET_REQMATS_SMG(rp.date_value1+70,pldp.productlistperdistribpoint_id) qtyweek11,
       GET_REQMATS_SMG(rp.date_value1+77,pldp.productlistperdistribpoint_id) qtyweek12
from   businessunit bu, department de, distributionpoint dp, product pr, productgroup pg,
       sizedefinition sz, activity ac, productlistperdistribpoint pldp, reportparam rp,
       languages l--, deliveryscheme ds, standarddeliveryline  sdl
where  de.department_id = dp.department_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 and
       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)
            --   and sdl.productlistperdistribpoint_id=pldp.productlistperdistribpoint_id
            --   and sdl.deliveryscheme_id=ds.deliveryscheme_id

/
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_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 <= GETCURRENTDATE())) 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_AMM
 (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 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
              d.gedescription
             when 'NL' then
              d.nldescription
             else
              d.endescription
           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
 (NOTENUMBER, PACKINGNOTELINE_ID, DELIVERYDATE, PRODUCTID, DELIVEREDQTY)
as select /*version 1.1*/
 pk.notenumber,
 pkl.packingnoteline_id,
 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,*/
 CAST(pkl.deliveredamount AS INT) 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 - 1
   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, TURNOVERGROUPCODE, TURNOVERGROUPDESC, ROUTEID, ROUTENUMBER, ROUTEDESC, DISTRICTCODE, DISTRICTDESC, SYSTEMUSERID, USERNAME, LANGUAGECODE, ROUTEMANAGERNUMBER, ROUTEMANAGERNAME)
as select 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,
       currency.invoiceamountdecimals,
       rc.code reasonCode,
       (select description
          from reasoncode_desc x
         where x.reasoncode_id = rc.reasoncode_id
           and x.language_id = languages.language_id) reasoncodeDesc,
       tg.code turnovergroupCode,
       (select description
          from turnovergroup_desc y
         where y.turnovergroup_id = tg.turnovergroup_id
           and y.language_id = languages.language_id) turnovergroupDesc,
       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, -- creation user name
       languages.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 outer join reasoncode rc
    on mc.reasoncode_id = rc.reasoncode_id
  left outer join turnovergroup tg
    on mc.turnovergroup_id = tg.turnovergroup_id, businessunit bu,
 businessunitsperusergroup bugroup, customer_link cl, invoiceheader ih
  left outer join route r
    on ih.route_id = r.route_id, currency, languages, systemuser s,
 systemuser s2
 where mc.invoicebusinessunit_id = bu.businessunit_id
   and bu.businessunit_id = bugroup.businessunit_id
   and mc.customer_link_id = cl.customer_link_id
   and mc.invoiceheader_id = ih.invoiceheader_id
   and ih.currency_id = currency.currency_id
   and mc.creationuser_id = s.systemuser_id
   and bugroup.usergroup_id = s2.usergroup_id
union
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 = languages.language_id) reasoncodeDesc,
       tg.code turnovergroupCode,
       (select description
          from turnovergroup_desc y
         where y.turnovergroup_id = tg.turnovergroup_id
           and y.language_id = languages.language_id) turnovergroupDesc,
       -1 routeID,
       -1 routeNumber,
       null routeDesc,
       null districtCode,
       null districtDesc,
       s2.systemuser_id systemuserID,
       s.username, -- creation user name
       languages.code languageCode,
       -1 routeManagernumber,
       '' routeManagerName
  from miscellaneouscharge mc
  left outer join reasoncode rc
    on mc.reasoncode_id = rc.reasoncode_id
  left outer join turnovergroup tg
    on mc.turnovergroup_id = tg.turnovergroup_id, businessunit bu,
 businessunitsperusergroup bugroup, customer_link cl, languages,
 systemuser s, systemuser s2
 where mc.invoicebusinessunit_id = bu.businessunit_id
   and bu.businessunit_id = bugroup.businessunit_id
   and mc.customer_link_id = cl.customer_link_id
   and mc.invoiceheader_id is null
   and mc.creationuser_id = s.systemuser_id
   and bugroup.usergroup_id = s2.usergroup_id

/
create or replace view V_MISSINGPRICES_SMG
 (LINETYPE, BILLINGMETHOD, CHAINCODE, CUSTOMERNUMBER, NAME, INVOICEFREQUENCY_ID, PRODUCTGROUPCODE, PRODUCTGROUPDESC, PRODUCTCODE, PRODUCTDESC, SIZECODE, SIZEDESC, FMCODE, FMDESC, DESCR)
as select 1 linetype,
       l.billingmethod,
       (select ch.code from chain ch where ch.chain_id = c.chain_id) chaincode,
       c.customernumber, c.name, c.invoicefrequency_id,
       (select pg.code from productgroup pg where pg.productgroup_id = p.productgroup_id) productgroupcode,
       (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = p.productgroup_id and pgd.language_id = c.language_id) productgroupdesc,
       p.code productcode,
       (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = c.language_id) productdesc,
       s.code sizecode,
       (select sd.description from sizedefinition_desc sd where sd.sizedefinition_id = s.sizedefinition_id and sd.language_id = c.language_id) sizedesc,
       f.code fmcode,
       (select fd.description from finishingmethod_desc fd where fd.finishingmethod_id = f.finishingmethod_id and fd.language_id = c.language_id) fmdesc,
       'Fakturamethode 1 - ohne Mietpreis' descr
from   productlistpercustomer l, customer c, product p, sizedefinition s, finishingmethod f
where  l.billingmethod = 1
and    l.customer_id = c.customer_id
and    l.product_id = p.product_id
and    l.sizedefinition_id = s.sizedefinition_id
and    l.finishingmethod_id = f.finishingmethod_id
and    sysdate between l.dateactive and l.dateinactive --only PLPC lines now active
and    pack_price.Rent_Price_Display(l.customer_id, l.product_id, l.sizedefinition_id, l.finishingmethod_id) is null
and    c.customerranking_id <> 1 -- keine Dummy-ITM-Kunden
union all
select 2 linetype,
       l.billingmethod,
       (select ch.code from chain ch where ch.chain_id = c.chain_id) chaincode,
       c.customernumber, c.name, c.invoicefrequency_id,
       (select pg.code from productgroup pg where pg.productgroup_id = p.productgroup_id) productgroupcode,
       (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = p.productgroup_id and pgd.language_id = c.language_id) productgroupdesc,
       p.code productcode,
       (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = c.language_id) productdesc,
       s.code sizecode,
       (select sd.description from sizedefinition_desc sd where sd.sizedefinition_id = s.sizedefinition_id and sd.language_id = c.language_id) sizedesc,
       f.code fmcode,
       (select fd.description from finishingmethod_desc fd where fd.finishingmethod_id = f.finishingmethod_id and fd.language_id = c.language_id) fmdesc,
       'Fakturamethode 2 - ohne Miet- oder Waschpreis'  descr
from   productlistpercustomer l, customer c, product p, sizedefinition s, finishingmethod f
where  l.billingmethod = 2
and    l.customer_id = c.customer_id
and    l.product_id = p.product_id
and    l.sizedefinition_id = s.sizedefinition_id
and    l.finishingmethod_id = f.finishingmethod_id
and    sysdate between l.dateactive and l.dateinactive --only PLPC lines now active
and    (pack_price.Wash_Price_Display(l.customer_id, l.product_id, l.sizedefinition_id, l.finishingmethod_id) is null
        or pack_price.Rent_Price_Display(l.customer_id, l.product_id, l.sizedefinition_id, l.finishingmethod_id) is null)
and    c.customerranking_id <> 1 -- keine Dummy-ITM-Kunden
union all
select 3 linetype,
       l.billingmethod,
       (select ch.code from chain ch where ch.chain_id = c.chain_id) chaincode,
       c.customernumber, c.name, c.invoicefrequency_id,
       pg.code productgroupcode,
       (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = p.productgroup_id and pgd.language_id = c.language_id) productgroupdesc,
       p.code productcode,
       (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = c.language_id) productdesc,
       s.code sizecode,
       (select sd.description from sizedefinition_desc sd where sd.sizedefinition_id = s.sizedefinition_id and sd.language_id = c.language_id) sizedesc,
       f.code fmcode,
       (select fd.description from finishingmethod_desc fd where fd.finishingmethod_id = f.finishingmethod_id and fd.language_id = c.language_id) fmdesc,
       'Fakturamethode 3 - nur Miete ohne Mietpreis' descr
from   productlistpercustomer l, customer c, product p, sizedefinition s, finishingmethod f, productgroup pg
where  l.billingmethod = 3
and    l.priceusage = 2
and    l.customer_id = c.customer_id
and    l.product_id = p.product_id
and    l.sizedefinition_id = s.sizedefinition_id
and    l.finishingmethod_id = f.finishingmethod_id
and    pg.productgroup_id = p.productgroup_id
and    sysdate between l.dateactive and l.dateinactive --only PLPC lines now active
and    pack_price.Rent_Price_Display(l.customer_id, l.product_id, l.sizedefinition_id, l.finishingmethod_id) is null
and    c.customerranking_id <> 1 -- keine Dummy-ITM-Kunde
and    p.code not IN ('H502', 'H505', 'H506', 'HLV041V', 'HLV042V', 'HLV043V', 'HLV044V', 'HL042V', 'HL044V', 'HL041V', 'HLV042', 'HLV041',
       'HLV032', 'HLV004', 'A54401', 'A54441', 'A7182A', '309046', 'YR0006', 'YR0009', 'A7180', 'C101', 'A7112', 'A7182S', 'KNKJW', 'KNKJS', 'A54421',
       'A7181', 'A54411', 'KNKJSI', 'HL043V', 'HLV12', 'KLKJW', 'KNKJR')
AND    PG.CODE NOT IN ('BKS', 'CONT')
union all
select 4 linetype,
       l.billingmethod,
       ch.code chaincode,
       c.customernumber, c.name, c.invoicefrequency_id,
       pg.code productgroupcode,
       (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = p.productgroup_id and pgd.language_id = c.language_id) productgroupdesc,
       p.code productcode,
       (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = c.language_id) productdesc,
       s.code sizecode,
       (select sd.description from sizedefinition_desc sd where sd.sizedefinition_id = s.sizedefinition_id and sd.language_id = c.language_id) sizedesc,
       f.code fmcode,
       (select fd.description from finishingmethod_desc fd where fd.finishingmethod_id = f.finishingmethod_id and fd.language_id = c.language_id) fmdesc,
       'Fakturamethode 3 - nur Waschpreis ohne Waschpreis' descr
from   productlistpercustomer l, customer c, product p, sizedefinition s, finishingmethod f, chain ch, productgroup pg
where  l.billingmethod = 3
and    l.priceusage = 3
and    l.customer_id = c.customer_id
and    l.product_id = p.product_id
and    l.sizedefinition_id = s.sizedefinition_id
and    l.finishingmethod_id = f.finishingmethod_id
and    pg.productgroup_id = p.productgroup_id
and    ch.chain_id = c.chain_id
and    sysdate between l.dateactive and l.dateinactive --only PLPC lines now active
and    pack_price.Wash_Price_Display(l.customer_id, l.product_id, l.sizedefinition_id, l.finishingmethod_id) is null
and    c.customerranking_id <> 1 -- keine Dummy-ITM-Kunden
and    ch.code not in ('ADVK', 'CHAU', 'SAL', 'SMOV')
and    pg.code not in ('BKS', 'CONT')
and    p.code not in ('30903D', 'A7180', 'A7182A', 'KNKJS', 'KNKJW', 'KNKJR', 'YR0006')
union all
select 5 linetype,
       l.billingmethod,
       ch.code chaincode,
       c.customernumber, c.name, c.invoicefrequency_id,
       pg.code productgroupcode,
       (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = p.productgroup_id and pgd.language_id = c.language_id) productgroupdesc,
       p.code productcode,
       (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = c.language_id) productdesc,
       s.code sizecode,
       (select sd.description from sizedefinition_desc sd where sd.sizedefinition_id = s.sizedefinition_id and sd.language_id = c.language_id) sizedesc,
       f.code fmcode,
       (select fd.description from finishingmethod_desc fd where fd.finishingmethod_id = f.finishingmethod_id and fd.language_id = c.language_id) fmdesc,
       'Fakturamethode 3 - Splitting' descr
from   productlistpercustomer l, customer c, product p, sizedefinition s, finishingmethod f, chain ch, productgroup pg, product_desc pd
where  l.billingmethod = 3
and    l.priceusage = 1
and    l.customer_id = c.customer_id
and    l.product_id = p.product_id
and    l.sizedefinition_id = s.sizedefinition_id
and    l.finishingmethod_id = f.finishingmethod_id
and    pg.productgroup_id = p.productgroup_id
and    ch.chain_id = c.chain_id
and    (p.product_id = pd.product_id
and    pd.language_id = 1)
and    sysdate between l.dateactive and l.dateinactive --only PLPC lines now active
and    (pack_price.Wash_Price_Display(l.customer_id, l.product_id, l.sizedefinition_id, l.finishingmethod_id) is null
       or pack_price.Rent_Price_Display(l.customer_id, l.product_id, l.sizedefinition_id, l.finishingmethod_id) is null)
and    c.customerranking_id <> 1 -- keine Dummy-ITM-Kunde
AND    PG.CODE NOT IN ('BKS', 'CONT')
and    ch.code not in ('ADVK', 'CHAU', 'SAL', 'SMOV')
union all
select 6 linetype,
       l.billingmethod,
       (select ch.code from chain ch where ch.chain_id = c.chain_id) chaincode,
       c.customernumber, c.name, c.invoicefrequency_id,
       (select pg.code from productgroup pg where pg.productgroup_id = p.productgroup_id) productgroupcode,
       (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = p.productgroup_id and pgd.language_id = c.language_id) productgroupdesc,
       p.code productcode,
       (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = c.language_id) productdesc,
       s.code sizecode,
       (select sd.description from sizedefinition_desc sd where sd.sizedefinition_id = s.sizedefinition_id and sd.language_id = c.language_id) sizedesc,
       (select fm.code from finishingmethod fm where l.finishingmethod_id = fm.finishingmethod_id ) fmcode,
       (select fd.description from finishingmethod_desc fd where fd.finishingmethod_id = l.finishingmethod_id and fd.language_id = c.language_id) fmdesc,
       'plpc regels met BM4 met optie "alleen sales prijs" waarvoor geen verkoopprijs bestaat' descr
from   productlistpercustomer l, customer c, product p, sizedefinition s
where  l.billingmethod = 4
and    l.chargewashesonlyforcog = 4
and    l.customer_id = c.customer_id
and    l.product_id = p.product_id
and    l.sizedefinition_id = s.sizedefinition_id
and    sysdate between l.dateactive and l.dateinactive --only PLPC lines now active
and    pack_price.Sales_Price_Display(l.customer_id, l.product_id, l.sizedefinition_id) is null
union all
-- sollte eigentlich kein Ergebnis liefern da kein Kunde FM4 mit Option <> 4 haben sollte!
select 7 linetype,
       l.billingmethod,
       (select ch.code from chain ch where ch.chain_id = c.chain_id) chaincode,
       c.customernumber, c.name, c.invoicefrequency_id,
       (select pg.code from productgroup pg where pg.productgroup_id = p.productgroup_id) productgroupcode,
       (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = p.productgroup_id and pgd.language_id = c.language_id) productgroupdesc,
       p.code productcode,
       (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = c.language_id) productdesc,
       s.code sizecode,
       (select sd.description from sizedefinition_desc sd where sd.sizedefinition_id = s.sizedefinition_id and sd.language_id = c.language_id) sizedesc,
       (select fm.code from finishingmethod fm where l.finishingmethod_id = fm.finishingmethod_id ) fmcode,
       (select fd.description from finishingmethod_desc fd where fd.finishingmethod_id = l.finishingmethod_id and fd.language_id = c.language_id) fmdesc,
       'Fakturamethode 4 - Verkaufspreis' descr
from   productlistpercustomer l, customer c, product p, sizedefinition s
where  l.billingmethod = 4
and    l.chargewashesonlyforcog <> 4
and    l.customer_id = c.customer_id
and    l.product_id = p.product_id
and    l.sizedefinition_id = s.sizedefinition_id
and    sysdate between l.dateactive and l.dateinactive --only PLPC lines now active
and    pack_price.Sales_Price_Display(l.customer_id, l.product_id, l.sizedefinition_id) is null
and    c.customerranking_id <> 1 -- keine Dummy-ITM-Kunden
union all
select 8 linetype,
       l.invoicemethod billingmethod,
       (select ch.code from chain ch where ch.chain_id = c.chain_id) chaincode,
       c.customernumber, c.name, c.invoicefrequency_id,
       null productgroupcode,
       null productgroupdesc,
       w.code productcode,
       (select wd.description from weighingcategory_desc wd where w.weighingcategory_id = wd.weighingcategory_id and wd.language_id = c.language_id) productdesc,
       null sizecode,
       null sizedesc,
       null fmcode,
       null fmdesc,
       'Wiegekategorien sauber' descr
from weighingcategpercustomer l, customer c, weighingcategory w
where w.weighingcategory_id = l.weighingcategory_id
and c.customer_id = l.customer_id
and invoicemethod = 3 -- saubere Verrechnung
and (pack_price.Weight_Price_Display(l.customer_id, l.weighingcategory_id, 'N') is null)
union all
select 9 linetype,
       l.invoicemethod billingmethod,
       (select ch.code from chain ch where ch.chain_id = c.chain_id) chaincode,
       c.customernumber, c.name, c.invoicefrequency_id,
       null productgroupcode,
       null productgroupdesc,
       w.code productcode,
       (select wd.description from weighingcategory_desc wd where w.weighingcategory_id = wd.weighingcategory_id and wd.language_id = c.language_id) productdesc,
       null sizecode,
       null sizedesc,
       null fmcode,
       null fmdesc,
       'Wiegekategorien ungleich sauber'
from weighingcategpercustomer l, customer c, weighingcategory w
where w.weighingcategory_id = l.weighingcategory_id
and c.customer_id = l.customer_id
and l.invoicemethod <> 3 -- keine Verrechnung sauberer Gewichte
and (pack_price.Weight_Price_Display(l.customer_id, l.weighingcategory_id, 'Y') 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(getcurrentdate(), 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(getcurrentdate(), 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(getcurrentdate(), 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(getcurrentdate(), 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, GETDATEONLY(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, SIZECODE, SIZEDESC, LANG, IDCODE, BU_ID, BU_CODE, BU_DESC, CUSTOWNED, CUSTNUMBER, CUSTNAME, COMPLETIONDATE, CONFIRMATIONDATE, WORKORDERNUMBER, MODIFCODE, F_MODIF, WEARERNUMBER, WEARERNAME, GPW_IDCODE, GPW_ISSUEDATE, REASONCODE_DESCR)
as select
  p.code productcode
, ( select sd.code
    from   sizedefinition sd
    where  sd.sizedefinition_id = ui.sizedefinition_id) sizecode
, ( select sdd.description
    from   sizedefinition_desc sdd
    where  sdd.language_id = 1--l.language_id
       and sdd.sizedefinition_id = ui.sizedefinition_id) sizedesc --l.code lang
, 'EN_GB' lang
, ui.primaryid IDcode
, ui.businessunit_id BU_ID
, ( select bu.code
    from   businessunit bu
    where  bu.businessunit_id= ui.businessunit_id ) BU_code
, ( select bu.description
    from   businessunit bu
    where  bu.businessunit_id= ui.businessunit_id ) BU_desc
, ui.customerowned custowned--, 'Y' custowned
, ( select c.customernumber
    from   customer c
    where  wear.customer_id = c.customer_id ) custnumber
, ( select c.name
    from   customer c
    where  wear.customer_id = c.customer_id ) custname
, w.completiondate
, w.confirmationdate
, w.workordernumber, (select m.code from modification m where m.modification_id=uim.modification_id) modifcode--m.code modifcode
, f_modifications(ui.uniqueitem_id, 'U') f_modif
, wear.wearernumber wearernumber
, wear.fullname wearername
, ui.primaryid GPW_idcode
, ufi.lastissuedate GPW_issuedate
, (select rcd.code from reasoncode rcd where rcd.reasoncode_id = w.reasoncode_id) reasoncode_descr
from
  uniqueitem ui
     left outer join uniqueitemmodification uim
      --  left outer join modification m
        --   on uim.modification_id= m.modification_id
        on uim.uniqueitem_id=ui.uniqueitem_id
     left outer join uniqueitemfixedinfo ufi
        left outer join workorder w
           on ufi.issuedbyworkorder_id=w.workorder_id
        on ufi.uniqueitem_id=ui.uniqueitem_id
  , uniqueitemnonpool unp--, languages l
, product p
, wearer wear
, weareremployment wemp--, v_garmentsperwearer vgpw
where
      p.product_id = ui.product_id
  and unp.uniqueitem_id=ui.uniqueitem_id
  and  unp.weareremployment_id=wemp.weareremployment_id
  and wemp.wearer_id=wear.wearer_id    and w.workordernumber is not null  --and m.code is not null
  and exists (select m.code from modification m where m.modification_id = uim.modification_id)
  and w.reasoncode_id in ( select reasoncode_id
                           from reasoncode rc
                           where  rc.code in ('20', '30', '40', '50', '51', '60', '61',
                                              '62', '64', '65', '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_MONTHLYLOANS_LLG
 (CUSTOMERNUMBER, CUSTOMERNAME, BUCODE, BUDESCRIPTION, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, PRODUCT_ID, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDEFINITION_ID, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHOD_ID, FINISHINGMETHODCODE, FINISHINGMETHODDESCRIPTION, PACKINGNOTENUMBER, PROCESSBUSINESSUNIT_ID, DELIVERYDATE, DELIVERYDATE_MONTH, DELIVERYDATE_YEAR, ORIGIN, AMOUNT, FIXEDAMOUNT, REFERENCE, PROCESSED, CAUSENOTENUMBER
, CAUSENOTEDELIVERYDATE, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE, SOILCOUNTSUBTYPE, REASONCODE_ID, RC_CODE, RC_DESCRIPTION, ADJ_RC_CODE, ADJ_RC_DESCRIPTION, RENTALCHARGE, LOANCHARGE)
as SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME,
  (select bu.code from businessunit bu where bu.businessunit_id = CUSTOMER.DEFAULTBUSINESSUNIT_ID) bucode,
  (select bu.description from businessunit bu where bu.businessunit_id = CUSTOMER.DEFAULTBUSINESSUNIT_ID) budescription,
  DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
  DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
  PRODUCT.PRODUCT_ID,
  PRODUCT.CODE PRODUCTCODE,
  (SELECT DESCRIPTION FROM PRODUCT_DESC P WHERE P.PRODUCT_ID = DELIVERYVARIATIONS.PRODUCT_ID
     AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  PRODUCTDESCRIPTION,
  DELIVERYVARIATIONS.SIZEDEFINITION_ID,
  (select SIZEDEFINITION.CODE from sizedefinition where sizedefinition.sizedefinition_id = deliveryvariations.sizedefinition_id) sizecode,
  (SELECT DESCRIPTION FROM SIZEDEFINITION_DESC S WHERE S.SIZEDEFINITION_ID = DELIVERYVARIATIONS.SIZEDEFINITION_ID
     AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  SIZEDESCRIPTION,
  FINISHINGMETHOD.FINISHINGMETHOD_ID,
  FINISHINGMETHOD.CODE FINISHINGMETHODCODE,
  (SELECT DESCRIPTION FROM FINISHINGMETHOD_DESC F WHERE F.FINISHINGMETHOD_ID = DELIVERYVARIATIONS.FINISHINGMETHOD_ID
     AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  FINISHINGMETHODDESCRIPTION,
  PACKINGNOTE.NOTENUMBER PACKINGNOTENUMBER, PACKINGNOTE.PROCESSBUSINESSUNIT_ID,
  DELIVERYVARIATIONS.DELIVERYDATE,
  trim(to_char(to_date(deliveryvariations.deliverydate, 'DD-MM-YYYY'), 'Month')) deliverydate_month,
  to_char(year(deliveryvariations.deliverydate)) deliverydate_year,
  DELIVERYVARIATIONS.ORIGIN,
  DELIVERYVARIATIONS.AMOUNT,
  DELIVERYVARIATIONS.FIXEDAMOUNT, DELIVERYVARIATIONS.REFERENCE, DELIVERYVARIATIONS.PROCESSED,
  CAUSENOTE.NOTENUMBER CAUSENOTENUMBER, CAUSENOTE.DELIVERYDATE CAUSENOTEDELIVERYDATE,
  DELIVERYVARIATIONS.SYSTEMUSER_ID, GETDATEONLY(DELIVERYVARIATIONS.TIMESTAMP) TIMESTAMP, LANGUAGES.CODE LANGUAGECODE,
  DELIVERYVARIATIONS.SOILCOUNTSUBTYPE,
  DELIVERYVARIATIONS.REASONCODE_ID,
  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 = LANGUAGES.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 = LANGUAGES.LANGUAGE_ID) ADJ_RC_DESCRIPTION,
  pack_price.Rent_Price(customer.customer_id,deliveryvariations.product_id,deliveryvariations.sizedefinition_id,deliveryvariations.finishingmethod_id,deliveryvariations.deliverydate) rentalcharge,
  pack_price.Loan_Price(customer.customer_id,deliveryvariations.product_id,deliveryvariations.sizedefinition_id,deliveryvariations.finishingmethod_id,deliveryvariations.deliverydate) loancharge
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT,
  PRODUCT, FINISHINGMETHOD, LANGUAGES,
  DELIVERYVARIATIONS
    LEFT OUTER JOIN PACKINGNOTE ON (DELIVERYVARIATIONS.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID)
    LEFT OUTER JOIN PACKINGNOTE CAUSENOTE ON (DELIVERYVARIATIONS.CAUSENOTE_ID = CAUSENOTE.PACKINGNOTE_ID)
    LEFT OUTER JOIN REASONCODE RC ON (DELIVERYVARIATIONS.REASONCODE_ID = RC.REASONCODE_ID)
    LEFT OUTER JOIN REASONCODE ADJ_RC ON (DELIVERYVARIATIONS.ADJUSTMENTREASON_ID = ADJ_RC.REASONCODE_ID)
WHERE DELIVERYVARIATIONS.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
  AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
  AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND DELIVERYVARIATIONS.PRODUCT_ID = PRODUCT.PRODUCT_ID
  AND DELIVERYVARIATIONS.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
  AND DEPARTMENT.ACTIVE = 'Y'
  AND DELIVERYVARIATIONS.ORIGIN = 3

/
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_MONTHLYUSAGEDECREASES_LLG
 (CUSTOMERNUMBER, CUSTOMERNAME, BUCODE, BUDESCRIPTION, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, PRODUCT_ID, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDEFINITION_ID, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHOD_ID, FINISHINGMETHODCODE, FINISHINGMETHODDESCRIPTION, PACKINGNOTENUMBER, PROCESSBUSINESSUNIT_ID, DELIVERYDATE, DELIVERYDATE_MONTH, DELIVERYDATE_YEAR, ORIGIN, AMOUNT, FIXEDAMOUNT, REFERENCE, PROCESSED, CAUSENOTENUMBER
, CAUSENOTEDELIVERYDATE, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE, SOILCOUNTSUBTYPE, REASONCODE_ID, RC_CODE, RC_DESCRIPTION, ADJ_RC_CODE, ADJ_RC_DESCRIPTION, RENTALCHARGE)
as SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME,
  (select bu.code from businessunit bu where bu.businessunit_id = CUSTOMER.DEFAULTBUSINESSUNIT_ID) bucode,
  (select bu.description from businessunit bu where bu.businessunit_id = CUSTOMER.DEFAULTBUSINESSUNIT_ID) budescription,
  DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
  DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
  PRODUCT.PRODUCT_ID,
  PRODUCT.CODE PRODUCTCODE,
  (SELECT DESCRIPTION FROM PRODUCT_DESC P WHERE P.PRODUCT_ID = DELIVERYVARIATIONS.PRODUCT_ID
     AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  PRODUCTDESCRIPTION,
  DELIVERYVARIATIONS.SIZEDEFINITION_ID,
  (select SIZEDEFINITION.CODE from sizedefinition where sizedefinition.sizedefinition_id = deliveryvariations.sizedefinition_id) sizecode,
  (SELECT DESCRIPTION FROM SIZEDEFINITION_DESC S WHERE S.SIZEDEFINITION_ID = DELIVERYVARIATIONS.SIZEDEFINITION_ID
     AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  SIZEDESCRIPTION,
  FINISHINGMETHOD.FINISHINGMETHOD_ID,
  FINISHINGMETHOD.CODE FINISHINGMETHODCODE,
  (SELECT DESCRIPTION FROM FINISHINGMETHOD_DESC F WHERE F.FINISHINGMETHOD_ID = DELIVERYVARIATIONS.FINISHINGMETHOD_ID
     AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  FINISHINGMETHODDESCRIPTION,
  PACKINGNOTE.NOTENUMBER PACKINGNOTENUMBER, PACKINGNOTE.PROCESSBUSINESSUNIT_ID,
  DELIVERYVARIATIONS.DELIVERYDATE,
  trim(to_char(to_date(deliveryvariations.deliverydate, 'DD-MM-YYYY'), 'Month')) deliverydate_month,
  to_char(year(deliveryvariations.deliverydate)) deliverydate_year,
  DELIVERYVARIATIONS.ORIGIN,
  DELIVERYVARIATIONS.AMOUNT,
  DELIVERYVARIATIONS.FIXEDAMOUNT, DELIVERYVARIATIONS.REFERENCE, DELIVERYVARIATIONS.PROCESSED,
  CAUSENOTE.NOTENUMBER CAUSENOTENUMBER, CAUSENOTE.DELIVERYDATE CAUSENOTEDELIVERYDATE,
  DELIVERYVARIATIONS.SYSTEMUSER_ID, GETDATEONLY(DELIVERYVARIATIONS.TIMESTAMP) TIMESTAMP, LANGUAGES.CODE LANGUAGECODE,
  DELIVERYVARIATIONS.SOILCOUNTSUBTYPE,
  DELIVERYVARIATIONS.REASONCODE_ID,
  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 = LANGUAGES.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 = LANGUAGES.LANGUAGE_ID) ADJ_RC_DESCRIPTION,
  pack_price.Rent_Price(customer.customer_id,deliveryvariations.product_id,deliveryvariations.sizedefinition_id,deliveryvariations.finishingmethod_id,deliveryvariations.deliverydate) rentalcharge
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT,
  PRODUCT, FINISHINGMETHOD, LANGUAGES,
  DELIVERYVARIATIONS
    LEFT OUTER JOIN PACKINGNOTE ON (DELIVERYVARIATIONS.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID)
    LEFT OUTER JOIN PACKINGNOTE CAUSENOTE ON (DELIVERYVARIATIONS.CAUSENOTE_ID = CAUSENOTE.PACKINGNOTE_ID)
    LEFT OUTER JOIN REASONCODE RC ON (DELIVERYVARIATIONS.REASONCODE_ID = RC.REASONCODE_ID)
    LEFT OUTER JOIN REASONCODE ADJ_RC ON (DELIVERYVARIATIONS.ADJUSTMENTREASON_ID = ADJ_RC.REASONCODE_ID)
WHERE DELIVERYVARIATIONS.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
  AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
  AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND DELIVERYVARIATIONS.PRODUCT_ID = PRODUCT.PRODUCT_ID
  AND DELIVERYVARIATIONS.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
  AND DEPARTMENT.ACTIVE = 'Y'
  AND DELIVERYVARIATIONS.ORIGIN = 3
  AND DELIVERYVARIATIONS.AMOUNT < 0

/
create or replace view V_MONTHLYUSAGEINCREASES_LLG
 (CUSTOMERNUMBER, CUSTOMERNAME, BUCODE, BUDESCRIPTION, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, PRODUCT_ID, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDEFINITION_ID, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHOD_ID, FINISHINGMETHODCODE, FINISHINGMETHODDESCRIPTION, PACKINGNOTENUMBER, PROCESSBUSINESSUNIT_ID, DELIVERYDATE, DELIVERYDATE_MONTH, DELIVERYDATE_YEAR, ORIGIN, AMOUNT, FIXEDAMOUNT, REFERENCE, PROCESSED, CAUSENOTENUMBER
, CAUSENOTEDELIVERYDATE, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE, SOILCOUNTSUBTYPE, REASONCODE_ID, RC_CODE, RC_DESCRIPTION, ADJ_RC_CODE, ADJ_RC_DESCRIPTION, RENTALCHARGE)
as SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME,
  (select bu.code from businessunit bu where bu.businessunit_id = CUSTOMER.DEFAULTBUSINESSUNIT_ID) bucode,
  (select bu.description from businessunit bu where bu.businessunit_id = CUSTOMER.DEFAULTBUSINESSUNIT_ID) budescription,
  DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
  DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
  PRODUCT.PRODUCT_ID,
  PRODUCT.CODE PRODUCTCODE,
  (SELECT DESCRIPTION FROM PRODUCT_DESC P WHERE P.PRODUCT_ID = DELIVERYVARIATIONS.PRODUCT_ID
     AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  PRODUCTDESCRIPTION,
  DELIVERYVARIATIONS.SIZEDEFINITION_ID,
  (select SIZEDEFINITION.CODE from sizedefinition where sizedefinition.sizedefinition_id = deliveryvariations.sizedefinition_id) sizecode,
  (SELECT DESCRIPTION FROM SIZEDEFINITION_DESC S WHERE S.SIZEDEFINITION_ID = DELIVERYVARIATIONS.SIZEDEFINITION_ID
     AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  SIZEDESCRIPTION,
  FINISHINGMETHOD.FINISHINGMETHOD_ID,
  FINISHINGMETHOD.CODE FINISHINGMETHODCODE,
  (SELECT DESCRIPTION FROM FINISHINGMETHOD_DESC F WHERE F.FINISHINGMETHOD_ID = DELIVERYVARIATIONS.FINISHINGMETHOD_ID
     AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  FINISHINGMETHODDESCRIPTION,
  PACKINGNOTE.NOTENUMBER PACKINGNOTENUMBER, PACKINGNOTE.PROCESSBUSINESSUNIT_ID,
  DELIVERYVARIATIONS.DELIVERYDATE,
  trim(to_char(to_date(deliveryvariations.deliverydate, 'DD-MM-YYYY'), 'Month')) deliverydate_month,
  to_char(year(deliveryvariations.deliverydate)) deliverydate_year,
  DELIVERYVARIATIONS.ORIGIN,
  DELIVERYVARIATIONS.AMOUNT,
  DELIVERYVARIATIONS.FIXEDAMOUNT, DELIVERYVARIATIONS.REFERENCE, DELIVERYVARIATIONS.PROCESSED,
  CAUSENOTE.NOTENUMBER CAUSENOTENUMBER, CAUSENOTE.DELIVERYDATE CAUSENOTEDELIVERYDATE,
  DELIVERYVARIATIONS.SYSTEMUSER_ID, GETDATEONLY(DELIVERYVARIATIONS.TIMESTAMP) TIMESTAMP, LANGUAGES.CODE LANGUAGECODE,
  DELIVERYVARIATIONS.SOILCOUNTSUBTYPE,
  DELIVERYVARIATIONS.REASONCODE_ID,
  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 = LANGUAGES.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 = LANGUAGES.LANGUAGE_ID) ADJ_RC_DESCRIPTION,
  pack_price.Rent_Price(customer.customer_id,deliveryvariations.product_id,deliveryvariations.sizedefinition_id,deliveryvariations.finishingmethod_id,deliveryvariations.deliverydate) rentalcharge
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT,
  PRODUCT, FINISHINGMETHOD, LANGUAGES,
  DELIVERYVARIATIONS
    LEFT OUTER JOIN PACKINGNOTE ON (DELIVERYVARIATIONS.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID)
    LEFT OUTER JOIN PACKINGNOTE CAUSENOTE ON (DELIVERYVARIATIONS.CAUSENOTE_ID = CAUSENOTE.PACKINGNOTE_ID)
    LEFT OUTER JOIN REASONCODE RC ON (DELIVERYVARIATIONS.REASONCODE_ID = RC.REASONCODE_ID)
    LEFT OUTER JOIN REASONCODE ADJ_RC ON (DELIVERYVARIATIONS.ADJUSTMENTREASON_ID = ADJ_RC.REASONCODE_ID)
WHERE DELIVERYVARIATIONS.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
  AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
  AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND DELIVERYVARIATIONS.PRODUCT_ID = PRODUCT.PRODUCT_ID
  AND DELIVERYVARIATIONS.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
  AND DEPARTMENT.ACTIVE = 'Y'
  AND DELIVERYVARIATIONS.ORIGIN = 3
  AND DELIVERYVARIATIONS.AMOUNT > 0

/
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_MONTH_INVENT_UTILIZATION_ANG
 (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
, 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, 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(sda.amount),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(sda.amount *
         ( 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
, 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
, standarddeliveryamount sda, standarddeliveryline sdl, productlistperdistribpoint plpd
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
and sda.standarddeliveryline_id=sdl.standarddeliveryline_id
and sdl.productlistperdistribpoint_id=plpd.productlistperdistribpoint_id
and plpd.distributionpoint_id=dh.distributionpoint_link_id
and plpd.product_id=dh.product_link_id
and plpd.sizedefinition_id=dh.sizedefinition_link_id
and plpd.finishingmethod_id=dh.finishingmethod_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.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_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)
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
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_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_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.deliveredqty,
       y.scannedqty,
       y.orderedqty - y.deliveredqty balance,
       y.approvedqty,
       y.actualdelivery,
       y.deliveredqty - y.actualdelivery 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_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_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)
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
   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 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 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
            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)
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 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
                   then 0 -- okay
                   else case when z.pack_qty > z.scan_qty
                         then 1 -- missing qty
                         else 2 -- exceeding qty
                        end
                  end
           end
       end  status_number,
       abs(z.pack_qty - z.scan_qty) status_qty,
       case when m.stackcheckproduct_id is null
         then 0
         else z.pack_qty - z.scan_qty
       end missing_qty,  -- negative when exceeding
       case when m.stackcheckproduct_id is null
         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
 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,
       greatest(count(distinct y.customer_id)-1,0) mixed_customers
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 customer_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 customer_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,
       nvl(mbc.relatedcustomer_id,-1) customer_id
  from multireadscanbatch mb,
       multireadscanbatchcontents mbc
 where mbc.multireadscanbatch_id = mb.multireadscanbatch_id
--   and mbc.product_id is not null
) 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_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_NONBUSINESSDAYS_LLG
 (CUSTOMER_ID, CUSTOMERNUMBER, SEARCHNAME, BUCODE, CLOSESTATUS, MONTH_DATE, YEAR_DATE, STARTDATE, ENDDATE)
as select c.customer_id,
       c.customernumber,
       c.searchname,
       bu.code bucode,
       nbd.closestatus,
       month(nbd.nonbusinessday) month_date,
       year(nbd.nonbusinessday) year_date,
       min(nbd.nonbusinessday) startdate,
       max(nbd.nonbusinessday) enddate
from nonbusinessday nbd,
     customer c,
     businessunit bu
where nbd.customer_id = c.customer_id
and c.invoicefrequency_id in (10, 110, 115)
and c.defaultbusinessunit_id = bu.businessunit_id
group by c.customer_id, c.customernumber, c.searchname, nbd.closestatus, bu.code, month(nbd.nonbusinessday), year(nbd.nonbusinessday)

/
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<=GETCURRENTDATE() and cu.dateinactive>GETCURRENTDATE()
      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<=GETCURRENTDATE() and cu.dateinactive>GETCURRENTDATE()
      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, PRODUCTCODE, PRODUCTDESCRIPTION, SIZECODE, FINMETHCODE, CIRCULATINGINVENTORY, BILLINGMETHOD, CHANGESPERWEEK, MINIMUMTURNAROUND, MINIMUMQUANTITY, DELAYEDEVENEXCHANGE, STARTDATE, RENTALPRICE, CUSTOMERLASTINCREASE, GENERALLASTINCREASE, ENDDATE, DELIVERYDAY, LANGUAGECODE, SIZE_DESC, RENTPRICEPERFREQUENCY)
as select
  prd.product_id, sizedefinition.sizedefinition_id, finishingmethod.finishingmethod_id
, productlistpercustomer.customer_id customerid, 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
, sizedefinition.code sizeCode ,finishingmethod.code finMethCode
, ( select sum(rqa.quantity)
  from  productlistperdistribpoint pldip, rentalqtyadjustment rqa, distributionpoint dip, department de
  where rqa.productlistperdistribpoint_id = pldip.productlistperdistribpoint_id
        and pldip.distributionpoint_id = dip.distributionpoint_id
            and dip.department_id = de.department_id
                and de.customer_id = productlistpercustomer.customer_id
        and productlistpercustomer.product_id = pldip.product_id
        and productlistpercustomer.sizedefinition_id = pldip.sizedefinition_id
        and productlistpercustomer.finishingmethod_id = pldip.finishingmethod_id
        and rqa.adjustmentdate <= GETCURRENTDATE()
  ) CirculatingInventory
, productlistpercustomer.billingmethod, productlistpercustomer.changesperweek
, productlistpercustomer.minimumturnaround, productlistpercustomer.minimumquantity
,  productlistpercustomer.delayedevenexchange, productlistpercustomer.dateactive Startdate
, pack_price.Rent_Price(productlistpercustomer.customer_id, prd.product_id, sizedefinition.sizedefinition_id, finishingmethod.finishingmethod_id, NULL, 1) RentalPrice
/*
-- this is how it was before order 20010677
, ( select customerrentprice.startdate from customerrentprice
  where customerrentprice.customerrentprice_id in
        (select max(crp.customerrentprice_id) from customerrentprice crp
        where crp.price = pack_price.Rent_Price(productlistpercustomer.customer_id,prd.product_id,sizedefinition.sizedefinition_id,finishingmethod.finishingmethod_id, NULL,1))
  ) CustomerLastIncrease
, ( select GeneralRentPrice.startdate from GeneralRentPrice
  where GeneralRentPrice.Generalrentprice_Id in
        (select max(grp.Generalrentprice_Id) from GeneralRentPrice grp
        where grp.price = pack_price.Rent_Price(productlistpercustomer.customer_id,prd.product_id,sizedefinition.sizedefinition_id,finishingmethod.finishingmethod_id, NULL,1))
  ) GeneralLastIncrease
  */
  , case when substr(
    pack_price.Rent_Price_Details(productlistpercustomer.customer_id, prd.product_id, sizedefinition.sizedefinition_id, finishingmethod.finishingmethod_id, NULL, 1),22,1) ='C'
    then to_date(substr(pack_price.Rent_Price_Details(productlistpercustomer.customer_id, prd.product_id, sizedefinition.sizedefinition_id, finishingmethod.finishingmethod_id, NULL, 1),14,8),'YYYYMMDD')
    else null
  end CustomerLastIncrease
, case when substr(
    pack_price.Rent_Price_Details(productlistpercustomer.customer_id, prd.product_id, sizedefinition.sizedefinition_id, finishingmethod.finishingmethod_id, NULL, 1),22,1) ='G'
    then to_date(substr(pack_price.Rent_Price_Details(productlistpercustomer.customer_id, prd.product_id, sizedefinition.sizedefinition_id, finishingmethod.finishingmethod_id, NULL, 1),14,8),'YYYYMMDD')
    else null
  end GeneralLastIncrease
, productlistpercustomer.dateinactive Enddate
, cast(F_PRODUCTDELIVERYDAYS(productlistpercustomer.productlistpercustomer_id, Languages.Language_Id) as varchar2(7)) DeliveryDay
, languages.code languagecode
, (select sd.description from sizedefinition_desc sd where sizedefinition.sizedefinition_id = sd.sizedefinition_id and languages.language_id=sd.language_id) Size_desc
, productlistpercustomer.rentpriceperfrequency
from
productlistpercustomer, product prd, sizedefinition, finishingmethod, languages
where  productlistpercustomer.product_id = prd.product_id
and productlistpercustomer.sizedefinition_id = sizedefinition.sizedefinition_id
and productlistpercustomer.finishingmethod_id = finishingmethod.finishingmethod_id

/
create or replace view V_NOTINVOICEDDNSN_SMG
 (LINETYPE, NOTENUMBER, DELIVERYDATE, STATUSDESC, PLANTCODE, CUSTOMERNUMBER, CUSTNAME, INVOICESTATUS, INVOICEFREQ, PROCESSEDDATETIME, INVOICEFREQ_DESC)
as select --deliverynotes
       1 linetype, pn.notenumber, pn.deliverydate,
       (select sd.description from status_desc sd where sd.status_id = s.status_id and sd.language_id = c.language_id) statusdesc,
       (select p.code from plant p, businessunit bu where pn.processbusinessunit_id = bu.businessunit_id and bu.plant_id = p.plant_id) plantcode,
       c.customernumber, c.name custname, pn.invoicestatus,
       c.invoicefrequency_id invoicefreq,
       pn.processedtimestamp processeddatetime,
       (select ifdesc.description from invoicefrequency_desc ifdesc where ifdesc.invoicefrequency_id = c.invoicefrequency_id and ifdesc.language_id = c.language_id) invoicefreq_desc
from packingnote pn
     join distributionpoint dpl on pn.distributionpoint_id = dpl.distributionpoint_id
     join department d on dpl.department_id = d.department_id
     join customer c on d.customer_id = c.customer_id
     join status s on pn.status_id = s.status_id
     --join businessunit procbu on pn.processbusinessunit_id = procbu.businessunit_id
     --join plant p on procbu.plant_id = p.plant_id
where pn.freeofchargereason_id is null
      and (exists (select pnl.product_id
                   from packingnoteline pnl, product p
                   where pnl.packingnote_id = pn.packingnote_id
                         and p.product_id = pnl.product_id
                         and pnl.invoiceheader_id is null)
            or exists (select pnc.packingnotecontainer_id from packingnotecontainer pnc where pnc.packingnote_id = pn.packingnote_id))
      and s.statustype = 'PN' and (s.code = 30 or s.code = 20 or s.code = 10)
      and pn.invoicestatus <> 2
union all
select --salesnotes
       2 linetype, wo.workordernumber notenumber, wo.completiondate deliverydate,
       (select sd.description from status_desc sd where sd.status_id = wo.status_id and sd.language_id = cl.language_id) statusdesc,
       (select p.code from plant p, businessunit bu where wo.businessunit_id = bu.businessunit_id and bu.plant_id = p.plant_id) plantcode,
       cl.customernumber, cl.name custname, 0 invoicestatus,
       cl.invoicefrequency_id invoicefreq,
       wo.neededdate processeddatetime,
       (select ifdesc.description from invoicefrequency_desc ifdesc where ifdesc.invoicefrequency_id = cl.invoicefrequency_id and ifdesc.language_id = cl.language_id) invoicefreq_desc
from workorder wo join customer cl on wo.customer_link_id = cl.customer_id
where wo.origin = 6 and wo.invoiceheader_id is null
      and wo.status_id = (select s.status_id from status s where s.statustype='WO' and s.code='30')

/
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_NRWASHESPERPRODUCT_STX
 (CUSTOMERNUMBER, CUSTOMERNAME, PRODUCTCODE, NRWASHES, YEAR, WEEK, MONTH, YEARWEEK, PRODUCT_DESC, LANGUAGE_ID, LANGUAGECODE, SIZECODE)
as select c.customernumber, c.name customername, p.code productcode, dh.amountdelivered nrwashes, YEAR(dh.deliverydate) year, getisoweek(dh.deliverydate) week, month(dh.deliverydate) month,
YEAR(dh.deliverydate)*100+getisoweek(dh.deliverydate) yearweek,
(select pd.description from product_desc pd where pd.product_id=p.product_id and languages.language_id=pd.language_id) product_desc, languages.language_id, languages.code languagecode,
sd.code sizecode
from deliveryhistory dh join customer c on dh.customer_link_id=c.customer_id
join product p on p.product_id=dh.product_link_id
join sizedefinition sd on sd.sizedefinition_id=dh.sizedefinition_link_id
cross join languages
where  dh.amountdelivered<>0
and p.typeofmerchandise=2

/
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
  cu.customernumber, cu.name customerName, bu.code businessunitCode, BU.BUSINESSUNIT_ID, address.city,
  DEP.DEPARTMENTNUMBER, DEP.DESCRIPTION DEPARTMENTDESC, w.wearernumber, w.fullname wearername,
  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, wearer w,
  languages
where uq.poolitem = 2 -- nonpol
  and uq.businessunit_id = bu.businessunit_id
  and uq.status_id = status.status_id
  and status.code = '20' -- in circulation
  and status.statustype = 'UI' -- unique item
  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
  and weem.wearer_id = w.wearer_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)
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
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)
      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)
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
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)
      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)
as SELECT PACKINGNOTE.PACKINGNOTE_ID PACKINGNOTEID,
 PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME,
 DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
 DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
 PACKINGNOTE.DELIVERYDATE,
 ROUTE.DESCRIPTION ROUTEDESCRIPTION,
 LANGUAGES.CODE LANGUAGECODE,
 CASE WHEN CUSTOMER.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
  , PACKINGNOTE.STOPNUMBER, ROUTE.PUTUPREPORTPERCUSTOMER
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, PLANTDEPARTMENT,
       STATUS, BUSINESSUNIT PROCESSBU,
       PACKINGNOTE
       LEFT OUTER JOIN ROUTECONTROL ON (PACKINGNOTE.ROUTECONTROL_ID = ROUTECONTROL.ROUTECONTROL_ID )
        LEFT OUTER JOIN ROUTE ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID,
      LANGUAGES
   WHERE PACKINGNOTE.STATUS_ID = STATUS.STATUS_ID
  AND STATUS.STATUSTYPE = 'PN'
  AND CAST(STATUS.CODE AS NUMERIC)<=20
  AND PACKINGNOTE.PLANTDEPARTMENT_ID = PLANTDEPARTMENT.PLANTDEPARTMENT_ID
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
  AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
  AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID

/
create or replace view V_OPTIMIZEDLOADPACKINGLINE
 (PACKINGNOTEID, PRODUCTCODE, PRODUCTDESCRIPTION, SIZECODE, FINISHINGMETHODCODE, PACKINGSEQUENCE, TOBEDELIVEREDAMOUNT, LANGUAGECODE, PUTUPTYPE, PACKINGNOTELINE_ID, BUNDLEQTY, SEQUENCENUMBER)
as SELECT PACKINGNOTELINE.PACKINGNOTE_ID,
  PRODUCT.CODE PRODUCTCODE,
  (SELECT DESCRIPTION FROM PRODUCT_DESC P WHERE P.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
     AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  PRODUCTDESCRIPTION,
  SIZEDEFINITION.CODE SIZECODE,
  FINISHINGMETHOD.CODE FINISHINGMETHODCODE,
  PACKINGNOTELINE.PACKINGSEQUENCE,
  PACKINGNOTELINE.TOBEDELIVEREDAMOUNT,
  LANGUAGES.CODE LANGUAGECODE,
  PACKINGNOTELINE.PUTUPTYPE,
  PACKINGNOTELINE.PACKINGNOTELINE_ID,
  PACKINGNOTELINE.BUNDLEQTY,
  PSZ.SEQUENCENUMBER
FROM PACKINGNOTELINE , FINISHINGMETHOD ,
      PRODUCT,
      SIZEDEFINITION, LANGUAGES
      , PRODUCTSIZE PSZ
WHERE PACKINGNOTELINE.PRODUCT_ID = PRODUCT.PRODUCT_ID
  AND PACKINGNOTELINE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
  AND FINISHINGMETHOD.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
      AND PRODUCT.PRODUCT_ID = PSZ.PRODUCT_ID
          AND PSZ.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID

/
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,
       orderpriority op,
       customer cu,
       customerranking cr,
       distributionpoint dp,
       weareremployment we,
       wearer wr,
       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  wo.workorder_id = x.workorder_id
  and  op.orderpriority_id = wo.orderpriority_id
  and  cu.customer_id = wo.customer_link_id
  and  cr.customerranking_id(+) = cu.customerranking_id
  and  dp.distributionpoint_id(+) = wo.distributionpoint_link_id
  and  we.weareremployment_id(+) = wo.weareremployment_link_id
  and  wr.wearer_id(+) = we.wearer_id
  and  pl.picklist_id = x.picklist_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
       plps.pickinglinenumber 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,
       plps.qtytopick qtyrequiredlocation, --per location (from picklistpickingsequence)
       (pll.qtytopick-pll.qtypicked) qtytopickproduct, --per product
       (plps.qtytopick-nvl(plps.qtypicked,0)) qtytopicklocation, --per location (from picklistpickingsequence)
       pll.qtypicked qtypickedproduct,
       plps.qtypicked 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, picklistlinelocation pllo,
     stockroomlocation sl, stockroom s,
     stockquantity sq, stockreservationpergrade srg, stockdefinitionperitem sdi,
     --product prd, sizedefinition sd,
     qualitygrade qg, picklistpickingsequence plps,
     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
and plps.picklistline_id = pll.picklistline_id

/
create or replace view V_ORDEREDCORRECTIONNEW
 (STOCKROOMCODE, PRODUCTCODE, SIZECODE, STOCKRESERVATIONPERGRADE_ID, QTYNONUNIQUEORDERED, QTYNONUNIQUEORDEREDDIRECTISSUE, QTYUNIQUEORDERED, QTYUNIQUEORDEREDDIRECTISSUE, OUTSTANDINGNONUNIQUE, OUTSTANDINGUNIQUE, OUTSTANDINGNONUNIQUEDI, OUTSTANDINGUNIQUEDI)
as (select sr.CODE,
       p.CODE,
       s.CODE,
       srg.STOCKRESERVATIONPERGRADE_ID,
       srg.QTYNONUNIQUEORDERED,
       srg.QTYNONUNIQUEORDEREDDIRECTISSUE,
       srg.QTYUNIQUEORDERED,
       srg.QTYUNIQUEORDEREDDIRECTISSUE,
       F_OrderedCorrection(sdi.Stockroom_id, sdi.Product_id, sdi.SizeDefinition_id, sdi.Customer_id, 'N', 'N') OutstandingNonUnique,
       F_OrderedCorrection(sdi.Stockroom_id, sdi.Product_id, sdi.SizeDefinition_id, sdi.Customer_id, 'Y', 'N') OutstandingUnique,
       F_OrderedCorrection(sdi.Stockroom_id, sdi.Product_id, sdi.SizeDefinition_id, sdi.Customer_id, 'N', 'Y') OutstandingNonUniqueDI,
       F_OrderedCorrection(sdi.Stockroom_id, sdi.Product_id, sdi.SizeDefinition_id, sdi.Customer_id, 'Y', 'Y') OutstandingUniqueDI
from stockreservationpergrade srg, stockdefinitionperitem sdi, product p, sizedefinition s, qualitygrade q, stockroom sr
where srg.STOCKDEFINITIONPERITEM_ID = sdi.STOCKDEFINITIONPERITEM_ID
and p.PRODUCT_ID = sdi.PRODUCT_ID
and s.SIZEDEFINITION_ID = sdi.SIZEDEFINITION_ID
and sr.STOCKROOM_ID = sdi.STOCKROOM_ID
and q.QUALITYGRADE_ID = srg.QUALITYGRADE_ID
and q.PRIORITY = 1)
/
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_ORDEREXCEPTION_ANG
 (LINETYPE, CUSTOMER_ID, BUSINESSUNIT_ID, DELIVERYDATE, BUSINESSUNITCODE, BUSINESSUNITDESC, CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESC, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESC, PRODUCTGROUPCODE, PRODUCTCODE, SIZECODE, FINMETHODCODE, PRODUCTDESC, AMOUNTORDERED, AMOUNTDELIVERED, DIFF, CUSTOMERLANGUAGECODE, LANGUAGECODE, SIZEDESC, STOCK_AMOUNT, REPORTPARAM_ID)
as SELECT /* not yet needed INDEX(bu XPKBUSINESSUNIT) */
       1 linetype, cu.customer_id, bu.businessunit_id,
rp.date_value2 deliverydate, bu.code businessunitCode, bu.description businessunitDesc, cu.customernumber, cu.name customerName
, de.departmentnumber, de.description departmentDesc, dp.distributionpointnumber, dp.description distributionpointDesc
, prdlk.Productgroupcode, prdlk.code productCode, sz.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
, 0 amountordered, 0 amountdelivered, 0 diff
, (select lan.code from languages lan where cu.language_id = lan.language_id) CUSTOMERLANGUAGECODE
, languages.code languageCode
, (select sizedefinition_link_desc.description from sizedefinition_link_desc where sizedefinition_link_desc.sizedefinition_link_id = sz.sizedefinition_id
  and sizedefinition_link_desc.language_id = languages.language_id) sizeDesc
, coalesce((select sum(N.AMOUNT) from (select mydate, GETABSDAYNUMBER(mydate) dayofweek
          from (select to_date('01-01-2010', 'dd-mm-yyyy') + rownum mydate
                  from invoiceheader--all_objects--
                 where rownum <= 365 * 40) dates) D   -- All dates from 1jan 2010 until 2050
   WHERE N.DAY_ID = D.DAYOFWEEK AND D.MYDATE >= rp.date_value1 AND D.MYDATE <= rp.date_value2), 0) STOCK_AMOUNT
, rp.reportparam_id
FROM NORMSTOCKAMOUNT N, PRODUCTLISTPERDISTRIBPOINT PLPD, distributionpoint dp, department de, customer cu, businessunit bu
, product_link prdlk, sizedefinition sz, finishingmethod fm, languages
, reportparam rp
where N.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 cu.defaultbusinessunit_id = bu.businessunit_id
   and PLPD.product_id = prdlk.product_link_id
   and PLPD.sizedefinition_id = sz.sizedefinition_id
   and PLPD.finishingmethod_id = fm.finishingmethod_id
   and cu.customernumber >= rp.number_value1
   and cu.customernumber <= rp.number_value2
   and de.departmentnumber >= rp.number_value3
   and de.departmentnumber <= rp.number_value4
   and dp.distributionpointnumber >= rp.number_value5
   and dp.distributionpointnumber <= rp.number_value6
   and cu.dateinactive >= rp.date_value1
   and cu.dateactive <= rp.date_value2
   and languages.code = rp.string_value
   and ((rp.string_value7 = 'true' and (bu.businessunit_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
       (rp.string_value7 = 'false'))
/*GROUP BY cu.customer_id, bu.businessunit_id, D.MYDATE, bu.code, bu.description, cu.customernumber, cu.name
, de.departmentnumber, de.description, dp.distributionpointnumber, dp.description
, prdlk.Productgroupcode, prdlk.code, prdlk.product_link_id, sz.code, sz.sizedefinition_id, fm.code
, languages.language_id, cu.language_id, languages.code, rp.reportparam_id*/
UNION ALL
select /* not yet needed INDEX(culk XPKCUSTOMER_LINK) INDEX(dilk XPKDISTRIBUTIONPOINT_LINK) INDEX(delk XPKDEPARTMENT_LINK) INDEX(bu XPKBUSINESSUNIT)  INDEX(fm XPKFINISHINGMETHOD)*/
      2 linetype, 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 amountordered, dh.amountdelivered 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
, 0 STOCK_AMOUNT
, rp.reportparam_id
from
  deliveryhistory dh, businessunit bu, customer culk, department_link delk, distributionpoint_link dilk
, product_link prdlk, sizedefinition_link szlk, finishingmethod fm
, languages, reportparam rp
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 culk.customernumber >= rp.number_value1
    and culk.customernumber <= rp.number_value2
    and delk.departmentnumber >= rp.number_value3
    and delk.departmentnumber <= rp.number_value4
    and dilk.distributionpointnumber >= rp.number_value5
    and dilk.distributionpointnumber <= rp.number_value6
    and culk.dateinactive >= rp.date_value1
    and culk.dateactive <= rp.date_value2
    and languages.code = rp.string_value
    AND dh.deliverydate >= rp.date_value1 AND dh.deliverydate <= rp.date_value2
   and ((rp.string_value7 = 'true' and (bu.businessunit_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
       (rp.string_value7 = 'false'))
/*GROUP BY culk.customer_id, bu.businessunit_id, dh.deliverydate, bu.code, bu.description, culk.customernumber, culk.name
, delk.departmentnumber, delk.description, dilk.distributionpointnumber, dilk.description
, prdlk.Productgroupcode, prdlk.code, prdlk.product_link_id, szlk.code, szlk.sizedefinition_link_id, fm.code
, languages.language_id, culk.languagecode, languages.code, rp.reportparam_id*/

/
create or replace view V_ORDEREXCEPTION_SGS
 (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, YEAR, WEEK, PRICE)
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
, (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
, dh.year, dh.week,  pack_price.Wash_Price(culk.customer_id, prdlk.product_link_id, dh.sizedefinition_link_id, dh.finishingmethod_id, dh.deliverydate) +
pack_price.Rent_Price(culk.customer_id, prdlk.product_link_id, dh.sizedefinition_link_id, dh.finishingmethod_id, dh.deliverydate)
price
from
  deliveryhistory dh, businessunit bu, customer culk, department_link delk, distributionpoint_link dilk
, product_link prdlk, sizedefinition_link szlk, finishingmethod fm
, languages
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

/
create or replace view V_ORDERFORM_SUM_SMG
 (REPORTPARAM_ID, COPY_NUMBER, CPL, CUSTOMERNUMBER, CUSTOMERNAME, CUSTNR, DEPARTMENTNUMBER, DEPACTIVE, DEPARTMENTNAME, DISTRIBUTIONPOINT_ID, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTNUMBERNAME, DISTRIBACTIVE, PRODUCTCODE, PRODUCTDESC, CUSTOMCODE, CUSTOMDESCRIPTION, CUSTOMER_ID, DELIVERYPOINT_ID, INTERNALPROCBU, BU_DESC, PLANTNAME, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTSTREET, PLANTZIP, PLANTCITY, DELPOINTCODE, PRODUCTGROUP, ACTIVITYCODE, LEGALENTITY_ID, LEGALENTITY_LEGALNAME
, LEGALENTITY_STREET, LEGALENTITY_ZIP, LEGALENTITY_CITY, PLANTNAME_PART2)
as select   rp.reportparam_id
,        rp.copy_number
,        0 cpl
,        c.customernumber
,        max(c.name) customername
,        insertspace_after_x_characters(to_char(c.CUSTOMERNUMBER),3) custnr
,        t.departmentnumber
,        max(t.active) depactive
,        max(t.description) departmentname
,        dp.distributionpoint_id
,        dp.distributionpointnumber
,        max(dp.description) distributionpointnumbername
,        max(dp.active) distribactive
,        p.code productcode
,        ( select pd.description from   product_desc pd
                where  pd.product_id = p.product_id
                   and pd.language_id = c.language_id )  productdesc
,        max(l.customcode) customcode
,        max(l.customdescription) customdescription
,        max(t.customer_id) customer_id
,        dp.deliverypoint_id
,        ( select min(bu.code)
           from   customeractivities ca
       ,      activity act
       ,      businessunit bu
           where  ca.customer_id = c.customer_id
              and ca.activity_id = act.activity_id
              and act.code = 'BK'
              and ca.internalprocessingbu_id = bu.businessunit_id ) internalprocbu
,        bu.description bu_desc
,        pl.name plantname
,        pl.phoneno plantphone
,        pl.faxno plantfax, pl.WEBSITE PLANTWEBSITE
,        ad.street plantstreet
,        ad.zipcode plantzip
,        ad.city plantcity
,        delp.code delpointcode
,        pg.code productgroup
,        act.code activitycode, bu.Legalentity_Id, le.legalname LegalEntity_LegalName
, leadd.street LegalEntity_Street, leadd.zipcode LegalEntity_Zip, leadd.city LegalEntity_City
, case when pl.CODE = 'ARNO' then substr(pl.NAME, 25)
       when PL.CODE = 'CHEM' then substr(PL.NAME, 35)
       when PL.CODE = 'GRAZ' then substr(PL.NAME, 25)
       when PL.CODE = 'INZ' then substr(PL.NAME, 25)
       when PL.CODE = 'KRAM' then bu.Description--substr(PL.NAME, 25)
       when PL.CODE = 'LEOG' then substr(PL.NAME, 25)
       when PL.CODE = 'MATT' then substr(PL.NAME, 25)
       when PL.CODE = 'ORAD' then substr(PL.NAME, 27)
       when PL.CODE = 'PWSK' then substr(PL.NAME, 25)
       when PL.CODE = 'ROGA' then substr(PL.NAME, 36)
       when PL.CODE = 'SA14' then bu.Description--substr(PL.NAME, 25)
       when PL.CODE = 'SA22' then substr(PL.NAME, 25)
       when PL.CODE = 'SAWR' then substr(PL.NAME, 25)
       when PL.CODE = 'SCHI' then substr(PL.NAME, 25)
       when PL.CODE = 'SMA' then substr(PL.NAME, 25)
       when PL.CODE = 'SMB' then substr(PL.NAME, 20)
       when PL.CODE = 'SMHR' then substr(PL.NAME, 33)
       when PL.CODE = 'SMP' then substr(PL.NAME, 35)
       when PL.CODE = 'SMPL' then substr(PL.NAME, 31)
       when PL.CODE = 'SMRO' then substr(PL.NAME, 27)
       when PL.CODE = 'SMRS' then substr(PL.NAME, 31)
       when PL.CODE = 'SMS' then substr(PL.NAME, 25)
       when PL.CODE = 'SMSK' then substr(PL.NAME, 29)
       when PL.CODE = 'SMSL' then substr(PL.NAME, 36)
       when PL.CODE = 'SMTY' then substr(PL.NAME, 31)
       when PL.CODE = 'SMZL' then substr(PL.NAME, 25)
       when PL.CODE = 'SZOM' then substr(PL.NAME, 20)
else PL.NAME end PLANTNAME_PART2
from     productlistperdistribpoint plpd
,        distributionpoint dp
,        deliverypoint delp
,        department t
,        customer c
,        product p
,        standarddeliveryline stl
,        productlistpercustomer l
,        reportparam rp
,        businessunit bu
         left outer join legalentity le
              inner join address leadd on leadd.address_id = le.address_id
         on le.legalentity_id = bu.legalentity_id
,        productgroup pg
,        activity act
,        plant pl
,        address ad
where    dp.distributionpoint_id = plpd.distributionpoint_id
         and delp.deliverypoint_id = dp.deliverypoint_id
         and t.department_id = dp.department_id
         and c.customer_id = t.customer_id
         and delp.customer_id=c.customer_id
         and p.product_id = plpd.product_id
         and stl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
         and l.product_id=p.product_id
         and l.productlistpercustomer_id = stl.productlistpercustomer_id and
                  l.soilcountmethod <> 0 and
                  l.straightevenexchange = 'N'
          and p.productgroup_id=pg.productgroup_id
         and pg.activity_id=act.activity_id
and rp.number_value = c.customer_id
     and ( rp.number_value4 = 0 or rp.number_value4 = dp.deliverypoint_id )
     and trunc(rp.number_value5) = bu.businessunit_id
     and bu.plant_id = pl.plant_id
     and ad.address_id = pl.address_id
     and rp.date_value1 between l.dateactive and l.dateinactive
     and rp.date_value1 between stl.dateactive and stl.dateinactive
     and  (coalesce((select sum(rqa.quantity)
              from   rentalqtyadjustment rqa
              where  rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
              and rqa.adjustmentdate < rp.date_value1),0)>0)
group by rp.reportparam_id
,        rp.copy_number
,        c.customer_id
,        c.customernumber
,        t.departmentnumber
,        dp.distributionpoint_id
,        dp.distributionpointnumber
,        p.code, p.product_id
,        pg.code
,        act.code
,        dp.deliverypoint_id
,        bu.description
,        pl.name
,        pl.phoneno
,        pl.faxno, pl.WEBSITE
,        ad.street
,        ad.zipcode
,        ad.city
,        delp.code, c.language_id, bu.legalentity_id, le.legalname
, leadd.street, leadd.zipcode, leadd.city, PL.CODE
union all
select   distinct rp.reportparam_id
,        rp.copy_number
,        1 cpl
,        a.customernumber
,        a.name customername
,        insertspace_after_x_characters(to_char(a.customernumber),3) custnr
,        b.departmentnumber
,        b.active depactive
,        b.description departmentname
,        c.distributionpoint_id
,        c.distributionpointnumber
,        c.description distributionpointnumbername
,        c.active distribactive
,        g.code productcode
,        ( select z.description
           from   product_desc z
           where  z.product_id = g.product_id
              and a.language_id = z.language_id ) productdesc
,        ( select max(plpc.customcode)
           from   productlistpercustomer plpc
           where  plpc.productlistpercustomer_id=e.productlistpercustomer_id ) customcode
,        ( select max(plpc.customdescription)
           from   productlistpercustomer plpc
           where  plpc.productlistpercustomer_id=e.productlistpercustomer_id ) customdescription
,        a.customer_id
,        dp.deliverypoint_id
,        ( select min(bu.code)
           from   customeractivities ca, activity ac,businessunit bu
           where  ca.customer_id=a.customer_id
              and ca.activity_id=ac.activity_id
              and ac.code='BK'
              and ca.internalprocessingbu_id=bu.businessunit_id ) internalprocbu
,        bu.description bu_desc
,        pl.name plantname
,        pl.phoneno plantphone
,        pl.faxno plantfax, pl.WEBSITE PLANTWEBSITE
,        ad.street plantstreet
,        ad.zipcode plantzip
,        ad.city plantcity
,        dp.code delpointcode
,        pg.code   productgroup
,        act.code  activitycode, bu.Legalentity_Id, le.legalname LegalEntity_LegalName
, leadd.street LegalEntity_Street, leadd.zipcode LegalEntity_Zip, leadd.city LegalEntity_City
, case when pl.CODE = 'ARNO' then substr(pl.NAME, 25)
       when PL.CODE = 'CHEM' then substr(PL.NAME, 35)
       when PL.CODE = 'GRAZ' then substr(PL.NAME, 25)
       when PL.CODE = 'INZ' then substr(PL.NAME, 25)
       when PL.CODE = 'KRAM' then bu.Description--substr(PL.NAME, 25)
       when PL.CODE = 'LEOG' then substr(PL.NAME, 25)
       when PL.CODE = 'MATT' then substr(PL.NAME, 25)
       when PL.CODE = 'ORAD' then substr(PL.NAME, 27)
       when PL.CODE = 'PWSK' then substr(PL.NAME, 25)
       when PL.CODE = 'ROGA' then substr(PL.NAME, 36)
       when PL.CODE = 'SA14' then bu.Description--substr(PL.NAME, 25)
       when PL.CODE = 'SA22' then substr(PL.NAME, 25)
       when PL.CODE = 'SAWR' then substr(PL.NAME, 25)
       when PL.CODE = 'SCHI' then substr(PL.NAME, 25)
       when PL.CODE = 'SMA' then substr(PL.NAME, 25)
       when PL.CODE = 'SMB' then substr(PL.NAME, 20)
       when PL.CODE = 'SMHR' then substr(PL.NAME, 33)
       when PL.CODE = 'SMP' then substr(PL.NAME, 35)
       when PL.CODE = 'SMPL' then substr(PL.NAME, 31)
       when PL.CODE = 'SMRO' then substr(PL.NAME, 27)
       when PL.CODE = 'SMRS' then substr(PL.NAME, 31)
       when PL.CODE = 'SMS' then substr(PL.NAME, 25)
       when PL.CODE = 'SMSK' then substr(PL.NAME, 29)
       when PL.CODE = 'SMSL' then substr(PL.NAME, 36)
       when PL.CODE = 'SMTY' then substr(PL.NAME, 31)
       when PL.CODE = 'SMZL' then substr(PL.NAME, 25)
       when PL.CODE = 'SZOM' then substr(PL.NAME, 20)
else PL.NAME end PLANTNAME_PART2
from     customer a
,        department b
,        distributionpoint c
,        deliverypoint dp
,        productlistpercustomer e
,        address f
,        product g
,        productgroup pg
,        activity act
,        reportparam rp
,        businessunit bu
         left outer join legalentity le
              inner join address leadd on leadd.address_id = le.address_id
         on le.legalentity_id = bu.legalentity_id
,        plant pl
,        address ad
,        weareremployment we
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 e.customer_id = a.customer_id
     and e.product_id=g.product_id
     and g.productgroup_id=pg.productgroup_id
     and pg.activity_id=act.activity_id
     and g.typeofmerchandise = 2
     and we.distributionpoint_id = c.distributionpoint_id
     and exists(select 1 from   wearerinventory wi
            where wi.weareremployment_id=we.weareremployment_id
               and wi.product_id = g.product_id
               and wi.dateactive <= rp.date_value1
               and wi.dateinactive >= rp.date_value1
               and wi.circinventory+wi.freeofchargeqty > 0)
     and e.dateactive <= rp.date_value1
     and e.dateinactive > rp.date_value1
     and not exists ( select 1  from   productlistperdistribpoint plpd,  standarddeliveryline sdl
             where  plpd.distributionpoint_id = c.distributionpoint_id
                and plpd.productlistperdistribpoint_id=sdl.productlistperdistribpoint_id
                and sdl.productlistpercustomer_id=e.productlistpercustomer_id
                and plpd.product_id = g.product_id
                and e.soilcountmethod <> 0
                and e.straightevenexchange = 'N'
                and rp.date_value1 between sdl.dateactive and sdl.dateinactive )
     and ( b.active='Y' or c.active='Y' )
     and rp.number_value = a.customer_id
     and ( rp.number_value4 = 0 or rp.number_value4 = dp.deliverypoint_id )
     and trunc(rp.number_value5) = bu.businessunit_id
     and bu.plant_id = pl.plant_id
     and ad.address_id = pl.address_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, r.routenumber, ph.stopnumber, c.customernumber,
(substr(to_char(ph.productiondate,'yyyymmddhh24miss'),1,8)||substr(to_char(rc.packingdeadline,'yyyymmddhh24mi'),-6,4) ) packingdatetime,
p.code productcode, s.code sizecode, trunc(pl.tobedeliveredamount) quantityordered
 from packingnote ph, packingnoteline pl, product p, customer_link c, route r, distributionpoint d,
 department e, routecontrol rc, sizedefinition s, status, plantdepartment pd
where ph.packingnote_id = pl.packingnote_id
and pl.product_id = p.product_id
and ph.route_id = r.route_id
and ph.distributionpoint_id = d.distributionpoint_id
and d.department_id = e.department_id
and e.customer_id = c.customer_id
and ph.routecontrol_id = rc.routecontrol_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_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 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, --/ (select count(*) from view pl where pl.packingnoteline_id = pnl.packingnoteline_id)
       pnl.deliveredamount pnlcqty,
       ui.businessunit_id,
       languages.code language_code,
       pnl.packingnoteline_id,
       ui.prevstay_id
  from uniqueitem ui
  left outer 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 (pnl.product_id = ui.product_id and pnl.sizedefinition_id = ui.sizedefinition_id and pnl.finishingmethod_id = ui.finishingmethod_id and ui.distributionpoint_id = pn.distributionpoint_id), product pr, stay st, languages
 where ui.stay_id = st.stay_id
   and 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)))
      --staytype = 1 and staynr <> 35
   and ui.product_id = pr.product_id
   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 outer 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 (pnlc.product_id = ui1.product_id and pnlc.sizedefinition_id = ui1.sizedefinition_id and pnlc.finishingmethod_id = ui1.finishingmethod_id and ui1.stay_id = (select s.stay_id
                                                                                                                                                                                                                                                                                                                                                                                                                                       from stay s
                                                                                                                                                                                                                                                                                                                                                                                                                                      where s.staytype = 1
                                                                                                                                                                                                                                                                                                                                                                                                                                        and s.staynr = 20)), uniqueitem ui2, stay s1, stay s2, product pr, uniqueorpackuniquecontents uorpuc, uniqueorpackcontents uorpc, uniqueorpack uorp, languages
 where ui1.stay_id = s1.stay_id
   and ((s1.staytype = 1 and s1.staynr = 35) or
       (s1.staytype = 1 and s1.staynr = 20))
   and ui1.uniqueitem_id = uorpuc.uniqueitem_id
   and uorpuc.uniqueorpackcontents_id = uorpc.uniqueorpackcontents_id
   and uorpc.uniqueitem_id = uorp.uniqueitem_id
   and uorp.uniqueitem_id = ui2.uniqueitem_id
   and ui2.stay_id = s2.stay_id
   and s2.staytype = 3
   and s2.staynr in (20, 30, 35, 40, 45, 46)
   and ui1.product_id = pr.product_id
   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, getdateonly(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_OUTOFCIRCULATIONHISTORYCC
 (OUTOFCIRCYEAR, OUTOFCIRCWEEK, DEPARTMENTNUMBER, DEPARTMENTDESC, WEARERNUMBER, WEARERNAME, 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,
 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,
 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, getdateonly(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_OUTOFCIRCULATIONHISTORY_CBD
 (OUTOFCIRCYEAR, OUTOFCIRCWEEK, PRIMARYID, DEPARTMENTNUMBER, DEPARTMENTDESC, WEARERNUMBER, WEARERNAME, PRODUCTCODE, PRODUCTDESC, REASONCODE, REASONDESC, RAGREASONCODE, RAGREASONDESC, INCIRCDATE, OUTOFCIRCDATE, TOBECHARGEDPERCENTAGE, RESIDUALVALUE, INVOICEHEADER_ID, CHARGETYPE, STATUS, INVOICECATEGORY, LANGUAGECODE, LANGUAGE_ID, SECONDARYID)
as select a.outofcircyear
,      a.outofcircweek
,      a.primaryid
,      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
,      b.code reasoncode
,      ( select description
         from   reasoncode_desc x
         where  x.reasoncode_id = a.reasoncode_id
            and x.language_id = languages.language_id) reasondesc
,      c.code ragreasoncode
,      ( select 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
,      a.invoiceheader_id
,      a.chargetype
,      a.status
,      b.invoicecategory
,      languages.code languagecode
,      languages.language_id
,      coalesce( (select sui.secondaryid
                  from   secondaryuniqueitem sui
                  where  sui.uniqueitem_id = a.uniqueitem_link_id),
                 (select rag.secondaryid
                  from   raggeditem rag
                  where  rag.raggeditem_id = a.uniqueitem_link_id )) secondaryid
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
, GETDATEONLY(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_OUTSTANDINGCOLLECTIONS_LLG
 (DELIVERROUTENR, STOPNUMBER, CUSTOMERNUMBER, CUSTOMERNAME, BU_CODE, PLANNEDDELIVERYDATE, PICKUPDATE, PICKUPROUTENR, NOTSORTED, SORTED)
as select r.routenumber deliverroutenr,
s.stopnumber,
c.customernumber,  c.name customername,
(select bu.code from businessunit bu where bu.businessunit_id = c.defaultbusinessunit_id) bu_code,
b.planneddeliverydate,
max(case when st.staytype = 6 and st.staynr = 70 then b.pickupdate else null end) pickupdate,
max(case when st.staytype = 6 and st.staynr = 70 then (select rt.routenumber from route rt where b.pickuproute_id = rt.route_id) else null end) pickuproutenr,
sum(case when st.staytype = 6 and st.staynr = 60 then 1 else 0 end) as NotSorted,
sum(case when st.staytype = 6 and st.staynr = 70 then 1 else 0 end) as Sorted
from routecontrol rc
inner join stop s on s.routecontrol_id = rc.routecontrol_id
inner join customer c on c.Customer_id = s.customer_link_id
inner join department d on d.customer_id = c.Customer_id
inner join distributionpoint dp on dp.department_id = d.department_id
inner join route r on r.route_id = rc.route_id
inner join bagtag b on b.distributionpoint_id = dp.distributionpoint_id
inner join stay st on b.stay_id = st.stay_id
where rc.drivingdate = b.planneddeliverydate
group by c.customernumber,  c.name, c.defaultbusinessunit_id, r.routenumber, s.stopnumber, b.planneddeliverydate
having sum(case when st.staytype = 6 and st.staynr = 60 then 1 else 0 end) > 0

/
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, WORKORDERNUMBER, REQUESTDATE, NEEDEDDATE, QUANTITYORDERED, QUANTITYCANCELLED, QUANTITYFILLED, OUTSTANDING, STATUS_DESC, STATUS_CODE, PROD_CODE, SIZE_CODE, PROD_DESC, SIZE_DESC, REASON_CODE, REFERENCENUMBER, REASON_DESC, LAN_CODE, REMARK, WOREFERENCENR, WOREFNR_DESC, PROCBUID
, NEEDFORBUID, NEEDFORBUCODE, INTPROCESSBUID, INTPROCESSBUCODE)
as select 1 linetype,
wo.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 distributionpointnumber, '' DistribPoint_desc,
w.wearernumber, w.fullname, wo.workordernumber, wo.requestdate, wo.neededdate,
wol.quantityordered, wol.quantitycancelled, wol.quantityfilled,
case when (wol.quantityordered < wol.quantitycancelled + wol.quantityfilled)
then 0
else (wol.quantityordered - wol.quantitycancelled - wol.quantityfilled)
end 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 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,
coalesce((select st.managedbybu_id from  stockroom st where wo.processingstockroom_id=st.stockroom_id),wo.businessunit_id) procbuid,
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 workorder wo
     left outer join woreferencenumber worefnr on wo.woreferencenumber_id = worefnr.woreferencenumber_id,
weareremployment we, wearer w, customer cu, department de, distributionpoint dp,
workorderline wol
left outer join product pr on wol.product_link_id = pr.product_id
left outer join sizedefinition sd on wol.sizedefinition_link_id = sd.sizedefinition_id,
status st, reasoncode rc, languages lan
where wol.workorder_id = wo.workorder_id
and wo.status_id = st.status_id and st.statustype = 'WO'
and wo.weareremployment_link_id = we.weareremployment_id --is an union instead of left join because of 2 ways to determine customer
and we.wearer_id = w.wearer_id and w.customer_id = cu.customer_id
and cu.customer_id = de.customer_id and dp.department_id = de.department_id and dp.distributionpoint_id = we.distributionpoint_id
and rc.reasoncode_id = wo.reasoncode_id
union all
select 2 linetype,
wo.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, wo.workordernumber, wo.requestdate, wo.neededdate,
wol.quantityordered, wol.quantitycancelled, wol.quantityfilled,
case when (wol.quantityordered < wol.quantitycancelled + wol.quantityfilled)
then 0
else (wol.quantityordered - wol.quantitycancelled - wol.quantityfilled)
end 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 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,
coalesce((select st.managedbybu_id from  stockroom st where wo.processingstockroom_id=st.stockroom_id),wo.businessunit_id) procbuid,
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 workorder wo
left outer 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
left outer join woreferencenumber worefnr on wo.woreferencenumber_id = worefnr.woreferencenumber_id
, workorderline wol
left outer join product pr on wol.product_link_id = pr.product_id
left outer join sizedefinition sd on wol.sizedefinition_link_id = sd.sizedefinition_id,
status st, reasoncode rc, languages lan
where wol.workorder_id = wo.workorder_id
and wo.status_id = st.status_id and st.statustype = 'WO'
and rc.reasoncode_id = wo.reasoncode_id
and wo.weareremployment_link_id is null
and wo.distributionpoint_link_id is not null
union
select 3 linetype,
wo.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, wo.workordernumber, wo.requestdate, wo.neededdate,
wol.quantityordered, wol.quantitycancelled, wol.quantityfilled,
case when (wol.quantityordered < wol.quantitycancelled + wol.quantityfilled)
then 0
else (wol.quantityordered - wol.quantitycancelled - wol.quantityfilled)
end 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 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) procbuid,
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 workorder wo
          join customer cu on wo.customer_link_id = cu.customer_id
left outer join woreferencenumber worefnr on wo.woreferencenumber_id = worefnr.woreferencenumber_id
, workorderline wol
left outer join product pr on wol.product_link_id = pr.product_id
left outer join sizedefinition sd on wol.sizedefinition_link_id = sd.sizedefinition_id,
status st, reasoncode rc, languages lan
where wol.workorder_id = wo.workorder_id
and wo.status_id = st.status_id and st.statustype = 'WO'
and rc.reasoncode_id = wo.reasoncode_id
and wo.weareremployment_link_id is null
and wo.distributionpoint_link_id is null

/
create or replace view V_OUTSTANDINGWORKORDERS_NIW
 (LINETYPE, BUSINESSUNIT_ID, DELIVERFROM, WEAREREMPLOYMENT_LINK_ID, ORIGIN, CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEP_DESC, DISTRIBUTIONPOINTNUMBER, DISTRIBPOINT_DESC, WEARERNUMBER, FULLNAME, WORKORDERNUMBER, REQUESTDATE, NEEDEDDATE, QUANTITYORDERED, QUANTITYCANCELLED, QUANTITYFILLED, OUTSTANDING, STATUS_DESC, STATUS_CODE, PROD_CODE, SIZE_CODE, PROD_DESC, SIZE_DESC, REASON_CODE, REFERENCENUMBER, REASON_DESC, LAN_CODE, PO_NUMBER, PO_DATE, PO_EXPDATE, PO_STATUS, COUNTWORKORDERLINEEMBLEM
)
as select 1 linetype,
wo.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, wo.workordernumber, wo.requestdate, wo.neededdate,
wol.quantityordered, wol.quantitycancelled, wol.quantityfilled,
case when (wol.quantityordered < wol.quantitycancelled + wol.quantityfilled)
then 0
else (wol.quantityordered - wol.quantitycancelled - wol.quantityfilled)
end 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 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
, (select max(ph.purchaseordernumber) from purchaseorderheader ph, purchaseorderline pl
  where ph.purchaseorderheader_id = pl.purchaseorderheader_id and (wol.purchaseorderline_id = pl.purchaseorderline_id
  or pl.purchaseorderline_id in (select wolpol.purchaseorderline_id from workorderlinepurchordline wolpol where wolpol.workorderline_id=wol.workorderline_id))) PO_Number
, (select max(ph.orderdate) from purchaseorderheader ph, purchaseorderline pl
  where ph.purchaseorderheader_id = pl.purchaseorderheader_id and (wol.purchaseorderline_id = pl.purchaseorderline_id
  or pl.purchaseorderline_id in (select wolpol.purchaseorderline_id from workorderlinepurchordline wolpol where wolpol.workorderline_id=wol.workorderline_id))) PO_Date
, (select max(ph.exportdate) from purchaseorderheader ph, purchaseorderline pl
  where ph.purchaseorderheader_id = pl.purchaseorderheader_id and (wol.purchaseorderline_id = pl.purchaseorderline_id
  or pl.purchaseorderline_id in (select wolpol.purchaseorderline_id from workorderlinepurchordline wolpol where wolpol.workorderline_id=wol.workorderline_id))) PO_ExpDate
, (select max(st.description) from purchaseorderheader ph, purchaseorderline pl, status_desc st
  where ph.purchaseorderheader_id = pl.purchaseorderheader_id and
  (wol.purchaseorderline_id = pl.purchaseorderline_id or pl.purchaseorderline_id in (select wolpol.purchaseorderline_id from workorderlinepurchordline wolpol where wolpol.workorderline_id=wol.workorderline_id))
  and ph.status_id = st.status_id and st.language_id = lan.language_id) PO_Status
, COALESCE(
    (SELECT COUNT(wokem.workorderlineemblem_id)
    FROM workorderline wokli, workorderlineemblem wokem
    WHERE wo.workorder_id     = wokli.workorder_id
    AND wokli.workorderline_id = wokem.workorderline_id
    ) , 0) countWorkorderLineEmblem
from workorder wo,
weareremployment we, wearer w, customer cu, department de, distributionpoint dp,
workorderline wol
left outer join product pr on wol.product_link_id = pr.product_id
left outer join sizedefinition sd on wol.sizedefinition_link_id = sd.sizedefinition_id,
status st, reasoncode rc, languages lan
where wol.workorder_id = wo.workorder_id
and wo.status_id = st.status_id and st.statustype = 'WO'
and wo.weareremployment_link_id = we.weareremployment_id --is an union instead of left join because of 2 ways to determine customer
and we.wearer_id = w.wearer_id and w.customer_id = cu.customer_id
and cu.customer_id = de.customer_id and dp.department_id = de.department_id and dp.distributionpoint_id = we.distributionpoint_id
and rc.reasoncode_id = wo.reasoncode_id
union all
select 2 linetype,
wo.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, wo.workordernumber, wo.requestdate, wo.neededdate,
wol.quantityordered, wol.quantitycancelled, wol.quantityfilled,
case when (wol.quantityordered < wol.quantitycancelled + wol.quantityfilled)
then 0
else (wol.quantityordered - wol.quantitycancelled - wol.quantityfilled)
end 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 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
, (select max(ph.purchaseordernumber) from purchaseorderheader ph, purchaseorderline pl
  where ph.purchaseorderheader_id = pl.purchaseorderheader_id and (wol.purchaseorderline_id = pl.purchaseorderline_id
  or pl.purchaseorderline_id in (select wolpol.purchaseorderline_id from workorderlinepurchordline wolpol where wolpol.workorderline_id=wol.workorderline_id))) PO_Number
, (select max(ph.orderdate) from purchaseorderheader ph, purchaseorderline pl
  where ph.purchaseorderheader_id = pl.purchaseorderheader_id and (wol.purchaseorderline_id = pl.purchaseorderline_id
  or pl.purchaseorderline_id in (select wolpol.purchaseorderline_id from workorderlinepurchordline wolpol where wolpol.workorderline_id=wol.workorderline_id))) PO_Date
, (select max(ph.exportdate) from purchaseorderheader ph, purchaseorderline pl
  where ph.purchaseorderheader_id = pl.purchaseorderheader_id and (wol.purchaseorderline_id = pl.purchaseorderline_id
  or pl.purchaseorderline_id in (select wolpol.purchaseorderline_id from workorderlinepurchordline wolpol where wolpol.workorderline_id=wol.workorderline_id))) PO_ExpDate
, (select max(st.description) from purchaseorderheader ph, purchaseorderline pl, status_desc st
  where ph.purchaseorderheader_id = pl.purchaseorderheader_id and
  (wol.purchaseorderline_id = pl.purchaseorderline_id or pl.purchaseorderline_id in (select wolpol.purchaseorderline_id from workorderlinepurchordline wolpol where wolpol.workorderline_id=wol.workorderline_id))
  and ph.status_id = st.status_id and st.language_id = lan.language_id) PO_Status
, COALESCE(
    (SELECT COUNT(wokem.workorderlineemblem_id)
    FROM workorderline wokli, workorderlineemblem wokem
    WHERE wo.workorder_id     = wokli.workorder_id
    AND wokli.workorderline_id = wokem.workorderline_id
    ) , 0) countWorkorderLineEmblem
from workorder wo
left outer 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
, workorderline wol
left outer join product pr on wol.product_link_id = pr.product_id
left outer join sizedefinition sd on wol.sizedefinition_link_id = sd.sizedefinition_id,
status st, reasoncode rc, languages lan
where wol.workorder_id = wo.workorder_id
and wo.status_id = st.status_id and st.statustype = 'WO'
and rc.reasoncode_id = wo.reasoncode_id
and wo.weareremployment_link_id is null

/
create or replace view V_OVERSFROMSTOCKTAKE_LLG
 (BUCODE, COUNTDATE, CUSTOMERNUMBER, CUSTOMERNAME, PRODUCTCODE, PRODUCTDESC, SIZECODE, PGCODE, LANGUAGECODE, DIFFERENCECPL)
as select
(select bu.code from businessunit bu,customer c, distributionpoint dp, department d
        where cic.distributionpoint_id = dp.distributionpoint_id
        and dp.department_id = d.department_id
        and d.customer_id = c.customer_id and bu.businessunit_id = c.defaultbusinessunit_id) bucode,
cic.countdate,
(select c.customernumber from customer c, distributionpoint dp, department d
        where cic.distributionpoint_id = dp.distributionpoint_id
        and dp.department_id = d.department_id
        and d.customer_id = c.customer_id) customernumber,
(select c.name from customer c, distributionpoint dp, department d
        where cic.distributionpoint_id = dp.distributionpoint_id
        and dp.department_id = d.department_id
        and d.customer_id = c.customer_id) customername,
(select p.code from product p where p.product_id = cic.product_id) productcode,
(select pd.description from product_desc pd where pd.product_id = cic.product_id and pd.language_id = l.language_id) productdesc,
(select sd.code from sizedefinition sd where sd.sizedefinition_id = cic.sizedefinition_id) sizecode,
(select pg.code from productgroup pg, product p where p.product_id = cic.product_id and pg.productgroup_id = p.productgroup_id) pgcode,
l.code languagecode,cic.adjustmentcpl differencecpl
from customerinventorycount cic,
languages l
where cic.adjustmentcpl > 0

/
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_PACKCONTENTS
 (PACKPRODUCTCODE, PACKPRODUCTDESCRIPTION, PRODUCTCODE, PRODUCTDESCRIPTION, SIZECODE, SIZEDESCRIPTION, AMOUNT, PACKSEQUENCE, REMARK, LOCATION, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE)
as SELECT PACKPRODUCT.CODE,
 (SELECT description FROM PRODUCT_DESC A WHERE A.PRODUCT_ID = PACKCONTENTS.PACK_ID
  AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) packproductdescription,
 PRODUCT.CODE,
 (SELECT description FROM PRODUCT_DESC B WHERE B.PRODUCT_ID = PACKCONTENTS.PRODUCT_ID
  AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
 SIZEDEFINITION.CODE,
 (SELECT description FROM SIZEDEFINITION_DESC C WHERE C.SIZEDEFINITION_ID = PACKCONTENTS.SIZEDEFINITION_ID
  AND C.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) sizedescription,
 PACKCONTENTS.AMOUNT, PACKCONTENTS.PACKSEQUENCE, PACKCONTENTS.REMARK, PACKCONTENTS.LOCATION,
 PACKCONTENTS.SYSTEMUSER_ID, PACKCONTENTS.TIMESTAMP, LANGUAGES.CODE
FROM PACKCONTENTS, PRODUCT PACKPRODUCT, PRODUCT, SIZEDEFINITION, LANGUAGES
WHERE PACKCONTENTS.PACK_ID = PACKPRODUCT.PRODUCT_ID
 and PACKCONTENTS.PRODUCT_ID = PRODUCT.PRODUCT_ID
 AND PACKCONTENTS.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID

/
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
        , (select r.routenumber from route r where rc.route_id = r.route_id) routenumber
        , (select dd.code from route r, day_desc dd, plant pl where rc.route_id = r.route_id and rc.plant_id = pl.plant_id and r.drivingday_id = dd.day_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
        , (select p.code from product p where pnl.product_id = p.product_id) productcode
        , (select pd.description from product_desc pd, plant pl where pnl.product_id = pd.product_id and rc.plant_id = pl.plant_id and pl.language_id = pd.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, customer cu where cu.customer_id = stop.customer_link_id and lan.language_id = cu.language_id) language_code
from routecontrol rc, stop
     left outer join customer cu on stop.customer_link_id = cu.customer_id
     , packingnote pn, packingnoteline pnl, distributionpoint dp, deliverypoint delp
     , address ad, (select rownum nr
                    from ( select 1 just_a_column
                    from dual
                    connect by level <= 99
                    )) c
where rc.routecontrol_id = stop.routecontrol_id and pn.stop_id = stop.stop_id and
pnl.packingnote_id = pn.packingnote_id and pnl.putuptype = 3 --packer / bundle tag
and pn.distributionpoint_id = dp.distributionpoint_id and dp.deliverypoint_id = delp.deliverypoint_id and delp.deliveryaddress_id = ad.address_id
      and c.nr <= f_packernoofbundles(pnl.tobedeliveredamount,pnl.bundleqty)

/
create or replace view V_PACKER_LINEN_AMM
 (ROUTECONTROL_ID, PLANT_ID, PLANT_CODE, CUSTOMERNUMBER, NAME, STREET, CITY, ZIPCODE, ROUTENUMBER, DAYCODE, STOPNUMBER, DRIVINGDATE, PLANTDEPARTMENTCODE, PRODUCTCODE, PRODUCTDESC, SIZECODE, ONE_WAY_PRODUCT, DELIVERYSCHEMECODE, BUNDLEQTY, TOBEDELIVEREDAMOUNT, TOTALSOILCOUNT, CURRENTBUNDLE, NOOFBUNDLES, PACKINGNOTE_ID, LANGUAGE_CODE, SUPPPRODCODE, FLEXFIELDDESC)
as select rc.routecontrol_id, rc.plant_id, p.code as plant_code, cu.customernumber, cu.name, ad.street, ad.city, ad.zipcode
        , (select r.routenumber from route r where rc.route_id = r.route_id) routenumber
        , (select dd.code from route r, day_desc dd, plant pl where rc.route_id = r.route_id and rc.plant_id = pl.plant_id and r.drivingday_id = dd.day_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
        , (select pr.code from product pr where pnl.product_id = pr.product_id) productcode
        , (select pd.description from product_desc pd, plant pl where pnl.product_id = pd.product_id and rc.plant_id = pl.plant_id and pl.language_id = pd.language_id) productdesc
        , (select sd.code from sizedefinition sd where sd.sizedefinition_id = pnl.sizedefinition_id) sizecode
        , case when (select prd.productgroup_id from product prd where pnl.product_id = prd.product_id) in (18,19,45,65,66) then 'Y'
				       else 'N'
					end as one_way_product
				, (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, customer cu WHERE cu.customer_id = stop.Customer_Link_Id AND lan.language_id = cu.language_id) LANGUAGE_CODE
, (case when 'CA' = (select co.code from country co where co.country_id = p.country_id)
  then (select max(dff.stringvalue) from dialogflexfields dff
         inner join characteristic ch on ch.characteristic_id = dff.characteristic_id
         inner join characteristicstempline cfl
               inner join characteristicstemplate cft on cft.characteristicstemplate_id = cfl.characteristicstemplate_id
         on cfl.characteristic_id = dff.characteristic_id
         where ch.dialog_id = 41 and ch.code = 'CASUP' and cft.code = 'SUPP' and dff.entity_id = pnl.Product_Id) --CA code
  else (select max(dff.stringvalue) from dialogflexfields dff
         inner join characteristic ch on ch.characteristic_id = dff.characteristic_id
         inner join characteristicstempline cfl
               inner join characteristicstemplate cft on cft.characteristicstemplate_id = cfl.characteristicstemplate_id
         on cfl.characteristic_id = dff.characteristic_id
         where ch.dialog_id = 41 and ch.code = 'USSUP' and cft.code = 'SUPP' and dff.entity_id = pnl.product_id) --US is the default code
    end) SuppProdCode
, (case when 'CA' = (select co.code from country co where co.country_id = p.country_id)
  then (select chd.description
        from characteristic ch, characteristic_desc chd
        where ch.dialog_id = 41 and ch.code = 'CASUP' and ch.characteristic_id = chd.characteristic_id
        and chd.language_id = coalesce(cu.language_id, p.language_id)) --CA code
  else (select chd.description
        from characteristic ch, characteristic_desc chd
        where ch.dialog_id = 41 and ch.code = 'USSUP' and ch.characteristic_id = chd.characteristic_id
        and chd.language_id = coalesce(cu.language_id, p.language_id)) --US is the default code
    end) FlexFieldDesc
from routecontrol rc, plant p, stop
     left outer join customer cu on stop.customer_link_id = cu.customer_id
     , packingnote pn, packingnoteline pnl, distributionpoint dp, deliverypoint delp
     , address ad, (select rownum nr
                    from ( select 1 just_a_column
                    from dual
                    connect by level <= 1000
                    )) c
where rc.routecontrol_id = stop.routecontrol_id
      and rc.plant_id = p.plant_id
      and pn.stop_id = stop.stop_id
			and pnl.packingnote_id = pn.packingnote_id
			and pnl.putuptype = 3 --packer / bundle tag
      and pn.distributionpoint_id = dp.distributionpoint_id
			and dp.deliverypoint_id = delp.deliverypoint_id
			and delp.deliveryaddress_id = ad.address_id
      and c.nr <= f_packernoofbundles(pnl.tobedeliveredamount,pnl.bundleqty)

/
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, customer cu where cu.customer_id = st.customer_link_id and lan.language_id = cu.language_id) language_code
          from routecontrol rc, stop st, packingnote pn, packingnoteline pnl, reportparam rp
         where rc.routecontrol_id = st.routecontrol_id
           and pn.stop_id = st.stop_id and pn.packingnote_id = rp.number_value
           and pnl.packingnote_id = pn.packingnote_id
           and pnl.putuptype = 5 --packer loose linen
         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) 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_PACKER_LOOSELINEN_AMM
 (ROUTECONTROL_ID, PLANT_ID, PLANT_CODE, DRIVINGDATE, ROUTENUMBER, DAYCODE, PRODUCTCODE, PRODUCTDESC, ONE_WAY_PRODUCT, SIZECODE, BUNDLEQTY, REPORTPARAM_ID, TOBEDELIVEREDAMOUNT, PLANTDEPARTMENTCODE, CURRENTBUNDLE, NOOFBUNDLES, LANGUAGE_CODE, SUPPPRODCODE, FLEXFIELDDESC)
as select x.routecontrol_id,
       x.plant_id,
			 x.plant_code,
       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,
			 case when (select p.productgroup_id from product p where x.product_id = p.product_id) in (18,19,45,65,66) then 'Y'
				       else 'N'
					end as one_way_product,
       (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
       , x.SuppProdCode, x.FlexFieldDesc
from (select rc.plant_id,
	             p.code as plant_code,
               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,
               lan.code language_code --(SELECT LAN.CODE FROM LANGUAGES LAN, customer cu WHERE cu.customer_id = st.Customer_Link_Id AND lan.language_id = cu.language_id) LANGUAGE_CODE
, (case when 'CA' = (select co.code from country co where co.country_id = p.country_id)
  then (select max(dff.stringvalue) from dialogflexfields dff
         inner join characteristic ch on ch.characteristic_id = dff.characteristic_id
         inner join characteristicstempline cfl
               inner join characteristicstemplate cft on cft.characteristicstemplate_id = cfl.characteristicstemplate_id
         on cfl.characteristic_id = dff.characteristic_id
         where ch.dialog_id = 41 and ch.code = 'CASUP' and cft.code = 'SUPP' and dff.entity_id = pnl.Product_Id) --CA code
  else (select max(dff.stringvalue) from dialogflexfields dff
         inner join characteristic ch on ch.characteristic_id = dff.characteristic_id
         inner join characteristicstempline cfl
               inner join characteristicstemplate cft on cft.characteristicstemplate_id = cfl.characteristicstemplate_id
         on cfl.characteristic_id = dff.characteristic_id
         where ch.dialog_id = 41 and ch.code = 'USSUP' and cft.code = 'SUPP' and dff.entity_id = pnl.Product_Id) --US is the default code
    end) SuppProdCode
    , (case when 'CA' = (select co.code from country co where co.country_id = p.country_id)
      then (select chd.description
            from characteristic ch, characteristic_desc chd
            where ch.dialog_id = 41 and ch.code = 'CASUP' and ch.characteristic_id = chd.characteristic_id
            and chd.language_id = lan.language_id) --CA code
      else (select chd.description
            from characteristic ch, characteristic_desc chd
            where ch.dialog_id = 41 and ch.code = 'USSUP' and ch.characteristic_id = chd.characteristic_id
            and chd.language_id = lan.language_id) --US is the default code
        end) FlexFieldDesc
        from routecontrol rc, plant p, STOP st, packingnote pn, packingnoteline pnl, reportparam rp, customer c, languages lan
        where rc.routecontrol_id = st.routecontrol_id
				  and rc.plant_id = p.plant_id
          and pn.stop_id = st.stop_id and pn.packingnote_id = rp.number_value
          and pnl.packingnote_id = pn.packingnote_id
          and pnl.putuptype = 5 --packer loose linen
          and st.customer_link_id = c.customer_id
          and c.language_id = lan.language_id
        group by rc.plant_id,
				         p.code,p.country_id,
                 rc.routecontrol_id,
                 rc.drivingdate,
                 rc.route_id,
                 pn.plantdepartment_id,
                 pnl.product_id,
                 pnl.sizedefinition_id,
                 rp.reportparam_id,
                 pnl.bundleqty,
                 lan.code, lan.language_id--,st.Customer_Link_Id
       ) x,
       (select rownum nr from (select 1 just_a_column from dual connect by level <= 1000)
       ) c
where c.nr <= f_packernoofbundles(x.tobedeliveredamount, x.bundleqty)

/
create or replace view V_PACKINGCUSTSUMMARY_DFD
 (LINETYPE, PLANT_ID, PLANTCODE, ROUTENUMBER, ROUTEDESC, DEPOTDESC, DRIVERNAME, DELIVERYDATE, LOADINGDOCK, TRUCKCODE, TRUCKDESC, STARTTIMECH, STOPNUMBER, CUSTOMERNUMBER, CUSTOMERNAME, PASSERBYCUSTOMER, PN_COUNT, DELPOINTCODE, DELPOINTDESC, SDL_PRODUCTS, WI_PRODUCTS, NONBUSINESSDAYS, PLANTDEPCODE, DEPARTMENTNUMBER, DISTRIBUTIONPOINTNUMBER)
as select distinct
1 linetype,
plant.plant_id,
plant.code plantcode,
r.routenumber,
r.description routedesc,
d.description depotdesc,
(case when rc.drivernumber = 0 then e.name
        else (select employee.name from employee where employee.employeenumber = rc.drivernumber
             and employee.plant_id = plant.plant_id)
   end) drivername,
rc.drivingdate deliverydate,
rc.loadingdock,
t.code truckcode,
t.description truckdesc,
to_char(rc.starttime,'fmhhfm:MI:AM') starttimech,
s.stopnumber,
c.customernumber,
c.name customername,
c.passerbycustomer,
(select count(1) from packingnote pn
        where pn.stop_id = s.stop_id) pn_count,
nvl(delp.code,(select delp1.code from deliverypoint delp1 where delp1.deliverypoint_id = rs.deliverypoint_id)) delpointcode,
nvl(delp.description,(select delp2.description from deliverypoint delp2 where delp2.deliverypoint_id = rs.deliverypoint_id)) delpointdesc,
(select count(1)
 from productlistperdistribpoint plpd
 inner join distributionpoint dp on plpd.distributionpoint_id = dp.distributionpoint_id
 inner join department d on dp.department_id = d.department_id
 inner join product pr on plpd.product_id = pr.product_id
 inner join standarddeliveryline sdl on plpd.productlistperdistribpoint_id = sdl.productlistperdistribpoint_id
 where d.customer_id = c.customer_id
 and dp.deliverypoint_id = nvl(delp.deliverypoint_id,rs.deliverypoint_id)
 and pr.putuptype = 1
 and sdl.dateactive <= rc.drivingdate and sdl.dateinactive >= rc.drivingdate) sdl_products,
(select count(1)
 from wearerinventory wi
 inner join weareremployment we on wi.weareremployment_id = we.weareremployment_id
 left outer join locker l on we.locker_id = l.locker_id
 where nvl(we.deliverypoint_id,l.deliverypoint_id) = nvl(delp.deliverypoint_id,rs.deliverypoint_id)
 and wi.dateactive <= rc.drivingdate and wi.dateinactive >= rc.drivingdate) wi_products,
(select count(1) from nonbusinessday nbd
 where nbd.customer_id = c.customer_id
 and nbd.nonbusinessday = rc.drivingdate
 and nbd.closestatus <> 3) nonbusinessdays,
pdep.code plantdepcode,
dep.departmentnumber,
dp.distributionpointnumber
from route r
inner join routecontrol rc on r.route_id = rc.route_id
inner join stop s on rc.routecontrol_id = s.routecontrol_id
left outer join routestop rs on s.routestop_id = rs.routestop_id
left outer join deliverypoint delp on s.deliverypoint_id = delp.deliverypoint_id
inner join customer c on s.customer_link_id = c.customer_id
inner join department dep on c.customer_id = dep.customer_id
inner join distributionpoint dp on dp.department_id = dep.department_id
inner join standarddelivery sdl on sdl.distributionpoint_id = dp.distributionpoint_id
inner join plantdepartment pdep on sdl.plantdepartment_id = pdep.plantdepartment_id
left outer join depot d on r.depot_id = d.depot_id
left outer join employee e on r.driver_id = e.employee_id
left outer join truck t on r.truck_id = t.truck_id
inner join plant on r.plant_id = plant.plant_id
where (s.status in (0, 3))
and dp.deliverypoint_id = nvl(delp.deliverypoint_id,rs.deliverypoint_id)
and pdep.plant_id = plant.plant_id
union
select distinct
2 linetype,
plant.plant_id,
plant.code plantcode,
r.routenumber,
r.description routedesc,
d.description depotdesc,
(case when rc.drivernumber = 0 then e.name
        else (select employee.name from employee where employee.employeenumber = rc.drivernumber
             and employee.plant_id = plant.plant_id)
   end) drivername,
rc.drivingdate deliverydate,
rc.loadingdock,
t.code truckcode,
t.description truckdesc,
to_char(rc.starttime,'fmhhfm:MI:AM') starttimech,
s.stopnumber,
c.customernumber,
c.name customername,
c.passerbycustomer,
(select count(1) from packingnote pn
        where pn.stop_id = s.stop_id) pn_count,
nvl(delp.code,(select delp3.code from deliverypoint delp3 where delp3.deliverypoint_id = rs.deliverypoint_id)) delpointcode,
nvl(delp.description,(select delp4.description from deliverypoint delp4 where delp4.deliverypoint_id = rs.deliverypoint_id)) delpointdesc,
(select count(1)
 from productlistperdistribpoint plpd
 inner join distributionpoint dp on plpd.distributionpoint_id = dp.distributionpoint_id
 inner join department d on dp.department_id = d.department_id
 inner join product pr on plpd.product_id = pr.product_id
 inner join standarddeliveryline sdl on plpd.productlistperdistribpoint_id = sdl.productlistperdistribpoint_id
 where d.customer_id = c.customer_id
 and dp.deliverypoint_id = nvl(delp.deliverypoint_id,rs.deliverypoint_id)
 and pr.putuptype = 1
 and sdl.dateactive <= rc.drivingdate and sdl.dateinactive >= rc.drivingdate) sdl_products,
(select count(1)
 from wearerinventory wi
 inner join weareremployment we on wi.weareremployment_id = we.weareremployment_id
 left outer join locker l on we.locker_id = l.locker_id
 where nvl(we.deliverypoint_id,l.deliverypoint_id) = nvl(delp.deliverypoint_id,rs.deliverypoint_id)
 and wi.dateactive <= rc.drivingdate and wi.dateinactive >= rc.drivingdate) wi_products,
(select count(1) from nonbusinessday nbd
 where nbd.customer_id = c.customer_id
 and nbd.nonbusinessday = rc.drivingdate
 and nbd.closestatus <> 3) nonbusinessdays,
 pdep.code plantdepcode,
dep.departmentnumber,
dp.distributionpointnumber
from route r
inner join routecontrol rc on r.route_id = rc.route_id
inner join stop s on rc.routecontrol_id = s.routecontrol_id
left outer join routestop rs on s.routestop_id = rs.routestop_id
left outer join deliverypoint delp on s.deliverypoint_id = delp.deliverypoint_id
inner join customer c on s.customer_link_id = c.customer_id
inner join department dep on c.customer_id = dep.customer_id
inner join distributionpoint dp on dp.department_id = dep.department_id
inner join standarddelivery sd on sd.distributionpoint_id = dp.distributionpoint_id
inner join standarddeliveryline sdl on sd.standarddelivery_id = sdl.standarddelivery_id
inner join productlistperdistribpoint plpd on sdl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
inner join product pr on plpd.product_id = pr.product_id
inner join productgroup pg on pr.productgroup_id = pg.productgroup_id
inner join packingdepartmentdefinition pdd on pg.productgroup_id = pdd.productgroup_id
inner join plantdepartment pdep on pdd.plantdepartment_id = pdep.plantdepartment_id
left outer join depot d on r.depot_id = d.depot_id
left outer join employee e on r.driver_id = e.employee_id
left outer join truck t on r.truck_id = t.truck_id
inner join plant on r.plant_id = plant.plant_id
where (s.status in (0, 3))
and sd.plantdepartment_id is null
and dp.deliverypoint_id = nvl(delp.deliverypoint_id,rs.deliverypoint_id)
and pdep.plant_id = plant.plant_id

/
create or replace view V_PACKINGNOTE
 (PACKINGNOTEID, STATUSTYPE, DRIVINGDATE, DEPOTCODE, DEPOTDESCRIPTION, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERLEGALNAME, STREET, STREET2, CITY, STATE, ZIPCODE, COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, PACKINGDEPARTMENTCODE, PACKINGDEPARTMENTDESCRIPTION, TRANSPORTARTICLECODE, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENUMBER, EMPLOYEENAME
, PRODUCTIONDATE, DELIVERYDATE, STATUSCODE, STATUSDESCRIPTION, REMARK, PROCESSBUCODE, PROCESSBUDESCRIPTION, INVOICEBUCODE, INVOICEBUDESCRIPTION, ROUTENUMBER, ROUTEDESCRIPTION, LOADINGDOCK, CLEANRETURN, DEADLINE, DEADLINEASNUMERIC, CONSIGNMENTNOTENUMBER, SYSTEMUSER_ID, TIMESTAMP, CREATIONTIMESTAMP, ENDDATEFORUSE, DAYDESCRIPTION, WEEK, LANGUAGECODE, DRIVERNAME, DRIVERNUMBER, BULKPUTUPONPACKINGNOTE, YEAR, PACKINGNOTECOLUMNS, DELIVERGARMENTS, STOPNUMBER, PUTUPREPORTPERCUSTOMER
, EXTRANAME1, CUSTOMERSEARCHNAME, ORIGIN, LAYOUTCODE, REMARKONPACKINGNOTE, REMARKONDELIVERYNOTE, DISTRICTDESC, DISTRICTCODE)
as SELECT PACKINGNOTE.PACKINGNOTE_ID PACKINGNOTEID,STATUS.STATUSTYPE,  ROUTECONTROL.DRIVINGDATE, DEPOT.CODE DEPOTCODE, DEPOT.DESCRIPTION DEPOTDESCRIPTION,
 PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME CUSTOMERLEGALNAME,
 ADDRESS.STREET, ADDRESS.STREET2, ADDRESS.CITY, ADDRESS.STATE, ADDRESS.ZIPCODE, ADDRESS.COUNTY,
 DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
 DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
  DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
 PACKINGNOTE.SEQUENCENUMBER, PLANTDEPARTMENT.CODE PACKINGDEPARTMENTCODE, PLANTDEPARTMENT.DESCRIPTION PACKINGDEPARTMENTDESCRIPTION,
 TRANSPORTARTICLE.CODE TRANSPORTARTICLECODE,
 (SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
 PACKINGNOTE.OCCUPANCY, EMPLOYEE.EMPLOYEENUMBER, EMPLOYEE.NAME EMPLOYEENAME,
 PACKINGNOTE.PRODUCTIONDATE,
 PACKINGNOTE.DELIVERYDATE,
 STATUS.CODE STATUSCODE,
 (SELECT DESCRIPTION FROM STATUS_DESC S WHERE S.STATUS_ID = PACKINGNOTE.STATUS_ID AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) STATUSDESCRIPTION,
 PACKINGNOTE.PNREMARK REMARK, PROCESSBU.CODE PROCESSBUCODE, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
 INVOICEBU.CODE INVOICEBUCODE, INVOICEBU.DESCRIPTION INVOICEBUDESCRIPTION,
 ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION ROUTEDESCRIPTION,ROUTE.LOADINGDOCK,
 PACKINGNOTE.CLEANRETURN,
 PACKINGNOTE.DEADLINE,
 GETTIMEASNUMERIC(PACKINGNOTE.DEADLINE) DEADLINEASNUMERIC,
 CONSIGNMENTNOTE.CONSIGNMENTNOTENUMBER,
 PACKINGNOTE.SYSTEMUSER_ID, PACKINGNOTE.TIMESTAMP,PACKINGNOTE.CREATIONTIMESTAMP,
 PACKINGNOTE.ENDDATEFORUSE,
 (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,
  DRIVER.NAME DRIVERNAME,
  DRIVER.EMPLOYEENUMBER DRIVERNUMBER
  , CASE WHEN CUSTOMER.DELNOTEFORBULKPUTUPITEMS = 0 THEN  'N' ELSE 'Y' END BULKPUTUPONPACKINGNOTE,
  PACKINGNOTE.YEAR YEAR
  , (SELECT SS.VALUE FROM SYSTEMSETTING SS WHERE SS.PLANT_ID = PROCESSBU.PLANT_ID
            AND SS.NAME = 'PACKINGNOTECOLUMNS') PACKINGNOTECOLUMNS
  , (SELECT COUNT(1) FROM CUSTOMERDELIVERYDAY CDD WHERE CUSTOMER.CUSTOMER_ID = CDD.CUSTOMER_ID
        AND CDD.DAY_ID = PACKINGNOTE.DAYNUMBER AND CDD.TYPEOFMERCHADISE = 2) DELIVERGARMENTS,
        PACKINGNOTE.STOPNUMBER, ROUTE.PUTUPREPORTPERCUSTOMER,
		CUSTOMER.EXTRANAME1, CUSTOMER.SEARCHNAME CUSTOMERSEARCHNAME, PACKINGNOTE.Origin,
(select fly.code from formlayout fly where fly.formlayout_id = CUSTOMER.deliverynotelayout_id) layoutcode,
DISTRIBUTIONPOINT.REMARKONPACKINGNOTE, DISTRIBUTIONPOINT.REMARKONDELIVERYNOTE, di.code DistrictDesc, di.description DistrictCode
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, PLANTDEPARTMENT,
       TRANSPORTARTICLE,STATUS, DELIVERYPOINT, ADDRESS,
       BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU,
       PACKINGNOTE
       LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
       LEFT OUTER JOIN ROUTECONTROL ON (PACKINGNOTE.ROUTECONTROL_ID = ROUTECONTROL.ROUTECONTROL_ID )
       LEFT OUTER JOIN CONSIGNMENTNOTE ON (PACKINGNOTE.CONSIGNMENTNOTE_ID = CONSIGNMENTNOTE.CONSIGNMENTNOTE_ID)
       LEFT OUTER JOIN ROUTE
              LEFT OUTER JOIN DEPOT ON DEPOT.DEPOT_ID = ROUTE.DEPOT_ID
              LEFT OUTER JOIN EMPLOYEE DRIVER ON DRIVER.EMPLOYEE_ID = ROUTE.DRIVER_ID
              INNER JOIN DISTRICT DI on DI.District_Id = Route.District_Id
       ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID,
       LANGUAGES
 	WHERE
      PACKINGNOTE.TRANSPORTARTICLE_ID = TRANSPORTARTICLE.TRANSPORTARTICLE_ID
  AND PACKINGNOTE.STATUS_ID = STATUS.STATUS_ID
  AND STATUS.STATUSTYPE = 'PN'  --AND (STATUS.CODE='10' OR STATUS.CODE ='20' OR STATUS.CODE ='5')
  AND CAST(STATUS.CODE AS NUMERIC)<=20
  AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = ADDRESS.ADDRESS_ID
	AND PACKINGNOTE.PLANTDEPARTMENT_ID = PLANTDEPARTMENT.PLANTDEPARTMENT_ID
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
	AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  AND PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
	AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
	AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID

/
create or replace view V_PACKINGNOTELINE
 (PACKINGNOTEID, PRODUCTGROUPCODE, PRODUCTCODE, PRODUCTDESCRIPTION, ACTIVITYCODE, ACTIVITYDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, FINISHINGMETHODCODE, PACKINGSEQUENCE, PACKINGAMOUNT, THEORETICALWEIGHT, STANDARDAMOUNT, VARIATIONAMOUNT, DELIVEREDAMOUNT, TOBEDELIVEREDAMOUNT, NODELIVERYAMOUNT, PRICE, DISCOUNT, LOCATION, REMARKFORPACKINGINSTRUCTIONS, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE, BULKPUTUP
, PUTUPTYPE, PACKINGNOTELINE_ID, PACKINGAMOUNTPSZ, BUNDLEQTY, PRODUCT_ID, ISPACK, PRICECOG, SEQUENCENUMBER, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, PACKINGGROUP, REPLACEMENTQTY, REPLACEMENTLOSSQTY, PROD_PACKINGSEQUENCE)
as SELECT PACKINGNOTELINE.PACKINGNOTE_ID,--PACKINGNOTE.PACKINGNOTE_ID,
  PRODUCTGROUP.CODE, --PACKINGNOTE.NOTENUMBER,
  PRODUCT.CODE PRODUCTCODE,
  (SELECT DESCRIPTION FROM PRODUCT_DESC P WHERE P.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
     AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  PRODUCTDESCRIPTION, -- PRODUCTDESCRIPTION
  ACTIVITY.CODE ACTIVITYCODE,
  (SELECT DESCRIPTION FROM ACTIVITY_DESC AD WHERE AD.ACTIVITY_ID = ACTIVITY.ACTIVITY_ID
     AND AD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  ACTIVITYDESCRIPTION,
  PACKINGNOTELINE.CUSTOMCODE,
  PACKINGNOTELINE.CUSTOMDESCRIPTION, -- PRODUCTCUSTOMDESCRIPTION
  SIZEDEFINITION.CODE SIZECODE,
  (SELECT DESCRIPTION FROM SIZEDEFINITION_DESC S WHERE S.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID
     AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  SIZEDESCRIPTION,
  (SELECT DESCRIPTION FROM FINISHINGMETHOD_DESC F WHERE F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
     AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  FINISHINGMETHODDESCRIPTION,
  FINISHINGMETHOD.CODE FINISHINGMETHODCODE,
  PACKINGNOTELINE.PACKINGSEQUENCE, PRODUCT.PACKINGAMOUNT,
  CASE
   WHEN PSZ.THEORETICALWEIGHT = 0 THEN PRODUCT.THEORETICALWEIGHT
	 ELSE PSZ.THEORETICALWEIGHT
   END  THEORETICALWEIGHT,
--  PRODUCT.THEORETICALWEIGHT
  PACKINGNOTELINE.STANDARDAMOUNT, PACKINGNOTELINE.VARIATIONAMOUNT,
  PACKINGNOTELINE.DELIVEREDAMOUNT, PACKINGNOTELINE.TOBEDELIVEREDAMOUNT,
  PACKINGNOTELINE.NODELIVERYAMOUNT NODELIVERYAMOUNT,
  (CASE WHEN PACKINGNOTELINE.PRICE IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICE END) PRICE, PACKINGNOTELINE.DISCOUNT, PACKINGNOTELINE.LOCATION,
  PACKINGNOTELINE.REMARKFORPACKINGINSTRUCTIONS, PACKINGNOTELINE.SYSTEMUSER_ID, PACKINGNOTELINE.TIMESTAMP,
  LANGUAGES.CODE LANGUAGECODE,
  CASE WHEN PACKINGNOTELINE.PUTUPTYPE = 2 THEN 'Y' ELSE 'N' END BULKPUTUP, PACKINGNOTELINE.PUTUPTYPE,
  PACKINGNOTELINE.PACKINGNOTELINE_ID, PSZ.PACKINGAMOUNT PACKINGAMOUNTPSZ,
  PACKINGNOTELINE.BUNDLEQTY,
  PRODUCT.PRODUCT_ID, PRODUCT.PACK ISPACK,
  (CASE WHEN PACKINGNOTELINE.PRICECOG IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICECOG END) PRICECOG
  , PSZ.SEQUENCENUMBER, PACKINGNOTELINE.NOCHARGEPREVSHORTAGE, PACKINGNOTELINE.NOCHARGEPREVREJECTED
  , PRODUCT.PACKINGGROUP
  , PACKINGNOTELINE.REPLACEMENTQTY
  , PACKINGNOTELINE.REPLACEMENTLOSSQTY, PRODUCT.PACKINGSEQUENCE Prod_PACKINGSEQUENCE
FROM PACKINGNOTELINE , FINISHINGMETHOD ,
      --PACKINGNOTE,
      PRODUCT,PRODUCTGROUP, ACTIVITY,
      SIZEDEFINITION, LANGUAGES
      , PRODUCTSIZE PSZ
WHERE PACKINGNOTELINE.PRODUCT_ID = PRODUCT.PRODUCT_ID
  AND PACKINGNOTELINE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
  AND PRODUCTGROUP.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID
  AND FINISHINGMETHOD.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
      AND PRODUCT.PRODUCT_ID = PSZ.PRODUCT_ID
          AND PSZ.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
  AND PRODUCTGROUP.ACTIVITY_ID = ACTIVITY.ACTIVITY_ID

/
create or replace view V_PACKINGNOTELINEPERDELSCH
 (PACKINGNOTELINE_ID, STARTDATE, TOBEDELIVEREDQTY, DELIVEREDQTY, CODE, DEFAULTDELIVERYSCHEME, FREQUENCY, OFFSETWEEK, SYSTEMUSER_ID, TIMESTAMP)
as SELECT 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, DELIVERYSCHEME SC
WHERE PD.DELIVERYSCHEME_ID = SC.DELIVERYSCHEME_ID

/
create or replace view V_PACKINGNOTELINEPUTUP_ECL
 (PACKINGNOTEID, PUTUPTYPE)
as SELECT PACKINGNOTELINE.PACKINGNOTE_ID PACKINGNOTEID,PACKINGNOTELINE.PUTUPTYPE
FROM PACKINGNOTELINE

/
create or replace view V_PACKINGNOTELINE_AMM
 (PACKINGNOTEID, PRODUCTGROUPCODE, PRODUCTCODE, PRODUCTDESCRIPTION, ACTIVITYCODE, ACTIVITYDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, FINISHINGMETHODCODE, PACKINGSEQUENCE, PACKINGAMOUNT, THEORETICALWEIGHT, STANDARDAMOUNT, VARIATIONAMOUNT, DELIVEREDAMOUNT, TOBEDELIVEREDAMOUNT, NODELIVERYAMOUNT, PRICE, DISCOUNT, LOCATION, REMARKFORPACKINGINSTRUCTIONS, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE, BULKPUTUP
, PUTUPTYPE, PACKINGNOTELINE_ID, PACKINGAMOUNTPSZ, BUNDLEQTY, PRODUCT_ID, ISPACK, PRICECOG, SEQUENCENUMBER, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, PACKINGGROUP, REPLACEMENTQTY, REPLACEMENTLOSSQTY, FULLLOAD, SUPPPRODCODE)
as SELECT PACKINGNOTELINE.PACKINGNOTE_ID packingnoteid,
  PRODUCTGROUP.CODE productgroupcode, --PACKINGNOTE.NOTENUMBER,
  PRODUCT.CODE PRODUCTCODE,
  (SELECT DESCRIPTION FROM PRODUCT_DESC P WHERE P.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
     AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  PRODUCTDESCRIPTION,
  ACTIVITY.CODE ACTIVITYCODE,
  (SELECT DESCRIPTION FROM ACTIVITY_DESC AD WHERE AD.ACTIVITY_ID = ACTIVITY.ACTIVITY_ID
     AND AD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  ACTIVITYDESCRIPTION,
  PACKINGNOTELINE.CUSTOMCODE productcustomcode,
  PACKINGNOTELINE.CUSTOMDESCRIPTION productcustomdescription,
  SIZEDEFINITION.CODE SIZECODE,
  (SELECT DESCRIPTION FROM SIZEDEFINITION_DESC S WHERE S.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID
     AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  SIZEDESCRIPTION,
  (SELECT DESCRIPTION FROM FINISHINGMETHOD_DESC F WHERE F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
     AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  FINISHINGMETHODDESCRIPTION,
  FINISHINGMETHOD.CODE FINISHINGMETHODCODE,
  PACKINGNOTELINE.PACKINGSEQUENCE, PRODUCT.PACKINGAMOUNT,
  CASE
   WHEN PSZ.THEORETICALWEIGHT = 0 THEN PRODUCT.THEORETICALWEIGHT
	 ELSE PSZ.THEORETICALWEIGHT
   END  THEORETICALWEIGHT,
  PACKINGNOTELINE.STANDARDAMOUNT, PACKINGNOTELINE.VARIATIONAMOUNT,
  PACKINGNOTELINE.DELIVEREDAMOUNT, PACKINGNOTELINE.TOBEDELIVEREDAMOUNT,
  PACKINGNOTELINE.NODELIVERYAMOUNT NODELIVERYAMOUNT,
  (CASE WHEN PACKINGNOTELINE.PRICE IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICE END) PRICE, PACKINGNOTELINE.DISCOUNT, PACKINGNOTELINE.LOCATION,
  PACKINGNOTELINE.REMARKFORPACKINGINSTRUCTIONS, PACKINGNOTELINE.SYSTEMUSER_ID, PACKINGNOTELINE.TIMESTAMP,
  LANGUAGES.CODE LANGUAGECODE,
  CASE WHEN PACKINGNOTELINE.PUTUPTYPE = 2 THEN 'Y' ELSE 'N' END BULKPUTUP, PACKINGNOTELINE.PUTUPTYPE,
  PACKINGNOTELINE.PACKINGNOTELINE_ID,
  coalesce((select pss.packingamount from plantproductsizesettings pss, packingnote pa, businessunit bu
    where pa.packingnote_id = PACKINGNOTELINE.Packingnote_Id and bu.businessunit_id = pa.processbusinessunit_id and
       pss.plant_id = bu.plant_id and pss.product_id = PRODUCT.product_id
             and pss.sizedefinition_id = SIZEDEFINITION.sizedefinition_id) , PSZ.PACKINGAMOUNT) PACKINGAMOUNTPSZ,
  PACKINGNOTELINE.BUNDLEQTY,
  PRODUCT.PRODUCT_ID, PRODUCT.PACK ISPACK,
  (CASE WHEN PACKINGNOTELINE.PRICECOG IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICECOG END) PRICECOG
  , PSZ.SEQUENCENUMBER, PACKINGNOTELINE.NOCHARGEPREVSHORTAGE, PACKINGNOTELINE.NOCHARGEPREVREJECTED
  , PRODUCT.PACKINGGROUP
  , PACKINGNOTELINE.REPLACEMENTQTY
  , PACKINGNOTELINE.REPLACEMENTLOSSQTY, PRODUCTGROUP.FULLLOAD
, (case when 'CA' = (select co.code from country co, plant pl, packingnote pn, businessunit pbu
        where pn.packingnote_id = packingnoteline.packingnote_id and pn.processbusinessunit_id = pbu.businessunit_id
              and pl.plant_id = pbu.plant_id and co.country_id = pl.country_id)
  then (select max(dff.stringvalue) from dialogflexfields dff
         inner join characteristic ch on ch.characteristic_id = dff.characteristic_id
         inner join characteristicstempline cfl
               inner join characteristicstemplate cft on cft.characteristicstemplate_id = cfl.characteristicstemplate_id
         on cfl.characteristic_id = dff.characteristic_id
         where ch.dialog_id = 41 and ch.code = 'CASUP' and cft.code = 'SUPP' and dff.entity_id = PRODUCT.Product_Id) --CA code
  else (select max(dff.stringvalue) from dialogflexfields dff
         inner join characteristic ch on ch.characteristic_id = dff.characteristic_id
         inner join characteristicstempline cfl
               inner join characteristicstemplate cft on cft.characteristicstemplate_id = cfl.characteristicstemplate_id
         on cfl.characteristic_id = dff.characteristic_id
         where ch.dialog_id = 41 and ch.code = 'USSUP' and cft.code = 'SUPP' and dff.entity_id = PRODUCT.Product_Id) --US is the default code
    end) SuppProdCode
FROM PACKINGNOTELINE, FINISHINGMETHOD,
      PRODUCT, PRODUCTGROUP, ACTIVITY,
      SIZEDEFINITION, LANGUAGES, PRODUCTSIZE PSZ
WHERE PACKINGNOTELINE.PRODUCT_ID = PRODUCT.PRODUCT_ID
  AND PACKINGNOTELINE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
  AND PRODUCTGROUP.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID
  AND FINISHINGMETHOD.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
      AND PRODUCT.PRODUCT_ID = PSZ.PRODUCT_ID
          AND PSZ.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
  AND PRODUCTGROUP.ACTIVITY_ID = ACTIVITY.ACTIVITY_ID

/
create or replace view V_PACKINGNOTELINE_BCM
 (PACKINGNOTEID, PRODUCTGROUPCODE, PRODUCTCODE, PRODUCTDESCRIPTION, ACTIVITYCODE, ACTIVITYDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, FINISHINGMETHODCODE, PACKINGSEQUENCE, PACKINGAMOUNT, THEORETICALWEIGHT, STANDARDAMOUNT, VARIATIONAMOUNT, DELIVEREDAMOUNT, TOBEDELIVEREDAMOUNT, NODELIVERYAMOUNT, PRICE, DISCOUNT, LOCATION, REMARKFORPACKINGINSTRUCTIONS, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE, BULKPUTUP
, PUTUPTYPE, PACKINGNOTELINE_ID, PACKINGAMOUNTPSZ, BUNDLEQTY, PRODUCT_ID, ISPACK, PRICECOG, SEQUENCENUMBER, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, PRODUCTGROUPDESCRIPTION, PGCUSTOMDESCRIPTION)
as SELECT PACKINGNOTELINE.PACKINGNOTE_ID,--PACKINGNOTE.PACKINGNOTE_ID,
  PRODUCTGROUP.CODE, --PACKINGNOTE.NOTENUMBER,
  PRODUCT.CODE PRODUCTCODE,
  (SELECT DESCRIPTION FROM PRODUCT_DESC P WHERE P.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
     AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  PRODUCTDESCRIPTION, -- PRODUCTDESCRIPTION
  ACTIVITY.CODE ACTIVITYCODE,
  (SELECT DESCRIPTION FROM ACTIVITY_DESC AD WHERE AD.ACTIVITY_ID = ACTIVITY.ACTIVITY_ID
     AND AD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  ACTIVITYDESCRIPTION,
  PACKINGNOTELINE.CUSTOMCODE,
  PACKINGNOTELINE.CUSTOMDESCRIPTION, -- PRODUCTCUSTOMDESCRIPTION
  SIZEDEFINITION.CODE SIZECODE,
  (SELECT DESCRIPTION FROM SIZEDEFINITION_DESC S WHERE S.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID
     AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  SIZEDESCRIPTION,
  (SELECT DESCRIPTION FROM FINISHINGMETHOD_DESC F WHERE F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
     AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  FINISHINGMETHODDESCRIPTION,
  FINISHINGMETHOD.CODE FINISHINGMETHODCODE,
  PACKINGNOTELINE.PACKINGSEQUENCE, PRODUCT.PACKINGAMOUNT,
  CASE
   WHEN PSZ.THEORETICALWEIGHT = 0 THEN PRODUCT.THEORETICALWEIGHT
	 ELSE PSZ.THEORETICALWEIGHT
   END  THEORETICALWEIGHT,
--  PRODUCT.THEORETICALWEIGHT
  PACKINGNOTELINE.STANDARDAMOUNT, PACKINGNOTELINE.VARIATIONAMOUNT,
  PACKINGNOTELINE.DELIVEREDAMOUNT, PACKINGNOTELINE.TOBEDELIVEREDAMOUNT,
  PACKINGNOTELINE.NODELIVERYAMOUNT NODELIVERYAMOUNT,
  (CASE WHEN PACKINGNOTELINE.PRICE IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICE END) PRICE, PACKINGNOTELINE.DISCOUNT, PACKINGNOTELINE.LOCATION,
  PACKINGNOTELINE.REMARKFORPACKINGINSTRUCTIONS, PACKINGNOTELINE.SYSTEMUSER_ID, PACKINGNOTELINE.TIMESTAMP,
  LANGUAGES.CODE LANGUAGECODE,
  CASE WHEN PACKINGNOTELINE.PUTUPTYPE = 2 THEN 'Y' ELSE 'N' END BULKPUTUP, PACKINGNOTELINE.PUTUPTYPE,
  PACKINGNOTELINE.PACKINGNOTELINE_ID, PSZ.PACKINGAMOUNT PACKINGAMOUNTPSZ,
  PACKINGNOTELINE.BUNDLEQTY,
  PRODUCT.PRODUCT_ID, PRODUCT.PACK ISPACK,
  (CASE WHEN PACKINGNOTELINE.PRICECOG IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICECOG END) PRICECOG
  , PSZ.SEQUENCENUMBER, PACKINGNOTELINE.NOCHARGEPREVSHORTAGE, PACKINGNOTELINE.NOCHARGEPREVREJECTED
  , (SELECT DESCRIPTION FROM PRODUCTGROUP_DESC A WHERE  A.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTGROUPDESCRIPTION
  , (SELECT PGPC.CUSTOMDESCRITPION FROM PRODUCTGROUPPERCUSTOMER PGPC, DISTRIBUTIONPOINT DP, DEPARTMENT DEP
         WHERE  PGPC.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID AND PGPC.CUSTOMER_ID = DEP.CUSTOMER_ID
                AND DEP.DEPARTMENT_ID = DP.DEPARTMENT_ID AND DP.DISTRIBUTIONPOINT_ID = PACKINGNOTE.DISTRIBUTIONPOINT_ID) PGCUSTOMDESCRIPTION
FROM PACKINGNOTELINE , FINISHINGMETHOD ,
      PACKINGNOTE,
      PRODUCT,PRODUCTGROUP, ACTIVITY,
      SIZEDEFINITION, LANGUAGES
      , PRODUCTSIZE PSZ
WHERE PACKINGNOTELINE.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID
  AND PACKINGNOTELINE.PRODUCT_ID = PRODUCT.PRODUCT_ID
  AND PACKINGNOTELINE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
  AND PRODUCTGROUP.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID
  AND FINISHINGMETHOD.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
      AND PRODUCT.PRODUCT_ID = PSZ.PRODUCT_ID
          AND PSZ.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
  AND PRODUCTGROUP.ACTIVITY_ID = ACTIVITY.ACTIVITY_ID

/
create or replace view V_PACKINGNOTELINE_LLG
 (PACKINGNOTE_ID, CODE, PRODUCTCODE, PRODUCTDESCRIPTION, ACTIVITYCODE, ACTIVITYDESCRIPTION, CUSTOMCODE, CUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, FINISHINGMETHODCODE, PACKINGSEQUENCE, PACKINGAMOUNT, THEORETICALWEIGHT, STANDARDAMOUNT, VARIATIONAMOUNT, DELIVEREDAMOUNT, TOBEDELIVEREDAMOUNT, NODELIVERYAMOUNT, PRICE, DISCOUNT, LOCATION, REMARKFORPACKINGINSTRUCTIONS, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE, BULKPUTUP, PUTUPTYPE, PACKINGNOTELINE_ID
, PACKINGAMOUNTPSZ, BUNDLEQTY, PRODUCT_ID, ISPACK, PRICECOG, SEQUENCENUMBER, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, SIZEDEFINITION_ID, FINISHINGMETHOD_ID, PLPC_REMARK)
as select pnl.packingnote_id,
  pg.code,
  p.code productcode,
  (select description from product_desc pd where pd.product_id = pnl.product_id
     and pd.language_id = l.language_id)  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,
  sd.code sizecode,
  (select description from sizedefinition_desc sdef where sdef.sizedefinition_id = pnl.sizedefinition_id
     and sdef.language_id = l.language_id)  sizedescription,
  (select description from finishingmethod_desc fd where fd.finishingmethod_id = pnl.finishingmethod_id
     and fd.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,
  pnl.standardamount, pnl.variationamount,
  pnl.deliveredamount, pnl.tobedeliveredamount,
  pnl.nodeliveryamount nodeliveryamount,
  (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, pnl.nochargeprevshortage, pnl.nochargeprevrejected
  , pnl.sizedefinition_id
  , pnl.finishingmethod_id
  , (select plpc.remark from productlistpercustomer plpc where plpc.customer_id =
                                                         (select c.customer_id from customer c, department d, distributionpoint dp, packingnote pn
                                                                   where c.customer_id = d.customer_id and d.department_id = dp.department_id
                                                                   and dp.distributionpoint_id = pn.distributionpoint_id
                                                                   and pn.packingnote_id = pnl.packingnote_id)
    and plpc.product_id = pnl.product_id and plpc.sizedefinition_id = pnl.sizedefinition_id
    and plpc.finishingmethod_id = pnl.finishingmethod_id and plpc.dateactive <= sysdate and plpc.dateinactive > sysdate) plpc_remark
from packingnoteline pnl
      , finishingmethod fm
      , product p
      , productgroup pg
      , activity a
      , sizedefinition sd
      , languages l
      , productsize psz
where 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

/
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_PACKINGNOTELINE_REI
 (PACKINGNOTEID, PRODUCTGROUPCODE, PRODUCTCODE, PRODUCTDESCRIPTION, ACTIVITYCODE, ACTIVITYDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, FINISHINGMETHODCODE, WEIGHINGCATEGORYDESCRIPTION, WEIGHINGCATEGORYCODE, PACKINGSEQUENCE, PACKINGAMOUNT, THEORETICALWEIGHT, STANDARDAMOUNT, VARIATIONAMOUNT, DELIVEREDAMOUNT, TOBEDELIVEREDAMOUNT, NODELIVERYAMOUNT, PRICE, DISCOUNT, LOCATION, REMARKFORPACKINGINSTRUCTIONS
, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE, BULKPUTUP, PUTUPTYPE, PACKINGNOTELINE_ID, PACKINGAMOUNTPSZ, BUNDLEQTY, PRODUCT_ID, ISPACK, PRICECOG, SEQUENCENUMBER, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, PACKINGGROUP, REPLACEMENTQTY, REPLACEMENTLOSSQTY)
as SELECT PACKINGNOTELINE.PACKINGNOTE_ID,--PACKINGNOTE.PACKINGNOTE_ID,
  PRODUCTGROUP.CODE, --PACKINGNOTE.NOTENUMBER,
  PRODUCT.CODE PRODUCTCODE,
  (SELECT DESCRIPTION FROM PRODUCT_DESC P WHERE P.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
     AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  PRODUCTDESCRIPTION, -- PRODUCTDESCRIPTION
  ACTIVITY.CODE ACTIVITYCODE,
  (SELECT DESCRIPTION FROM ACTIVITY_DESC AD WHERE AD.ACTIVITY_ID = ACTIVITY.ACTIVITY_ID
     AND AD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  ACTIVITYDESCRIPTION,
  PACKINGNOTELINE.CUSTOMCODE,
  PACKINGNOTELINE.CUSTOMDESCRIPTION, -- PRODUCTCUSTOMDESCRIPTION
  SIZEDEFINITION.CODE SIZECODE,
  (SELECT DESCRIPTION FROM SIZEDEFINITION_DESC S WHERE S.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID
     AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  SIZEDESCRIPTION,
  (SELECT DESCRIPTION FROM FINISHINGMETHOD_DESC F WHERE F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
     AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  FINISHINGMETHODDESCRIPTION,
  FINISHINGMETHOD.CODE FINISHINGMETHODCODE,
  (SELECT DESCRIPTION FROM WEIGHINGCATEGORY_DESC W WHERE W.WEIGHINGCATEGORY_ID = PRODUCT.WEIGHINGCATEGORY_ID
     AND W.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  WEIGHINGCATEGORYDESCRIPTION,
  WEIGHINGCATEGORY.CODE,
  PACKINGNOTELINE.PACKINGSEQUENCE, PRODUCT.PACKINGAMOUNT,
  CASE
   WHEN PSZ.THEORETICALWEIGHT = 0 THEN PRODUCT.THEORETICALWEIGHT
   ELSE PSZ.THEORETICALWEIGHT
   END  THEORETICALWEIGHT,
--  PRODUCT.THEORETICALWEIGHT
  PACKINGNOTELINE.STANDARDAMOUNT, PACKINGNOTELINE.VARIATIONAMOUNT,
  PACKINGNOTELINE.DELIVEREDAMOUNT, PACKINGNOTELINE.TOBEDELIVEREDAMOUNT,
  PACKINGNOTELINE.NODELIVERYAMOUNT NODELIVERYAMOUNT,
  (CASE WHEN PACKINGNOTELINE.PRICE IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICE END) PRICE, PACKINGNOTELINE.DISCOUNT, PACKINGNOTELINE.LOCATION,
  REMARKFORPACKINGINSTRUCTIONS, PACKINGNOTELINE.SYSTEMUSER_ID, PACKINGNOTELINE.TIMESTAMP,
  LANGUAGES.CODE LANGUAGECODE,
  CASE WHEN PACKINGNOTELINE.PUTUPTYPE = 2 THEN 'Y' ELSE 'N' END BULKPUTUP, PACKINGNOTELINE.PUTUPTYPE,
  PACKINGNOTELINE.PACKINGNOTELINE_ID, PSZ.PACKINGAMOUNT PACKINGAMOUNTPSZ,
  PACKINGNOTELINE.BUNDLEQTY,
  PRODUCT.PRODUCT_ID, PRODUCT.PACK ISPACK,
  (CASE WHEN PACKINGNOTELINE.PRICECOG IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICECOG END) PRICECOG
  , PSZ.SEQUENCENUMBER, PACKINGNOTELINE.NOCHARGEPREVSHORTAGE, PACKINGNOTELINE.NOCHARGEPREVREJECTED
  , PRODUCT.PACKINGGROUP
  , PACKINGNOTELINE.REPLACEMENTQTY
  , PACKINGNOTELINE.REPLACEMENTLOSSQTY
FROM PACKINGNOTELINE , FINISHINGMETHOD , WEIGHINGCATEGORY,
      --PACKINGNOTE,
      PRODUCT,PRODUCTGROUP, ACTIVITY,
      SIZEDEFINITION, LANGUAGES
      , PRODUCTSIZE PSZ
WHERE PACKINGNOTELINE.PRODUCT_ID = PRODUCT.PRODUCT_ID
  AND PACKINGNOTELINE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
  AND PRODUCTGROUP.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID
  AND FINISHINGMETHOD.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
      AND PRODUCT.PRODUCT_ID = PSZ.PRODUCT_ID
          AND PSZ.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
  AND PRODUCTGROUP.ACTIVITY_ID = ACTIVITY.ACTIVITY_ID
  AND PRODUCT.WEIGHINGCATEGORY_ID = WEIGHINGCATEGORY.WEIGHINGCATEGORY_ID
  --and packingnoteline.packingnote_id=410321

/
create or replace view V_PACKINGNOTELINE_SNG
 (PACKINGNOTEID, PRODUCTGROUPCODE, PRODUCTCODE, PRODUCTDESCRIPTION, ACTIVITYCODE, ACTIVITYDESCRIPTION, PRODUCTCUSTOMCODE, PRODUCTCUSTOMDESCRIPTION, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODDESCRIPTION, FINISHINGMETHODCODE, PACKINGSEQUENCE, PACKINGAMOUNT, THEORETICALWEIGHT, STANDARDAMOUNT, VARIATIONAMOUNT, DELIVEREDAMOUNT, TOBEDELIVEREDAMOUNT, NODELIVERYAMOUNT, PRICE, DISCOUNT, LOCATION, REMARKFORPACKINGINSTRUCTIONS, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE, BULKPUTUP
, PUTUPTYPE, PACKINGNOTELINE_ID, PACKINGAMOUNTPSZ, BUNDLEQTY, PRODUCT_ID, ISPACK, PRICECOG, SEQUENCENUMBER, NOCHARGEPREVSHORTAGE, NOCHARGEPREVREJECTED, CAGES)
as SELECT PACKINGNOTELINE.PACKINGNOTE_ID,
  PRODUCTGROUP.CODE,
  PRODUCT.CODE PRODUCTCODE,
  (SELECT DESCRIPTION FROM PRODUCT_DESC P WHERE P.PRODUCT_ID = PACKINGNOTELINE.PRODUCT_ID
     AND P.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  PRODUCTDESCRIPTION,
  ACTIVITY.CODE ACTIVITYCODE,
  (SELECT DESCRIPTION FROM ACTIVITY_DESC AD WHERE AD.ACTIVITY_ID = ACTIVITY.ACTIVITY_ID
     AND AD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  ACTIVITYDESCRIPTION,
  PACKINGNOTELINE.CUSTOMCODE,
  PACKINGNOTELINE.CUSTOMDESCRIPTION,
  SIZEDEFINITION.CODE SIZECODE,
  (SELECT DESCRIPTION FROM SIZEDEFINITION_DESC S WHERE S.SIZEDEFINITION_ID = PACKINGNOTELINE.SIZEDEFINITION_ID
     AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  SIZEDESCRIPTION,
  (SELECT DESCRIPTION FROM FINISHINGMETHOD_DESC F WHERE F.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
     AND F.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID)  FINISHINGMETHODDESCRIPTION,
  FINISHINGMETHOD.CODE FINISHINGMETHODCODE,
  PACKINGNOTELINE.PACKINGSEQUENCE, PRODUCT.PACKINGAMOUNT,
  CASE
   WHEN PSZ.THEORETICALWEIGHT = 0 THEN PRODUCT.THEORETICALWEIGHT
	 ELSE PSZ.THEORETICALWEIGHT
   END  THEORETICALWEIGHT,
  PACKINGNOTELINE.STANDARDAMOUNT, PACKINGNOTELINE.VARIATIONAMOUNT,
  PACKINGNOTELINE.DELIVEREDAMOUNT, PACKINGNOTELINE.TOBEDELIVEREDAMOUNT,
  PACKINGNOTELINE.NODELIVERYAMOUNT NODELIVERYAMOUNT,
  (CASE WHEN PACKINGNOTELINE.PRICE IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICE END) PRICE, PACKINGNOTELINE.DISCOUNT, PACKINGNOTELINE.LOCATION,
  PACKINGNOTELINE.REMARKFORPACKINGINSTRUCTIONS, PACKINGNOTELINE.SYSTEMUSER_ID, PACKINGNOTELINE.TIMESTAMP,
  LANGUAGES.CODE LANGUAGECODE,
  CASE WHEN PACKINGNOTELINE.PUTUPTYPE = 2 THEN 'Y' ELSE 'N' END BULKPUTUP, PACKINGNOTELINE.PUTUPTYPE,
  PACKINGNOTELINE.PACKINGNOTELINE_ID, PSZ.PACKINGAMOUNT PACKINGAMOUNTPSZ,
  PACKINGNOTELINE.BUNDLEQTY,
  PRODUCT.PRODUCT_ID, PRODUCT.PACK ISPACK,
  (CASE WHEN PACKINGNOTELINE.PRICECOG IS NULL THEN 0 ELSE PACKINGNOTELINE.PRICECOG END) PRICECOG
  , PSZ.SEQUENCENUMBER, PACKINGNOTELINE.NOCHARGEPREVSHORTAGE, PACKINGNOTELINE.NOCHARGEPREVREJECTED
, CASE WHEN PRODUCT.CODE IN ('1200', '1201', '1202') THEN CEIL((PACKINGNOTELINE.STANDARDAMOUNT + PACKINGNOTELINE.VARIATIONAMOUNT)/100)
WHEN PRODUCT.CODE IN ('1160', '1216', 'ThermoCovers') THEN CEIL((PACKINGNOTELINE.STANDARDAMOUNT + PACKINGNOTELINE.VARIATIONAMOUNT)/140)
WHEN PRODUCT.CODE IN ('1228', '1229', '1230', '1231', '1232', '1233', '1234', 'CounterPanes', 'DualCovers') THEN CEIL((PACKINGNOTELINE.STANDARDAMOUNT + PACKINGNOTELINE.VARIATIONAMOUNT)/200)
WHEN PRODUCT.CODE IN ('1100', '1140', '1161', '1162') THEN CEIL((PACKINGNOTELINE.STANDARDAMOUNT + PACKINGNOTELINE.VARIATIONAMOUNT)/300)
WHEN PRODUCT.CODE IN ('HandTowels') THEN CEIL((PACKINGNOTELINE.STANDARDAMOUNT + PACKINGNOTELINE.VARIATIONAMOUNT)/360)
WHEN PRODUCT.CODE IN ('1300') THEN CEIL((PACKINGNOTELINE.STANDARDAMOUNT + PACKINGNOTELINE.VARIATIONAMOUNT)/400)
WHEN PRODUCT.CODE IN ('1367', '1371', '1392') THEN CEIL((PACKINGNOTELINE.STANDARDAMOUNT + PACKINGNOTELINE.VARIATIONAMOUNT)/600)
WHEN PRODUCT.CODE IN ('1120') THEN CEIL((PACKINGNOTELINE.STANDARDAMOUNT + PACKINGNOTELINE.VARIATIONAMOUNT)/1800)
WHEN PRODUCT.CODE IN ('0101') THEN coalesce(cast((select ta.code
          from transportarticle ta, packingnote pn
          where ta.transportarticle_id = pn.transportarticle_id
                and pn.packingnote_id = PACKINGNOTELINE.PACKINGNOTE_ID) as number), 0)
ELSE 0
END CAGES
FROM PACKINGNOTELINE , FINISHINGMETHOD ,
      PRODUCT,PRODUCTGROUP, ACTIVITY,
      SIZEDEFINITION, LANGUAGES
      , PRODUCTSIZE PSZ
WHERE PACKINGNOTELINE.PRODUCT_ID = PRODUCT.PRODUCT_ID
  AND PACKINGNOTELINE.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
  AND PRODUCTGROUP.PRODUCTGROUP_ID = PRODUCT.PRODUCTGROUP_ID
  AND FINISHINGMETHOD.FINISHINGMETHOD_ID = PACKINGNOTELINE.FINISHINGMETHOD_ID
      AND PRODUCT.PRODUCT_ID = PSZ.PRODUCT_ID
          AND PSZ.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
  AND PRODUCTGROUP.ACTIVITY_ID = ACTIVITY.ACTIVITY_ID

/
create or replace view V_PACKINGNOTELNPERDELSCH_BHO
 (PACKINGNOTELINE_ID, STARTDATE, TOBEDELIVEREDQTY, DELIVEREDQTY, CODE, DEFAULTDELIVERYSCHEME, FREQUENCY, OFFSETWEEK, DELIVERYSCHEME_DESCRIPTION, SYSTEMUSER_ID, TIMESTAMP)
as SELECT PD.PACKINGNOTELINE_ID, PD.STARTDATE, PD.TOBEDELIVEREDQTY, PD.DELIVEREDQTY,
       SC.CODE, SC.DEFAULTDELIVERYSCHEME, SC.FREQUENCY, SC.OFFSETWEEK,
       (SELECT max(SCD.DESCRIPTION)
              FROM deliveryscheme_desc SCD
              WHERE SCD.DELIVERYSCHEME_ID = SC.DELIVERYSCHEME_ID) DELIVERYSCHEME_DESCRIPTION,
       pd.systemuser_id, pd.timestamp
FROM packingnotelineperdelscheme PD, DELIVERYSCHEME SC
WHERE PD.DELIVERYSCHEME_ID = SC.DELIVERYSCHEME_ID

/
create or replace view V_PACKINGNOTE_BCM
 (PACKINGNOTEID, STATUSTYPE, DRIVINGDATE, DEPOTCODE, DEPOTDESCRIPTION, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERLEGALNAME, STREET, STREET2, CITY, STATE, ZIPCODE, COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, PACKINGDEPARTMENTCODE
, PACKINGDEPARTMENTDESCRIPTION, TRANSPORTARTICLECODE, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENUMBER, EMPLOYEENAME, PRODUCTIONDATE, DELIVERYDATE, STATUSCODE, STATUSDESCRIPTION, REMARK, PROCESSBUCODE, PROCESSBUDESCRIPTION, INVOICEBUCODE, INVOICEBUDESCRIPTION, ROUTENUMBER, ROUTEDESCRIPTION, LOADINGDOCK, CLEANRETURN, DEADLINE, DEADLINEASNUMERIC, CONSIGNMENTNOTENUMBER, SYSTEMUSER_ID, TIMESTAMP, CREATIONTIMESTAMP, ENDDATEFORUSE, DAYDESCRIPTION, WEEK, LANGUAGECODE
, DRIVERNAME, DRIVERNUMBER, BULKPUTUPONPACKINGNOTE, YEAR, PACKINGNOTECOLUMNS, DELIVERGARMENTS, STOPNUMBER, PUTUPREPORTPERCUSTOMER, LOADSEQUENCENR, TOTALSEQUENCE)
as SELECT PACKINGNOTE.PACKINGNOTE_ID PACKINGNOTEID,STATUS.STATUSTYPE,  ROUTECONTROL.DRIVINGDATE, DEPOT.CODE DEPOTCODE, DEPOT.DESCRIPTION DEPOTDESCRIPTION,
 PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME CUSTOMERLEGALNAME,
 ADDRESS.STREET, ADDRESS.STREET2, ADDRESS.CITY, ADDRESS.STATE, ADDRESS.ZIPCODE, ADDRESS.COUNTY,
 DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
 DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
 PLANT.CODE PLANTCODE, PLANT.NAME PLANTNAME, PLANT.WEBSITE PLANTWEBSITE, PLANT.EMAIL PLANTEMAIL,PLANTADDRESS.STREET PLANTSTREET,
 PLANTADDRESS.ZIPCODE PLANTZIPCODE,PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.PHONENO PLANTPHONENO, PLANT.FAXNO PLANTFAXNO,
 DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
 PACKINGNOTE.SEQUENCENUMBER, PLANTDEPARTMENT.CODE PACKINGDEPARTMENTCODE, PLANTDEPARTMENT.DESCRIPTION PACKINGDEPARTMENTDESCRIPTION,
 TRANSPORTARTICLE.CODE TRANSPORTARTICLECODE,
 (SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
 PACKINGNOTE.OCCUPANCY, EMPLOYEE.EMPLOYEENUMBER, EMPLOYEE.NAME EMPLOYEENAME,
 PACKINGNOTE.PRODUCTIONDATE,
 PACKINGNOTE.DELIVERYDATE,
 STATUS.CODE STATUSCODE,
 (SELECT DESCRIPTION FROM STATUS_DESC S WHERE S.STATUS_ID = PACKINGNOTE.STATUS_ID AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) STATUSDESCRIPTION,
 PACKINGNOTE.PNREMARK REMARK, PROCESSBU.CODE PROCESSBUCODE, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
 INVOICEBU.CODE INVOICEBUCODE, INVOICEBU.DESCRIPTION INVOICEBUDESCRIPTION,
 ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION ROUTEDESCRIPTION,ROUTE.LOADINGDOCK,
 PACKINGNOTE.CLEANRETURN,
 PACKINGNOTE.DEADLINE,
 GETTIMEASNUMERIC(PACKINGNOTE.DEADLINE) DEADLINEASNUMERIC,
 CONSIGNMENTNOTE.CONSIGNMENTNOTENUMBER,
 PACKINGNOTE.SYSTEMUSER_ID, PACKINGNOTE.TIMESTAMP,PACKINGNOTE.CREATIONTIMESTAMP,
 PACKINGNOTE.ENDDATEFORUSE,
 (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,
  DRIVER.NAME DRIVERNAME,
  DRIVER.EMPLOYEENUMBER DRIVERNUMBER
  , CASE WHEN CUSTOMER.DELNOTEFORBULKPUTUPITEMS = 0 THEN  'N' ELSE 'Y' END BULKPUTUPONPACKINGNOTE,
  PACKINGNOTE.YEAR  YEAR
  ,(SELECT SS.VALUE FROM SYSTEMSETTING SS WHERE SS.PLANT_ID = PROCESSBU.PLANT_ID
            AND SS.NAME = 'PACKINGNOTECOLUMNS' ) PACKINGNOTECOLUMNS
  , (SELECT COUNT(*) FROM CUSTOMERDELIVERYDAY CDD WHERE CUSTOMER.CUSTOMER_ID = CDD.CUSTOMER_ID
        AND CDD.DAY_ID = PACKINGNOTE.DAYNUMBER AND CDD.TYPEOFMERCHADISE =2) DELIVERGARMENTS,
        PACKINGNOTE.STOPNUMBER, ROUTE.PUTUPREPORTPERCUSTOMER
  ,     PACKINGNOTE.LOADSEQUENCENR LOADSEQUENCENR
  , (SELECT MAX(PN.LOADSEQUENCENR) FROM PACKINGNOTE PN WHERE PN.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
  AND PN.DELIVERYDATE = PACKINGNOTE.DELIVERYDATE
  and pn.status_id not in (select st.status_id from status st where st.statustype = 'PN' and st.code in (40,60))) TOTALSEQUENCE
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, PLANTDEPARTMENT,
       TRANSPORTARTICLE,STATUS, DELIVERYPOINT, ADDRESS, PLANT, ADDRESS PLANTADDRESS,
       BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU,
       PACKINGNOTE
       LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
       LEFT OUTER JOIN ROUTECONTROL ON (PACKINGNOTE.ROUTECONTROL_ID = ROUTECONTROL.ROUTECONTROL_ID )
       LEFT OUTER JOIN CONSIGNMENTNOTE ON (PACKINGNOTE.CONSIGNMENTNOTE_ID = CONSIGNMENTNOTE.CONSIGNMENTNOTE_ID)
       LEFT OUTER JOIN ROUTE ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID
       LEFT OUTER JOIN DEPOT ON DEPOT.DEPOT_ID=ROUTE.DEPOT_ID
       LEFT OUTER JOIN EMPLOYEE DRIVER ON DRIVER.EMPLOYEE_ID=ROUTE.DRIVER_ID,
       LANGUAGES
   WHERE
      PACKINGNOTE.TRANSPORTARTICLE_ID = TRANSPORTARTICLE.TRANSPORTARTICLE_ID
  AND PACKINGNOTE.STATUS_ID = STATUS.STATUS_ID
  AND STATUS.STATUSTYPE = 'PN'
  AND CAST(STATUS.CODE AS NUMERIC)<=20
  AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = ADDRESS.ADDRESS_ID
  AND PACKINGNOTE.PLANTDEPARTMENT_ID = PLANTDEPARTMENT.PLANTDEPARTMENT_ID
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  AND PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
  AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
  AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
  AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID

/
create or replace view V_PACKINGNOTE_BHO
 (PACKINGNOTEID, STATUSTYPE, DRIVINGDATE, DEPOTCODE, DEPOTDESCRIPTION, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERLEGALNAME, STREET, STREET2, CITY, STATE, ZIPCODE, COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, PACKINGDEPARTMENTCODE, PACKINGDEPARTMENTDESCRIPTION, TRANSPORTARTICLECODE, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENUMBER, EMPLOYEENAME
, PRODUCTIONDATE, DELIVERYDATE, STATUSCODE, STATUSDESCRIPTION, REMARK, PROCESSBUCODE, PROCESSBUDESCRIPTION, INVOICEBUCODE, INVOICEBUDESCRIPTION, ROUTENUMBER, ROUTEDESCRIPTION, LOADINGDOCK, CLEANRETURN, DEADLINE, CONSIGNMENTNOTENUMBER, SYSTEMUSER_ID, TIMESTAMP, CREATIONTIMESTAMP, ENDDATEFORUSE, DAYDESCRIPTION, WEEK, LANGUAGECODE, DRIVERNAME, BULKPUTUPONPACKINGNOTE, RETURN_ROUTENR, RETURNROTUE_DAY_DESC)
as SELECT PACKINGNOTE.PACKINGNOTE_ID packingnoteid,status.statustype,  routecontrol.drivingdate, depot.code depotcode, depot.description depotdescription,
 PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME customername, CUSTOMER.LEGALNAME customerlegalname,
 ADDRESS.STREET, ADDRESS.STREET2, ADDRESS.CITY, ADDRESS.STATE, ADDRESS.ZIPCODE, ADDRESS.COUNTY,
 DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION departmentdescription,
 DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION distributionpointdescription,
  DELIVERYPOINT.CODE deliverypointcode, DELIVERYPOINT.DESCRIPTION deliverypointdescription,
 PACKINGNOTE.SEQUENCENUMBER, PLANTDEPARTMENT.CODE packingdepartmentcode, PLANTDEPARTMENT.DESCRIPTION packingdepartmentdescription,
 TRANSPORTARTICLE.CODE transportarticlecode,
 (SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
 PACKINGNOTE.OCCUPANCY, EMPLOYEE.EMPLOYEENUMBER, EMPLOYEE.NAME employeename,
 PACKINGNOTE.PRODUCTIONDATE,
 PACKINGNOTE.DELIVERYDATE,
 STATUS.CODE statuscode,
 (SELECT DESCRIPTION FROM STATUS_DESC S WHERE S.STATUS_ID = PACKINGNOTE.STATUS_ID AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) STATUSDESCRIPTION,
 PACKINGNOTE.PNREMARK REMARK, PROCESSBU.CODE processbucode, PROCESSBU.DESCRIPTION processbudescription,
 INVOICEBU.CODE invoicebucode, INVOICEBU.DESCRIPTION invoicebudescription,
 ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION routedescription,ROUTE.LOADINGDOCK,
 PACKINGNOTE.CLEANRETURN,
 PACKINGNOTE.DEADLINE,
 CONSIGNMENTNOTE.CONSIGNMENTNOTENUMBER,
 PACKINGNOTE.SYSTEMUSER_ID, PACKINGNOTE.TIMESTAMP,PACKINGNOTE.CREATIONTIMESTAMP,
 packingnote.enddateforuse,
 (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,
  driver.name drivername
  , case when CUSTOMER.Delnoteforbulkputupitems = 0 then 'N' else  'Y' end BULKPUTUPONPACKINGNOTE
  , -1 RETURN_ROUTENR--RETURN ROUTE NUMBER
  , '' RETURNROTUE_DAY_DESC --RETURN ROUTE DRIVING DAY DESC
  FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, PLANTDEPARTMENT,
       TRANSPORTARTICLE,STATUS, DELIVERYPOINT, ADDRESS,
       BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU,
       PACKINGNOTE
       LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
       LEFT OUTER join routecontrol on (packingnote.routecontrol_id = routecontrol.routecontrol_id )
       LEFT OUTER JOIN CONSIGNMENTNOTE ON (PACKINGNOTE.CONSIGNMENTNOTE_ID = CONSIGNMENTNOTE.CONSIGNMENTNOTE_ID)
       LEFT OUTER JOIN (ROUTE left outer join depot on depot.depot_id=route.depot_id
                              left outer join employee driver on driver.employee_id=route.driver_id) ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_Id,
       LANGUAGES
 	WHERE
      PACKINGNOTE.TRANSPORTARTICLE_ID = TRANSPORTARTICLE.TRANSPORTARTICLE_ID
  and PACKINGNOTE.STATUS_ID = STATUS.STATUS_ID
  and status.statustype = 'PN' and cast(status.code as numeric) <= 20
  AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = ADDRESS.ADDRESS_ID
	AND PACKINGNOTE.PLANTDEPARTMENT_ID = PLANTDEPARTMENT.PLANTDEPARTMENT_ID
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
	AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  and PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
	AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
	AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND PACKINGNOTE.STOP_ID IS NULL --UNION CONDITION 1
UNION
SELECT PACKINGNOTE.PACKINGNOTE_ID packingnoteid,status.statustype,  routecontrol.drivingdate, depot.code depotcode, depot.description depotdescription,
 PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME customername, CUSTOMER.LEGALNAME customerlegalname,
 ADDRESS.STREET, ADDRESS.STREET2, ADDRESS.CITY, ADDRESS.STATE, ADDRESS.ZIPCODE, ADDRESS.COUNTY,
 DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION departmentdescription,
 DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION distributionpointdescription,
  DELIVERYPOINT.CODE deliverypointcode, DELIVERYPOINT.DESCRIPTION deliverypointdescription,
 PACKINGNOTE.SEQUENCENUMBER, PLANTDEPARTMENT.CODE packingdepartmentcode, PLANTDEPARTMENT.DESCRIPTION packingdepartmentdescription,
 TRANSPORTARTICLE.CODE transportarticlecode,
 (SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
 PACKINGNOTE.OCCUPANCY, EMPLOYEE.EMPLOYEENUMBER, EMPLOYEE.NAME employeename,
 PACKINGNOTE.PRODUCTIONDATE,
 PACKINGNOTE.DELIVERYDATE,
 STATUS.CODE statuscode,
 (SELECT DESCRIPTION FROM STATUS_DESC S WHERE S.STATUS_ID = PACKINGNOTE.STATUS_ID AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) STATUSDESCRIPTION,
 PACKINGNOTE.PNREMARK REMARK, PROCESSBU.CODE processbucode, PROCESSBU.DESCRIPTION processbudescription,
 INVOICEBU.CODE invoicebucode, INVOICEBU.DESCRIPTION invoicebudescription,
 ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION routedescription,ROUTE.LOADINGDOCK,
 PACKINGNOTE.CLEANRETURN,
 PACKINGNOTE.DEADLINE,
 CONSIGNMENTNOTE.CONSIGNMENTNOTENUMBER,
 PACKINGNOTE.SYSTEMUSER_ID, PACKINGNOTE.TIMESTAMP,PACKINGNOTE.CREATIONTIMESTAMP,
 packingnote.enddateforuse,
 (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,
  driver.name drivername
  , case when CUSTOMER.Delnoteforbulkputupitems = 0 then 'N' else 'Y' end BULKPUTUPONPACKINGNOTE
  , RET_ROUTE.ROUTENUMBER  RETURN_ROUTENR--RETURN ROUTE NUMBER
  , (SELECT DESCRIPTION FROM DAY_DESC WHERE DAY_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID AND DAY_DESC.DAY_ID = RET_ROUTE.DRIVINGDAY_ID) RETURNROTUE_DAY_DESC --RETURN ROUTE DRIVING DAY DESC
  FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, PLANTDEPARTMENT,
       TRANSPORTARTICLE,STATUS, DELIVERYPOINT, ADDRESS,
       BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU,
       PACKINGNOTE
       LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
       LEFT OUTER join routecontrol on (packingnote.routecontrol_id = routecontrol.routecontrol_id )
       LEFT OUTER JOIN CONSIGNMENTNOTE ON (PACKINGNOTE.CONSIGNMENTNOTE_ID = CONSIGNMENTNOTE.CONSIGNMENTNOTE_ID)
       LEFT OUTER JOIN (ROUTE left outer join depot on depot.depot_id=route.depot_id
                              left outer join employee driver on driver.employee_id=route.driver_id) ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_Id,
       STOP ST LEFT OUTER JOIN (ROUTESTOP RS LEFT OUTER JOIN ROUTE RET_ROUTE ON RET_ROUTE.ROUTE_ID = RS.RETURNROUTE_ID)
            ON RS.ROUTESTOP_ID = ST.ROUTESTOP_ID,
       LANGUAGES
 	WHERE
      PACKINGNOTE.TRANSPORTARTICLE_ID = TRANSPORTARTICLE.TRANSPORTARTICLE_ID
  and PACKINGNOTE.STATUS_ID = STATUS.STATUS_ID
  and status.statustype = 'PN' and cast(status.code as numeric) <= 20
  AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = ADDRESS.ADDRESS_ID
	AND PACKINGNOTE.PLANTDEPARTMENT_ID = PLANTDEPARTMENT.PLANTDEPARTMENT_ID
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
	AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  and PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
	AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
	AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND PACKINGNOTE.STOP_ID = ST.STOP_ID --UNION CONDITION 2

/
create or replace view V_PACKINGNOTE_BUT
 (PACKINGNOTEID, STATUSTYPE, DRIVINGDATE, DEPOTCODE, DEPOTDESCRIPTION, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERLEGALNAME, STREET, STREET2, CITY, STATE, ZIPCODE, COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, PACKINGDEPARTMENTCODE, PACKINGDEPARTMENTDESCRIPTION, TRANSPORTARTICLECODE, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENUMBER, EMPLOYEENAME
, PRODUCTIONDATE, DELIVERYDATE, STATUSCODE, STATUSDESCRIPTION, REMARK, PROCESSBUCODE, PROCESSBUDESCRIPTION, INVOICEBUCODE, INVOICEBUDESCRIPTION, ROUTENUMBER, ROUTEDESCRIPTION, LOADINGDOCK, CLEANRETURN, DEADLINE, CONSIGNMENTNOTENUMBER, SYSTEMUSER_ID, TIMESTAMP, CREATIONTIMESTAMP, ENDDATEFORUSE, DAYDESCRIPTION, WEEK, LANGUAGECODE, DRIVERNAME, DRIVERNUMBER, BULKPUTUPONPACKINGNOTE, YEAR, PACKINGNOTECOLUMNS, DELIVERGARMENTS, STOPNUMBER, PUTUPREPORTPERCUSTOMER, REFERENCENUMBER
)
as SELECT PACKINGNOTE.PACKINGNOTE_ID PACKINGNOTEID,STATUS.STATUSTYPE,  ROUTECONTROL.DRIVINGDATE, DEPOT.CODE DEPOTCODE, DEPOT.DESCRIPTION DEPOTDESCRIPTION,
 PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME CUSTOMERLEGALNAME,
 ADDRESS.STREET, ADDRESS.STREET2, ADDRESS.CITY, ADDRESS.STATE, ADDRESS.ZIPCODE, ADDRESS.COUNTY,
 DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
 DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
  DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
 PACKINGNOTE.SEQUENCENUMBER, PLANTDEPARTMENT.CODE PACKINGDEPARTMENTCODE, PLANTDEPARTMENT.DESCRIPTION PACKINGDEPARTMENTDESCRIPTION,
 TRANSPORTARTICLE.CODE TRANSPORTARTICLECODE,
 (SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
 PACKINGNOTE.OCCUPANCY, EMPLOYEE.EMPLOYEENUMBER, EMPLOYEE.NAME EMPLOYEENAME,
 PACKINGNOTE.PRODUCTIONDATE,
 PACKINGNOTE.DELIVERYDATE,
 STATUS.CODE STATUSCODE,
 (SELECT DESCRIPTION FROM STATUS_DESC S WHERE S.STATUS_ID = PACKINGNOTE.STATUS_ID AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) STATUSDESCRIPTION,
 PACKINGNOTE.PNREMARK REMARK, PROCESSBU.CODE PROCESSBUCODE, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
 INVOICEBU.CODE INVOICEBUCODE, INVOICEBU.DESCRIPTION INVOICEBUDESCRIPTION,
 ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION ROUTEDESCRIPTION,ROUTE.LOADINGDOCK,
 PACKINGNOTE.CLEANRETURN,
 PACKINGNOTE.DEADLINE,
 CONSIGNMENTNOTE.CONSIGNMENTNOTENUMBER,
 PACKINGNOTE.SYSTEMUSER_ID, PACKINGNOTE.TIMESTAMP,PACKINGNOTE.CREATIONTIMESTAMP,
 PACKINGNOTE.ENDDATEFORUSE,
 (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,
  DRIVER.NAME DRIVERNAME,
  DRIVER.EMPLOYEENUMBER DRIVERNUMBER
  , CASE WHEN CUSTOMER.DELNOTEFORBULKPUTUPITEMS = 0 THEN  'N' ELSE 'Y' END BULKPUTUPONPACKINGNOTE,
  PACKINGNOTE.YEAR YEAR
  , (SELECT SS.VALUE FROM SYSTEMSETTING SS WHERE SS.PLANT_ID = PROCESSBU.PLANT_ID
            AND SS.NAME = 'PACKINGNOTECOLUMNS') PACKINGNOTECOLUMNS
  , (SELECT COUNT(*) FROM CUSTOMERDELIVERYDAY CDD WHERE CUSTOMER.CUSTOMER_ID = CDD.CUSTOMER_ID
        AND CDD.DAY_ID = PACKINGNOTE.DAYNUMBER AND CDD.TYPEOFMERCHADISE =2) DELIVERGARMENTS,
        PACKINGNOTE.STOPNUMBER, ROUTE.PUTUPREPORTPERCUSTOMER
, (SELECT MAX(DV.REFERENCE) FROM DELIVERYVARIATIONS DV WHERE DV.PACKINGNOTE_ID = PACKINGNOTE.PACKINGNOTE_ID)	REFERENCENUMBER
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, PLANTDEPARTMENT,
       TRANSPORTARTICLE,STATUS, DELIVERYPOINT, ADDRESS,
       BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU,
       PACKINGNOTE
       LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
       LEFT OUTER JOIN ROUTECONTROL ON (PACKINGNOTE.ROUTECONTROL_ID = ROUTECONTROL.ROUTECONTROL_ID )
       LEFT OUTER JOIN CONSIGNMENTNOTE ON (PACKINGNOTE.CONSIGNMENTNOTE_ID = CONSIGNMENTNOTE.CONSIGNMENTNOTE_ID)
       LEFT OUTER JOIN ROUTE ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID
              LEFT OUTER JOIN DEPOT ON DEPOT.DEPOT_ID=ROUTE.DEPOT_ID
              LEFT OUTER JOIN EMPLOYEE DRIVER ON DRIVER.EMPLOYEE_ID=ROUTE.DRIVER_ID,
       LANGUAGES
 	WHERE
      PACKINGNOTE.TRANSPORTARTICLE_ID = TRANSPORTARTICLE.TRANSPORTARTICLE_ID
  AND PACKINGNOTE.STATUS_ID = STATUS.STATUS_ID
  AND STATUS.STATUSTYPE = 'PN'
  --AND (STATUS.CODE='10' OR STATUS.CODE ='20' OR STATUS.CODE ='5')
  AND CAST(STATUS.CODE AS NUMERIC)<=20
  AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = ADDRESS.ADDRESS_ID
	AND PACKINGNOTE.PLANTDEPARTMENT_ID = PLANTDEPARTMENT.PLANTDEPARTMENT_ID
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
	AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  AND PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
	AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
	AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID

/
create or replace view V_PACKINGNOTE_CIW
 (PACKINGNOTEID, STATUSTYPE, DRIVINGDATE, DEPOTCODE, DEPOTDESCRIPTION, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERLEGALNAME, STREET, STREET2, CITY, STATE, ZIPCODE, COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, PACKINGDEPARTMENTCODE, PACKINGDEPARTMENTDESCRIPTION, TRANSPORTARTICLECODE, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENUMBER, EMPLOYEENAME
, PRODUCTIONDATE, DELIVERYDATE, STATUSCODE, STATUSDESCRIPTION, REMARK, PROCESSBUCODE, PROCESSBUDESCRIPTION, INVOICEBUCODE, INVOICEBUDESCRIPTION, ROUTENUMBER, ROUTEDESCRIPTION, LOADINGDOCK, CLEANRETURN, DEADLINE, CONSIGNMENTNOTENUMBER, SYSTEMUSER_ID, TIMESTAMP, CREATIONTIMESTAMP, ENDDATEFORUSE, DAYDESCRIPTION, WEEK, LANGUAGECODE, DRIVERNAME, DRIVERNUMBER, BULKPUTUPONPACKINGNOTE, YEAR, PACKINGNOTECOLUMNS, DELIVERGARMENTS, STOPNUMBER, PUTUPREPORTPERCUSTOMER, ORIGIN
, UNSCHEDULEDPACKINGNOTE)
as SELECT PACKINGNOTE.PACKINGNOTE_ID PACKINGNOTEID,STATUS.STATUSTYPE,  ROUTECONTROL.DRIVINGDATE, DEPOT.CODE DEPOTCODE, DEPOT.DESCRIPTION DEPOTDESCRIPTION,
 PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME CUSTOMERLEGALNAME,
 ADDRESS.STREET, ADDRESS.STREET2, ADDRESS.CITY, ADDRESS.STATE, ADDRESS.ZIPCODE, ADDRESS.COUNTY,
 DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
 DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
  DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
 PACKINGNOTE.SEQUENCENUMBER, PLANTDEPARTMENT.CODE PACKINGDEPARTMENTCODE, PLANTDEPARTMENT.DESCRIPTION PACKINGDEPARTMENTDESCRIPTION,
 TRANSPORTARTICLE.CODE TRANSPORTARTICLECODE,
 (SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
 PACKINGNOTE.OCCUPANCY, EMPLOYEE.EMPLOYEENUMBER, EMPLOYEE.NAME EMPLOYEENAME,
 PACKINGNOTE.PRODUCTIONDATE,
 PACKINGNOTE.DELIVERYDATE,
 STATUS.CODE STATUSCODE,
 (SELECT DESCRIPTION FROM STATUS_DESC S WHERE S.STATUS_ID = PACKINGNOTE.STATUS_ID AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) STATUSDESCRIPTION,
 PACKINGNOTE.PNREMARK REMARK, PROCESSBU.CODE PROCESSBUCODE, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
 INVOICEBU.CODE INVOICEBUCODE, INVOICEBU.DESCRIPTION INVOICEBUDESCRIPTION,
 ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION ROUTEDESCRIPTION,ROUTE.LOADINGDOCK,
 PACKINGNOTE.CLEANRETURN,
 PACKINGNOTE.DEADLINE,
 CONSIGNMENTNOTE.CONSIGNMENTNOTENUMBER,
 PACKINGNOTE.SYSTEMUSER_ID, PACKINGNOTE.TIMESTAMP,PACKINGNOTE.CREATIONTIMESTAMP,
 PACKINGNOTE.ENDDATEFORUSE,
 (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,
  DRIVER.NAME DRIVERNAME,
  DRIVER.EMPLOYEENUMBER DRIVERNUMBER --TODO6844
  , CASE WHEN CUSTOMER.DELNOTEFORBULKPUTUPITEMS = 0 THEN  'N' ELSE 'Y' END BULKPUTUPONPACKINGNOTE,
  PACKINGNOTE.YEAR YEAR
  , (SELECT SS.VALUE FROM SYSTEMSETTING SS WHERE SS.PLANT_ID = PROCESSBU.PLANT_ID
            AND SS.NAME = 'PACKINGNOTECOLUMNS') PACKINGNOTECOLUMNS
  , (SELECT COUNT(*) FROM CUSTOMERDELIVERYDAY CDD WHERE CUSTOMER.CUSTOMER_ID = CDD.CUSTOMER_ID
        AND CDD.DAY_ID = PACKINGNOTE.DAYNUMBER AND CDD.TYPEOFMERCHADISE =2) DELIVERGARMENTS,
        PACKINGNOTE.STOPNUMBER, ROUTE.PUTUPREPORTPERCUSTOMER,
  PACKINGNOTE.ORIGIN
  , DECODE((select count(*)
              from stop st
             where st.routecontrol_id = packingnote.routecontrol_id
               and st.customer_link_id = (select dp.customer_id
                                            from deliverypoint dp
                                           where dp.deliverypoint_id = packingnote.deliverypoint_id)
               and st.stopnumber = packingnote.stopnumber
               and st.routestop_id is null),0,'N','Y') UNSCHEDULEDPACKINGNOTE
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, PLANTDEPARTMENT,
       TRANSPORTARTICLE,STATUS, DELIVERYPOINT, ADDRESS,
       BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU,
       PACKINGNOTE
       LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
       LEFT OUTER JOIN ROUTECONTROL ON (PACKINGNOTE.ROUTECONTROL_ID = ROUTECONTROL.ROUTECONTROL_ID )
       LEFT OUTER JOIN CONSIGNMENTNOTE ON (PACKINGNOTE.CONSIGNMENTNOTE_ID = CONSIGNMENTNOTE.CONSIGNMENTNOTE_ID)
       LEFT OUTER JOIN ROUTE ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID
              LEFT OUTER JOIN DEPOT ON DEPOT.DEPOT_ID=ROUTE.DEPOT_ID
              LEFT OUTER JOIN EMPLOYEE DRIVER ON DRIVER.EMPLOYEE_ID=ROUTE.DRIVER_ID,
       LANGUAGES
   WHERE
      PACKINGNOTE.TRANSPORTARTICLE_ID = TRANSPORTARTICLE.TRANSPORTARTICLE_ID
  AND PACKINGNOTE.STATUS_ID = STATUS.STATUS_ID
  AND STATUS.STATUSTYPE = 'PN'
  AND CAST(STATUS.CODE AS NUMERIC)<=20
  AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = ADDRESS.ADDRESS_ID
  AND PACKINGNOTE.PLANTDEPARTMENT_ID = PLANTDEPARTMENT.PLANTDEPARTMENT_ID
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  AND PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
  AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
  AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID

/
create or replace view V_PACKINGNOTE_DFD
 (PACKINGNOTEID, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, PLANTSTREET, PLANTSTREET2, PLANTCITY, PLANTSTATE, PLANTZIP, PLANTPHONE, PLANTFAX, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, PACKINGDEPARTMENTCODE, PACKINGDEPARTMENTDESCRIPTION, TRANSPORTARTICLECODE, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, PRODUCTIONDATE, DELIVERYDATE, REMARK, PROCESSBUCODE, PROCESSBUDESCRIPTION
, ROUTENUMBER, ROUTEDESCRIPTION, CLEANRETURN, DEADLINE, DAYDESCRIPTION, WEEK, LANGUAGECODE, BULKPUTUPONPACKINGNOTE, YEAR, PACKINGNOTECOLUMNS, DELIVERGARMENTS, STOPNUMBER, PUTUPREPORTPERCUSTOMER)
as SELECT PACKINGNOTE.PACKINGNOTE_ID PACKINGNOTEID,
       --STATUS.STATUSTYPE,
       --ROUTECONTROL.DRIVINGDATE,
       --DEPOT.CODE DEPOTCODE,
       --DEPOT.DESCRIPTION DEPOTDESCRIPTION,
       PACKINGNOTE.NOTENUMBER,
       CUSTOMER.CUSTOMERNUMBER,
       CUSTOMER.NAME CUSTOMERNAME,
       --DELIVERYADDRESS.STREET DELIVERYSTREET,
       --DELIVERYADDRESS.STREET2 DELIVERYSTREET2,
       --DELIVERYADDRESS.STATE DELIVERYSTATE,
       --DELIVERYADDRESS.ZIPCODE DELIVERYZIP,
       PLANTADDRESS.STREET PLANTSTREET,
       PLANTADDRESS.STREET2 PLANTSTREET2,
       PLANTADDRESS.CITY PLANTCITY,
       PLANTADDRESS.STATE PLANTSTATE,
       PLANTADDRESS.ZIPCODE PLANTZIP,
       PLANT.PHONENO PLANTPHONE,
       PLANT.FAXNO PLANTFAX,
       DEPARTMENT.DEPARTMENTNUMBER,
       DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
       DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER,
       DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
       DELIVERYPOINT.CODE DELIVERYPOINTCODE,
       DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
       PACKINGNOTE.SEQUENCENUMBER,
       PLANTDEPARTMENT.CODE PACKINGDEPARTMENTCODE,
       PLANTDEPARTMENT.DESCRIPTION PACKINGDEPARTMENTDESCRIPTION,
       TRANSPORTARTICLE.CODE TRANSPORTARTICLECODE,
       (SELECT DESCRIPTION
          FROM TRANSPORTARTICLE_DESC A
         WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID
           AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) TRANSPORTARTICLEDESCRIPTION,
       PACKINGNOTE.OCCUPANCY,
       --EMPLOYEE.EMPLOYEENUMBER,
       --EMPLOYEE.NAME EMPLOYEENAME,
       PACKINGNOTE.PRODUCTIONDATE,
       PACKINGNOTE.DELIVERYDATE,
       --STATUS.CODE STATUSCODE,
       --(SELECT DESCRIPTION FROM STATUS_DESC S WHERE S.STATUS_ID = PACKINGNOTE.STATUS_ID AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) STATUSDESCRIPTION,
       PACKINGNOTE.PNREMARK REMARK,
       PROCESSBU.CODE PROCESSBUCODE,
       PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
       --INVOICEBU.CODE INVOICEBUCODE,
       --INVOICEBU.DESCRIPTION INVOICEBUDESCRIPTION,
       ROUTE.ROUTENUMBER,
       ROUTE.DESCRIPTION ROUTEDESCRIPTION,
       --ROUTE.LOADINGDOCK,
       --CONTAINERTYPE.CODE CONTAINERTYPECODE,
       PACKINGNOTE.CLEANRETURN,
       PACKINGNOTE.DEADLINE,
       --WEIGHINGCATEGORY.CODE WEIGHINGCATEGORYCODE,
       -- (SELECT B.DESCRIPTION  FROM WEIGHINGCATEGORY_DESC B
       --        WHERE B.WEIGHINGCATEGORY_ID = PACKINGNOTE.WEIGHINGCATEGORY_ID
       --        AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID
       --        ) WEIGHINGCATEGORYDESCRIPTION,
       --PACKINGNOTE.TAREWEIGHT, PACKINGNOTE.GROSSWEIGHT, PACKINGNOTE.WEIGHTDECIMALS,
       --(PACKINGNOTE.GROSSWEIGHT - PACKINGNOTE.TAREWEIGHT) NETWEIGHT,
       --PACKINGNOTE.SYSTEMUSER_ID,
       --PACKINGNOTE.TIMESTAMP,
       (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,
       --DRIVER.NAME DRIVERNAME,
       --DRIVER.EMPLOYEENUMBER DRIVERNUMBER, --TODO6844
       --, RETURNROUTE.ROUTENUMBER RETURNROUTENUMBER,
       --  (SELECT DESCRIPTION FROM DAY_DESC WHERE DAY_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID AND DAY_DESC.DAY_ID = DAY.DAYNUMBER) RETURNDAYDESCRIPTION,
       --PACKINGNOTE.WEIGHINGSEQUENCENR
       CASE
         WHEN CUSTOMER.DELNOTEFORBULKPUTUPITEMS = 0 THEN 'N'
         ELSE 'Y'
        END BULKPUTUPONPACKINGNOTE,
       PACKINGNOTE.YEAR YEAR,
       (SELECT rpad(trim(SS.VALUE), 1)
          FROM SYSTEMSETTING SS
         WHERE SS.PLANT_ID = PROCESSBU.PLANT_ID
           AND SS.NAME = 'PACKINGNOTECOLUMNS') PACKINGNOTECOLUMNS,
       (SELECT COUNT(*)
          FROM CUSTOMERDELIVERYDAY CDD
         WHERE CUSTOMER.CUSTOMER_ID = CDD.CUSTOMER_ID
           AND CDD.DAY_ID = PACKINGNOTE.DAYNUMBER
           AND CDD.TYPEOFMERCHADISE = 2) DELIVERGARMENTS,
       PACKINGNOTE.STOPNUMBER,
       ROUTE.PUTUPREPORTPERCUSTOMER
  FROM CUSTOMER,
       DEPARTMENT,
       DISTRIBUTIONPOINT,
       PLANTDEPARTMENT,
       TRANSPORTARTICLE,
       STATUS,
       DELIVERYPOINT,
       --ADDRESS DELIVERYADDRESS,
       BUSINESSUNIT      PROCESSBU,
       PLANT,
       LANGUAGES,
       ADDRESS PLANTADDRESS,
       --BUSINESSUNIT      INVOICEBU,
       --ROUTESTOP, ROUTE RETURNROUTE,DAY,
       PACKINGNOTE
  LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
  --LEFT OUTER JOIN CONTAINERTYPE ON (PACKINGNOTE.CONTAINERTYPE_ID = CONTAINERTYPE.CONTAINERTYPE_ID)
  LEFT OUTER JOIN ROUTECONTROL ON (PACKINGNOTE.ROUTECONTROL_ID = ROUTECONTROL.ROUTECONTROL_ID)
  --LEFT OUTER JOIN WEIGHINGCATEGORY ON (PACKINGNOTE.WEIGHINGCATEGORY_ID = WEIGHINGCATEGORY.WEIGHINGCATEGORY_ID),
  LEFT OUTER JOIN ROUTE ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID
  --LEFT OUTER JOIN DEPOT ON DEPOT.DEPOT_ID = ROUTE.DEPOT_ID
  --LEFT OUTER JOIN EMPLOYEE DRIVER ON DRIVER.EMPLOYEE_ID = ROUTE.DRIVER_ID
 WHERE PACKINGNOTE.TRANSPORTARTICLE_ID = TRANSPORTARTICLE.TRANSPORTARTICLE_ID
   AND PACKINGNOTE.STATUS_ID = STATUS.STATUS_ID
   AND STATUS.STATUSTYPE = 'PN'
      --AND (STATUS.CODE='10' OR STATUS.CODE ='20' OR STATUS.CODE ='5')
   AND CAST(STATUS.CODE AS NUMERIC) <= 20
   AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
   --AND DELIVERYPOINT.DELIVERYADDRESS_ID = DELIVERYADDRESS.ADDRESS_ID
   AND PACKINGNOTE.PLANTDEPARTMENT_ID = PLANTDEPARTMENT.PLANTDEPARTMENT_ID
   AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
   AND PROCESSBU.PLANT_ID = PLANT.PLANT_ID
   AND PLANT.ADDRESS_ID = PLANTADDRESS.ADDRESS_ID
   --AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
   AND PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
   AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
   AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
   --AND PACKINGNOTE.ROUTE_ID IS NOT NULL
   --AND PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID
   --AND ROUTE.ROUTE_ID= ROUTESTOP.ROUTE_ID
   --AND ROUTESTOP.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
   --AND ROUTESTOP.STOPNUMBER = PACKINGNOTE.STOPNUMBER
   --AND ROUTESTOP.RETURNROUTE_ID = RETURNROUTE.ROUTE_ID
   --AND RETURNROUTE.DRIVINGDAY_ID = DAY.DAY_ID

/
create or replace view V_PACKINGNOTE_LLG
 (NOTENUMBER, DELIVERYDATE, PACKINGNOTE_ID, REMARK, CUSTOMER_ID, CUSTOMERNUMBER, SEARCHNAME, CUSTOMERNAME, BUCODE, BUDESCRIPTION, ROUTENUMBER, ROUTEDESCRIPTION, LANGUAGECODE, DISTRIBUTIONPOINTDESCRIPTION, PRIMARYID, DAYNUMBER, NOOFDELIVERYDAYS, TRANSPORTARTICLEDESCRIPTION)
as SELECT
PACKINGNOTE.NOTENUMBER,
PACKINGNOTE.DELIVERYDATE,
PACKINGNOTE.PACKINGNOTE_ID,
packingnote.remark,
CUSTOMER.CUSTOMER_ID,
CUSTOMER.CUSTOMERNUMBER, CUSTOMER.SEARCHNAME,CUSTOMER.NAME CUSTOMERNAME,
PROCESSBU.CODE BUCODE,
PROCESSBU.DESCRIPTION BUDESCRIPTION,
ROUTE.ROUTENUMBER,
ROUTE.DESCRIPTION ROUTEDESCRIPTION,
LANGUAGES.CODE LANGUAGECODE,
DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
bt.primaryid,
packingnote.daynumber,
(select count(1) from customerdeliveryday cdd where cdd.customer_id = customer.customer_id) NOOFDELIVERYDAYS,
(SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION
FROM  CUSTOMER,
        DEPARTMENT, DISTRIBUTIONPOINT,
        BUSINESSUNIT PROCESSBU,
        PACKINGNOTE
        LEFT OUTER JOIN ROUTE
        ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID,
        LANGUAGES,
        bagtag bt
  WHERE bt.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
  AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
  AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  and packingnote.packingnote_id = bt.packingnote_id

/
create or replace view V_PACKINGNOTE_LST
 (PACKINGNOTEID, STATUSTYPE, DRIVINGDATE, DEPOTCODE, DEPOTDESCRIPTION, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERLEGALNAME, STREET, STREET2, CITY, STATE, ZIPCODE, COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, PACKINGDEPARTMENTCODE, PACKINGDEPARTMENTDESCRIPTION, TRANSPORTARTICLECODE, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENUMBER, EMPLOYEENAME
, PRODUCTIONDATE, DELIVERYDATE, STATUSCODE, STATUSDESCRIPTION, REMARK, PROCESSBUCODE, PROCESSBUDESCRIPTION, INVOICEBUCODE, INVOICEBUDESCRIPTION, ROUTENUMBER, ROUTEDESCRIPTION, LOADINGDOCK, CLEANRETURN, DEADLINE, CONSIGNMENTNOTENUMBER, SYSTEMUSER_ID, TIMESTAMP, CREATIONTIMESTAMP, ENDDATEFORUSE, DAYDESCRIPTION, WEEK, LANGUAGECODE, DRIVERNAME, BULKPUTUPONPACKINGNOTE, YEAR, PACKINGNOTECOLUMNS, DELIVERGARMENTS, STOPNUMBER, PUTUPREPORTPERCUSTOMER)
as SELECT PACKINGNOTE.PACKINGNOTE_ID PACKINGNOTEID,STATUS.STATUSTYPE,  ROUTECONTROL.DRIVINGDATE, DEPOT.CODE DEPOTCODE, DEPOT.DESCRIPTION DEPOTDESCRIPTION,
 PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME CUSTOMERLEGALNAME,
 ADDRESS.STREET, ADDRESS.STREET2, ADDRESS.CITY, ADDRESS.STATE, ADDRESS.ZIPCODE, ADDRESS.COUNTY,
 DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
 DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
  DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
 PACKINGNOTE.SEQUENCENUMBER, PLANTDEPARTMENT.CODE PACKINGDEPARTMENTCODE, PLANTDEPARTMENT.DESCRIPTION PACKINGDEPARTMENTDESCRIPTION,
 TRANSPORTARTICLE.CODE TRANSPORTARTICLECODE,
 (SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
 PACKINGNOTE.OCCUPANCY, EMPLOYEE.EMPLOYEENUMBER, EMPLOYEE.NAME EMPLOYEENAME,
 PACKINGNOTE.PRODUCTIONDATE,
 PACKINGNOTE.DELIVERYDATE,
 STATUS.CODE STATUSCODE,
 (SELECT DESCRIPTION FROM STATUS_DESC S WHERE S.STATUS_ID = PACKINGNOTE.STATUS_ID AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) STATUSDESCRIPTION,
 PACKINGNOTE.PNREMARK REMARK, PROCESSBU.CODE PROCESSBUCODE, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
 INVOICEBU.CODE INVOICEBUCODE, INVOICEBU.DESCRIPTION INVOICEBUDESCRIPTION,
 ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION ROUTEDESCRIPTION,ROUTE.LOADINGDOCK,
 PACKINGNOTE.CLEANRETURN,
 PACKINGNOTE.DEADLINE,
 CONSIGNMENTNOTE.CONSIGNMENTNOTENUMBER,
 PACKINGNOTE.SYSTEMUSER_ID, PACKINGNOTE.TIMESTAMP,PACKINGNOTE.CREATIONTIMESTAMP,
 PACKINGNOTE.ENDDATEFORUSE,
 (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,
  DRIVER.NAME DRIVERNAME--,
  , CASE WHEN CUSTOMER.DELNOTEFORBULKPUTUPITEMS = 0 THEN  'N' ELSE 'Y' END BULKPUTUPONPACKINGNOTE,
  PACKINGNOTE.YEAR YEAR
  , (SELECT SS.VALUE FROM SYSTEMSETTING SS WHERE SS.PLANT_ID = PROCESSBU.PLANT_ID
            AND SS.NAME = 'PACKINGNOTECOLUMNS') PACKINGNOTECOLUMNS
  , (SELECT COUNT(*) FROM CUSTOMERDELIVERYDAY CDD WHERE CUSTOMER.CUSTOMER_ID = CDD.CUSTOMER_ID
        AND CDD.DAY_ID = PACKINGNOTE.DAYNUMBER AND CDD.TYPEOFMERCHADISE =2) DELIVERGARMENTS,
        PACKINGNOTE.STOPNUMBER, ROUTE.PUTUPREPORTPERCUSTOMER
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, PLANTDEPARTMENT,
       TRANSPORTARTICLE,STATUS, DELIVERYPOINT, ADDRESS,
       BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU,
       PACKINGNOTE
       LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
       LEFT OUTER JOIN ROUTECONTROL ON (PACKINGNOTE.ROUTECONTROL_ID = ROUTECONTROL.ROUTECONTROL_ID )
       LEFT OUTER JOIN CONSIGNMENTNOTE ON (PACKINGNOTE.CONSIGNMENTNOTE_ID = CONSIGNMENTNOTE.CONSIGNMENTNOTE_ID)
       LEFT OUTER JOIN ROUTE ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID
              LEFT OUTER JOIN DEPOT ON DEPOT.DEPOT_ID=ROUTE.DEPOT_ID
              LEFT OUTER JOIN EMPLOYEE DRIVER ON DRIVER.EMPLOYEE_ID=ROUTE.DRIVER_ID,
       LANGUAGES
 	WHERE
      PACKINGNOTE.TRANSPORTARTICLE_ID = TRANSPORTARTICLE.TRANSPORTARTICLE_ID
  AND PACKINGNOTE.STATUS_ID = STATUS.STATUS_ID
  AND STATUS.STATUSTYPE = 'PN'
  --AND (STATUS.CODE='10' OR STATUS.CODE ='20' OR STATUS.CODE ='5')
--  AND CAST(STATUS.CODE AS NUMERIC)<=20
  AND CAST(STATUS.CODE AS NUMERIC)<=30
  AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = ADDRESS.ADDRESS_ID
	AND PACKINGNOTE.PLANTDEPARTMENT_ID = PLANTDEPARTMENT.PLANTDEPARTMENT_ID
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
	AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  AND PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
	AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
	AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID

/
create or replace view V_PACKINGNOTE_LTS
 (PACKINGDAY_ID, PACKINGNOTEID, STATUSTYPE, DRIVINGDATE, DEPOTCODE, DEPOTDESCRIPTION, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERLEGALNAME, STREET, STREET2, CITY, STATE, ZIPCODE, COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, PACKINGDEPARTMENTCODE, PACKINGDEPARTMENTDESCRIPTION, TRANSPORTARTICLECODE, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENUMBER
, EMPLOYEENAME, PRODUCTIONDATE, DELIVERYDATE, STATUSCODE, STATUSDESCRIPTION, REMARK, PROCESSBUCODE, PROCESSBUDESCRIPTION, INVOICEBUCODE, INVOICEBUDESCRIPTION, ROUTENUMBER, ROUTEDESCRIPTION, LOADINGDOCK, DRIVINGDAYDESC, CLEANRETURN, DEADLINE, CONSIGNMENTNOTENUMBER, SYSTEMUSER_ID, TIMESTAMP, CREATIONTIMESTAMP, ENDDATEFORUSE, DAYDESCRIPTION, WEEK, DRIVERNAME, DRIVERNUMBER, BULKPUTUPONPACKINGNOTE, YEAR, PACKINGNOTECOLUMNS, DELIVERGARMENTS, STOPNUMBER, PUTUPREPORTPERCUSTOMER
, CUSTOMERLANGUAGE, DEADLINEASNUMERIC, LABELCOLOR, INTERNALREMARKFORTRANSPLABEL, TRANSPLABINTERNALREMARKENDDATE, EXTERNALREMARKFORTRANSPLABEL, TRANSPLABEXTERNALREMARKENDDATE, NOOFTRANSPORTLABELS, USAGEDAYNUMBER, USAGEDAYDESC)
as SELECT ROUTE.PACKINGDAY_ID, PACKINGNOTE.PACKINGNOTE_ID PACKINGNOTEID,STATUS.STATUSTYPE,  ROUTECONTROL.DRIVINGDATE, DEPOT.CODE DEPOTCODE, DEPOT.DESCRIPTION DEPOTDESCRIPTION,
 PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME CUSTOMERLEGALNAME,
 ADDRESS.STREET, ADDRESS.STREET2, ADDRESS.CITY, ADDRESS.STATE, ADDRESS.ZIPCODE, ADDRESS.COUNTY,
 DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
 DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
  DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
 PACKINGNOTE.SEQUENCENUMBER, PLANTDEPARTMENT.CODE PACKINGDEPARTMENTCODE, PLANTDEPARTMENT.DESCRIPTION PACKINGDEPARTMENTDESCRIPTION,
 TRANSPORTARTICLE.CODE TRANSPORTARTICLECODE,
 (SELECT A.DESCRIPTION FROM TRANSPORTARTICLE_DESC  A WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID AND A.LANGUAGE_ID = CUSTOMER.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
 PACKINGNOTE.OCCUPANCY, EMPLOYEE.EMPLOYEENUMBER, EMPLOYEE.NAME EMPLOYEENAME,
 PACKINGNOTE.PRODUCTIONDATE,
 PACKINGNOTE.DELIVERYDATE,
 STATUS.CODE STATUSCODE,
 (SELECT S.DESCRIPTION FROM STATUS_DESC S WHERE S.STATUS_ID = PACKINGNOTE.STATUS_ID AND S.LANGUAGE_ID = CUSTOMER.LANGUAGE_ID ) STATUSDESCRIPTION,
 PACKINGNOTE.PNREMARK REMARK, PROCESSBU.CODE PROCESSBUCODE, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
 INVOICEBU.CODE INVOICEBUCODE, INVOICEBU.DESCRIPTION INVOICEBUDESCRIPTION,
 ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION ROUTEDESCRIPTION,ROUTE.LOADINGDOCK,
 (select dd.description from day_desc dd where dd.day_id = route.drivingday_id and dd.language_id = customer.language_id) drivingdaydesc,
 PACKINGNOTE.CLEANRETURN,
 PACKINGNOTE.DEADLINE,
 CONSIGNMENTNOTE.CONSIGNMENTNOTENUMBER,
 PACKINGNOTE.SYSTEMUSER_ID, PACKINGNOTE.TIMESTAMP,PACKINGNOTE.CREATIONTIMESTAMP,
 PACKINGNOTE.ENDDATEFORUSE,
 (SELECT UPPER(DD.DESCRIPTION) FROM DAY_DESC DD WHERE DD.LANGUAGE_ID = CUSTOMER.LANGUAGE_ID AND DD.DAY_ID = PACKINGNOTE.DAYNUMBER) DAYDESCRIPTION
,  CAST(PACKINGNOTE.WEEK AS VARCHAR2(2)) WEEK,-- LANGUAGES.CODE LANGUAGECODE,
  DRIVER.NAME DRIVERNAME,
  DRIVER.EMPLOYEENUMBER DRIVERNUMBER
  , CASE WHEN CUSTOMER.DELNOTEFORBULKPUTUPITEMS = 0 THEN  'N' ELSE 'Y' END BULKPUTUPONPACKINGNOTE,
  PACKINGNOTE.YEAR YEAR
  , (SELECT SS.VALUE FROM SYSTEMSETTING SS WHERE SS.PLANT_ID = PROCESSBU.PLANT_ID
            AND SS.NAME = 'PACKINGNOTECOLUMNS') PACKINGNOTECOLUMNS
  , (SELECT COUNT(*) FROM CUSTOMERDELIVERYDAY CDD WHERE CUSTOMER.CUSTOMER_ID = CDD.CUSTOMER_ID
        AND CDD.DAY_ID = PACKINGNOTE.DAYNUMBER AND CDD.TYPEOFMERCHADISE =2) DELIVERGARMENTS,
        PACKINGNOTE.STOPNUMBER, ROUTE.PUTUPREPORTPERCUSTOMER
, (SELECT CLAN.CODE FROM LANGUAGES CLAN WHERE CUSTOMER.LANGUAGE_ID = CLAN.LANGUAGE_ID) CUSTOMERLANGUAGE
, GETTIMEASNUMERIC(ROUTE.PACKINGDEADLINE) DEADLINEASNUMERIC
, DISTRIBUTIONPOINT.LABELCOLOR, DISTRIBUTIONPOINT.INTERNALREMARKFORTRANSPLABEL
, DISTRIBUTIONPOINT.TRANSPLABINTERNALREMARKENDDATE, DISTRIBUTIONPOINT.EXTERNALREMARKFORTRANSPLABEL
, DISTRIBUTIONPOINT.TRANSPLABEXTERNALREMARKENDDATE, DISTRIBUTIONPOINT.NOOFTRANSPORTLABELS
, (SELECT DUD.USAGEDAY_ID FROM DEPARTMENTUSAGEDAY DUD WHERE DUD.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID AND DUD.DAY_ID = ROUTE.DRIVINGDAY_ID) USAGEDAYNUMBER
, (SELECT DD.DESCRIPTION FROM DEPARTMENTUSAGEDAY DUD, DAY_DESC DD WHERE DUD.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID AND DUD.USAGEDAY_ID = DD.DAY_ID AND DUD.DAY_ID = ROUTE.DRIVINGDAY_ID AND DD.LANGUAGE_ID = CUSTOMER.LANGUAGE_ID) USAGEDAYDESC
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, PLANTDEPARTMENT,
       TRANSPORTARTICLE,STATUS, DELIVERYPOINT, ADDRESS,
       BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU,
       PACKINGNOTE
       LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
       LEFT OUTER JOIN ROUTECONTROL ON (PACKINGNOTE.ROUTECONTROL_ID = ROUTECONTROL.ROUTECONTROL_ID )
       LEFT OUTER JOIN CONSIGNMENTNOTE ON (PACKINGNOTE.CONSIGNMENTNOTE_ID = CONSIGNMENTNOTE.CONSIGNMENTNOTE_ID)
       LEFT OUTER JOIN ROUTE ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID
              LEFT OUTER JOIN DEPOT ON DEPOT.DEPOT_ID=ROUTE.DEPOT_ID
              LEFT OUTER JOIN EMPLOYEE DRIVER ON DRIVER.EMPLOYEE_ID=ROUTE.DRIVER_ID--,       LANGUAGES
   WHERE
      PACKINGNOTE.TRANSPORTARTICLE_ID = TRANSPORTARTICLE.TRANSPORTARTICLE_ID
  AND PACKINGNOTE.STATUS_ID = STATUS.STATUS_ID
  AND STATUS.STATUSTYPE = 'PN'
  AND CAST(STATUS.CODE AS NUMERIC)<=20
  AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = ADDRESS.ADDRESS_ID
  AND PACKINGNOTE.PLANTDEPARTMENT_ID = PLANTDEPARTMENT.PLANTDEPARTMENT_ID
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  AND PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
  AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
  AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID

/
create or replace view V_PACKINGNOTE_MID
 (PACKINGNOTEID, STATUSTYPE, DRIVINGDATE, DEPOTCODE, DEPOTDESCRIPTION, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERLEGALNAME, CUSTOMERSTREET, CUSTOMERSTREET2, CUSTOMERZIP, CUSTOMERCITY, CUSTOMERSTATE, CUSTOMERCOUNTY, CUSTCOUNTRY, CUSTCOUNTRY_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, LEGACYDEPARTMENTCODE, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, PACKINGDEPARTMENTCODE, PACKINGDEPARTMENTDESCRIPTION
, TRANSPORTARTICLECODE, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENUMBER, EMPLOYEENAME, PRODUCTIONDATE, DELIVERYDATE, STATUSCODE, STATUSDESCRIPTION, REMARK, PROCESSBUCODE, PROCESSBUDESCRIPTION, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, PLANTCOUNTRY_CODE, PLANTCOUNTRY_DESC, INVOICEBUCODE, INVOICEBUDESCRIPTION, ROUTENUMBER, ROUTEDESCRIPTION, LOADINGDOCK, CLEANRETURN, DEADLINE
, DEADLINEASNUMERIC, CONSIGNMENTNOTENUMBER, SYSTEMUSER_ID, TIMESTAMP, CREATIONTIMESTAMP, ENDDATEFORUSE, DAYDESCRIPTION, WEEK, LANGUAGECODE, DRIVERNAME, DRIVERNUMBER, BULKPUTUPONPACKINGNOTE, YEAR, PACKINGNOTECOLUMNS, DELIVERGARMENTS, STOPNUMBER, PUTUPREPORTPERCUSTOMER, EXTRANAME1, LAYOUTCODE)
as SELECT PACKINGNOTE.PACKINGNOTE_ID PACKINGNOTEID,STATUS.STATUSTYPE,  ROUTECONTROL.DRIVINGDATE, DEPOT.CODE DEPOTCODE, DEPOT.DESCRIPTION DEPOTDESCRIPTION,
 PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME CUSTOMERLEGALNAME,
 ADDRESS.street CUSTOMERSTREET, ADDRESS.street2 CUSTOMERSTREET2, ADDRESS.zipcode CUSTOMERZIP, ADDRESS.city CUSTOMERCITY,
 ADDRESS.State CUSTOMERSTATE,ADDRESS.COUNTY CUSTOMERCOUNTY, C1.CODE CUSTCOUNTRY, C1.DESCRIPTION CUSTCOUNTRY_DESC,
 DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION, DEPARTMENT.Legacydepartmentcode,
 DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
 DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
 PACKINGNOTE.SEQUENCENUMBER, PLANTDEPARTMENT.CODE PACKINGDEPARTMENTCODE, PLANTDEPARTMENT.DESCRIPTION PACKINGDEPARTMENTDESCRIPTION,
 TRANSPORTARTICLE.CODE TRANSPORTARTICLECODE,
 (SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
 PACKINGNOTE.OCCUPANCY, EMPLOYEE.EMPLOYEENUMBER, EMPLOYEE.NAME EMPLOYEENAME,
 PACKINGNOTE.PRODUCTIONDATE,
 PACKINGNOTE.DELIVERYDATE,
 STATUS.CODE STATUSCODE,
 (SELECT DESCRIPTION FROM STATUS_DESC S WHERE S.STATUS_ID = PACKINGNOTE.STATUS_ID AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) STATUSDESCRIPTION,
 PACKINGNOTE.PNREMARK REMARK, PROCESSBU.CODE PROCESSBUCODE, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
 PLANT.CODE PLANTCODE, PLANT.Name PLANTName, PLANT.WEBSITE PLANTWEBSITE, PLANT.Email PLANTEmail,
 PLANTADDRESS.STREET PLANTSTREET, PLANTADDRESS.ZIPCODE PLANTZIPCODE,
 PLANTADDRESS.CITY PLANTCITY, PLANTADDRESS.STATE PLANTSTATE, PLANT.phoneno PLANTPHONENO, PLANT.faxno PLANTFAXNO,
 C2.CODE PLANTCOUNTRY_CODE, C2.DESCRIPTION PLANTCOUNTRY_DESC,
 INVOICEBU.CODE INVOICEBUCODE, INVOICEBU.DESCRIPTION INVOICEBUDESCRIPTION,
 ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION ROUTEDESCRIPTION,ROUTE.LOADINGDOCK,
 PACKINGNOTE.CLEANRETURN,
 PACKINGNOTE.DEADLINE,
 GETTIMEASNUMERIC(PACKINGNOTE.DEADLINE) DEADLINEASNUMERIC,
 CONSIGNMENTNOTE.CONSIGNMENTNOTENUMBER,
 PACKINGNOTE.SYSTEMUSER_ID, PACKINGNOTE.TIMESTAMP,PACKINGNOTE.CREATIONTIMESTAMP,
 PACKINGNOTE.ENDDATEFORUSE,
 (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,
 DRIVER.NAME DRIVERNAME,
 DRIVER.EMPLOYEENUMBER DRIVERNUMBER
 , CASE WHEN CUSTOMER.DELNOTEFORBULKPUTUPITEMS = 0 THEN  'N' ELSE 'Y' END BULKPUTUPONPACKINGNOTE,
 PACKINGNOTE.YEAR YEAR
 , (SELECT SS.VALUE FROM SYSTEMSETTING SS WHERE SS.PLANT_ID = PROCESSBU.PLANT_ID
           AND SS.NAME = 'PACKINGNOTECOLUMNS') PACKINGNOTECOLUMNS
 , (SELECT COUNT(*) FROM CUSTOMERDELIVERYDAY CDD WHERE CUSTOMER.CUSTOMER_ID = CDD.CUSTOMER_ID
        AND CDD.DAY_ID = PACKINGNOTE.DAYNUMBER AND CDD.TYPEOFMERCHADISE =2) DELIVERGARMENTS,
        PACKINGNOTE.STOPNUMBER, ROUTE.PUTUPREPORTPERCUSTOMER,
 CUSTOMER.EXTRANAME1,
 (select fly.code from formlayout fly where fly.formlayout_id = CUSTOMER.deliverynotelayout_id) layoutcode
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, PLANTDEPARTMENT, PLANT, ADDRESS PLANTADDRESS,
       TRANSPORTARTICLE,STATUS, DELIVERYPOINT, ADDRESS, COUNTRY C1, COUNTRY C2,
       BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU,
       PACKINGNOTE
       LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
       LEFT OUTER JOIN ROUTECONTROL ON (PACKINGNOTE.ROUTECONTROL_ID = ROUTECONTROL.ROUTECONTROL_ID )
       LEFT OUTER JOIN CONSIGNMENTNOTE ON (PACKINGNOTE.CONSIGNMENTNOTE_ID = CONSIGNMENTNOTE.CONSIGNMENTNOTE_ID)
       LEFT OUTER JOIN ROUTE ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID
              LEFT OUTER JOIN DEPOT ON DEPOT.DEPOT_ID=ROUTE.DEPOT_ID
              LEFT OUTER JOIN EMPLOYEE DRIVER ON DRIVER.EMPLOYEE_ID=ROUTE.DRIVER_ID,
       LANGUAGES
 	WHERE
      PACKINGNOTE.TRANSPORTARTICLE_ID = TRANSPORTARTICLE.TRANSPORTARTICLE_ID
  AND PACKINGNOTE.STATUS_ID = STATUS.STATUS_ID
  AND STATUS.STATUSTYPE = 'PN'  --AND (STATUS.CODE='10' OR STATUS.CODE ='20' OR STATUS.CODE ='5')
  AND CAST(STATUS.CODE AS NUMERIC)<=20
  AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = ADDRESS.ADDRESS_ID
	AND PACKINGNOTE.PLANTDEPARTMENT_ID = PLANTDEPARTMENT.PLANTDEPARTMENT_ID
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
	AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  AND PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
	AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
	AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_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

/
create or replace view V_PACKINGNOTE_NIX
 (PACKINGNOTEID, STATUSTYPE, DRIVINGDATE, DEPOTCODE, DEPOTDESCRIPTION, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERLEGALNAME, STREET, STREET2, CITY, STATE, ZIPCODE, COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, PACKINGDEPARTMENTCODE, PACKINGDEPARTMENTDESCRIPTION, TRANSPORTARTICLECODE, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENUMBER, EMPLOYEENAME
, PRODUCTIONDATE, DELIVERYDATE, STATUSCODE, STATUSDESCRIPTION, REMARK, PROCESSBUCODE, PROCESSBUDESCRIPTION, INVOICEBUCODE, INVOICEBUDESCRIPTION, ROUTENUMBER, ROUTEDESCRIPTION, LOADINGDOCK, CLEANRETURN, DEADLINE, CONSIGNMENTNOTENUMBER, SYSTEMUSER_ID, TIMESTAMP, CREATIONTIMESTAMP, ENDDATEFORUSE, DAYDESCRIPTION, WEEK, LANGUAGECODE, DRIVERNAME, DRIVERNUMBER, BULKPUTUPONPACKINGNOTE, YEAR, PACKINGNOTECOLUMNS, DELIVERGARMENTS, STOPNUMBER, PUTUPREPORTPERCUSTOMER)
as SELECT PACKINGNOTE.PACKINGNOTE_ID PACKINGNOTEID,STATUS.STATUSTYPE,  ROUTECONTROL.DRIVINGDATE, DEPOT.CODE DEPOTCODE, DEPOT.DESCRIPTION DEPOTDESCRIPTION,
 PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME CUSTOMERLEGALNAME,
 ADDRESS.STREET, ADDRESS.STREET2, ADDRESS.CITY, ADDRESS.STATE, ADDRESS.ZIPCODE, ADDRESS.COUNTY,
 DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
 DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
  DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
 PACKINGNOTE.SEQUENCENUMBER, PLANTDEPARTMENT.CODE PACKINGDEPARTMENTCODE, PLANTDEPARTMENT.DESCRIPTION PACKINGDEPARTMENTDESCRIPTION,
 TRANSPORTARTICLE.CODE TRANSPORTARTICLECODE,
 (SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
 PACKINGNOTE.OCCUPANCY, EMPLOYEE.EMPLOYEENUMBER, EMPLOYEE.NAME EMPLOYEENAME,
 PACKINGNOTE.PRODUCTIONDATE,
 PACKINGNOTE.DELIVERYDATE,
 STATUS.CODE STATUSCODE,
 (SELECT DESCRIPTION FROM STATUS_DESC S WHERE S.STATUS_ID = PACKINGNOTE.STATUS_ID AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) STATUSDESCRIPTION,
 PACKINGNOTE.REMARK, PROCESSBU.CODE PROCESSBUCODE, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
 INVOICEBU.CODE INVOICEBUCODE, INVOICEBU.DESCRIPTION INVOICEBUDESCRIPTION,
 ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION ROUTEDESCRIPTION,ROUTE.LOADINGDOCK,
 PACKINGNOTE.CLEANRETURN,
 PACKINGNOTE.DEADLINE,
 CONSIGNMENTNOTE.CONSIGNMENTNOTENUMBER,
 PACKINGNOTE.SYSTEMUSER_ID, PACKINGNOTE.TIMESTAMP,PACKINGNOTE.CREATIONTIMESTAMP,
 PACKINGNOTE.ENDDATEFORUSE,
 (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,
  DRIVER.NAME DRIVERNAME,
  DRIVER.EMPLOYEENUMBER DRIVERNUMBER
  , CASE WHEN CUSTOMER.DELNOTEFORBULKPUTUPITEMS = 0 THEN  'N' ELSE 'Y' END BULKPUTUPONPACKINGNOTE,
  PACKINGNOTE.YEAR YEAR
  , (SELECT SS.VALUE FROM SYSTEMSETTING SS WHERE SS.PLANT_ID = PROCESSBU.PLANT_ID
            AND SS.NAME = 'PACKINGNOTECOLUMNS') PACKINGNOTECOLUMNS
  , (SELECT COUNT(*) FROM CUSTOMERDELIVERYDAY CDD WHERE CUSTOMER.CUSTOMER_ID = CDD.CUSTOMER_ID
        AND CDD.DAY_ID = PACKINGNOTE.DAYNUMBER AND CDD.TYPEOFMERCHADISE =2) DELIVERGARMENTS,
        PACKINGNOTE.STOPNUMBER, ROUTE.PUTUPREPORTPERCUSTOMER
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, PLANTDEPARTMENT,
       TRANSPORTARTICLE,STATUS, DELIVERYPOINT, ADDRESS,
       BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU,
       PACKINGNOTE
       LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
       LEFT OUTER JOIN ROUTECONTROL ON (PACKINGNOTE.ROUTECONTROL_ID = ROUTECONTROL.ROUTECONTROL_ID )
       LEFT OUTER JOIN CONSIGNMENTNOTE ON (PACKINGNOTE.CONSIGNMENTNOTE_ID = CONSIGNMENTNOTE.CONSIGNMENTNOTE_ID)
       LEFT OUTER JOIN ROUTE ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID
              LEFT OUTER JOIN DEPOT ON DEPOT.DEPOT_ID=ROUTE.DEPOT_ID
              LEFT OUTER JOIN EMPLOYEE DRIVER ON DRIVER.EMPLOYEE_ID=ROUTE.DRIVER_ID,
       LANGUAGES
 	WHERE
      PACKINGNOTE.TRANSPORTARTICLE_ID = TRANSPORTARTICLE.TRANSPORTARTICLE_ID
  AND PACKINGNOTE.STATUS_ID = STATUS.STATUS_ID
  AND STATUS.STATUSTYPE = 'PN'  --AND CAST(STATUS.CODE AS NUMERIC)<=20
  AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = ADDRESS.ADDRESS_ID
	AND PACKINGNOTE.PLANTDEPARTMENT_ID = PLANTDEPARTMENT.PLANTDEPARTMENT_ID
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
	AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  AND PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
	AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
	AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID

/
create or replace view V_PACKINGNOTE_PACKCONTENTS
 (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 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_PACKINGNOTE_PG3_LLG
 (PG_CODE, PACKINGNOTE_ID, SIZECODE, TOBEDELIVEREDAMOUNT)
as select pg.code pg_code,
pnl.packingnote_id,
sd.code sizecode,
pnl.tobedeliveredamount
from packingnote pn, packingnoteline pnl, product p, sizedefinition sd, productgroup pg
where pn.packingnote_id = pnl.packingnote_id
and pnl.product_id = p.product_id
and pnl.sizedefinition_id = sd.sizedefinition_id
and pg.productgroup_id = p.productgroup_id
and pg.code = 'L3'

/
create or replace view V_PACKINGNOTE_REF_LLG
 (REFERENCE, PRODUCT_ID, SIZEDEFINITION_ID, FINISHINGMETHOD_ID, PACKINGNOTE_ID, LANGUAGECODE)
as select dv.reference,
       dv.product_id,
       dv.sizedefinition_id,
       dv.finishingmethod_id,
       dv.packingnote_id,
       l.code languagecode
  from deliveryvariations dv, packingnoteline pnl, languages l, product p, productgroup pg
 where dv.packingnote_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 pnl.product_id = p.product_id
   and p.productgroup_id = pg.productgroup_id
   and pg.code = '99'

/
create or replace view V_PACKINGNOTE_SMG
 (PACKINGNOTEID, STATUSTYPE, DRIVINGDATE, DEPOTCODE, DEPOTDESCRIPTION, NOTENUMBER, CUSTOMERNUMBER, CUSTNR, CUSTOMERNAME, CUSTOMERLEGALNAME, STREET, STREET2, CITY, STATE, ZIPCODE, COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, PACKINGDEPARTMENTCODE, PACKINGDEPARTMENTDESCRIPTION, TRANSPORTARTICLECODE, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENUMBER
, EMPLOYEENAME, PRODUCTIONDATE, DELIVERYDATE, STATUSCODE, REMARK, PROCESSBUCODE, PROCESSBUDESCRIPTION, INVOICEBUCODE, INVOICEBUDESCRIPTION, ROUTENUMBER, ROUTEDESCRIPTION, LOADINGDOCK, CLEANRETURN, DEADLINE, CONSIGNMENTNOTENUMBER, SYSTEMUSER_ID, TIMESTAMP, CREATIONTIMESTAMP, ENDDATEFORUSE, DAYDESCRIPTION, WEEK, LANGUAGECODE, DRIVERNAME, DRIVERNUMBER, BULKPUTUPONPACKINGNOTE, YEAR, PACKINGNOTECOLUMNS, DELIVERGARMENTS, STOPNUMBER, PUTUPREPORTPERCUSTOMER)
as SELECT PACKINGNOTE.PACKINGNOTE_ID PACKINGNOTEID,STATUS.STATUSTYPE,  ROUTECONTROL.DRIVINGDATE, DEPOT.CODE DEPOTCODE, DEPOT.DESCRIPTION DEPOTDESCRIPTION,
 PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER,
 cast(insertspace_after_x_characters(to_char(CUSTOMER.CUSTOMERNUMBER),3) as varchar2(20)) custnr,
  CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME CUSTOMERLEGALNAME,
 ADDRESS.STREET, ADDRESS.STREET2, ADDRESS.CITY, ADDRESS.STATE, ADDRESS.ZIPCODE, ADDRESS.COUNTY,
 DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
 DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
  DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
 PACKINGNOTE.SEQUENCENUMBER, PLANTDEPARTMENT.CODE PACKINGDEPARTMENTCODE, PLANTDEPARTMENT.DESCRIPTION PACKINGDEPARTMENTDESCRIPTION,
 TRANSPORTARTICLE.CODE TRANSPORTARTICLECODE,
 (SELECT DESCRIPTION FROM TRANSPORTARTICLE_DESC  A WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
 PACKINGNOTE.OCCUPANCY, EMPLOYEE.EMPLOYEENUMBER, EMPLOYEE.NAME EMPLOYEENAME,
 PACKINGNOTE.PRODUCTIONDATE,
 PACKINGNOTE.DELIVERYDATE,
 STATUS.CODE STATUSCODE,
 PACKINGNOTE.PNREMARK REMARK
, PROCESSBU.CODE PROCESSBUCODE, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
 INVOICEBU.CODE INVOICEBUCODE, INVOICEBU.DESCRIPTION INVOICEBUDESCRIPTION,
 ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION ROUTEDESCRIPTION,ROUTE.LOADINGDOCK,
 PACKINGNOTE.CLEANRETURN,
 PACKINGNOTE.DEADLINE,
 CONSIGNMENTNOTE.CONSIGNMENTNOTENUMBER,
 PACKINGNOTE.SYSTEMUSER_ID, PACKINGNOTE.TIMESTAMP,PACKINGNOTE.CREATIONTIMESTAMP,
 PACKINGNOTE.ENDDATEFORUSE,
 (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,
  DRIVER.NAME DRIVERNAME,
  DRIVER.EMPLOYEENUMBER DRIVERNUMBER --TODO6844
  , CASE WHEN CUSTOMER.DELNOTEFORBULKPUTUPITEMS = 0 THEN  'N' ELSE 'Y' END BULKPUTUPONPACKINGNOTE,
  PACKINGNOTE.YEAR YEAR
  , (SELECT SS.VALUE FROM SYSTEMSETTING SS WHERE SS.PLANT_ID = PROCESSBU.PLANT_ID
            AND SS.NAME = 'PACKINGNOTECOLUMNS') PACKINGNOTECOLUMNS
  , (SELECT COUNT(*) FROM CUSTOMERDELIVERYDAY CDD WHERE CUSTOMER.CUSTOMER_ID = CDD.CUSTOMER_ID
        AND CDD.DAY_ID = PACKINGNOTE.DAYNUMBER AND CDD.TYPEOFMERCHADISE =2) DELIVERGARMENTS,
        PACKINGNOTE.STOPNUMBER, ROUTE.PUTUPREPORTPERCUSTOMER
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, PLANTDEPARTMENT,
       TRANSPORTARTICLE,STATUS, DELIVERYPOINT, ADDRESS,
       BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU,
       --ROUTESTOP, ROUTE RETURNROUTE,DAY,
       PACKINGNOTE
       LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
       --LEFT OUTER JOIN CONTAINERTYPE ON (PACKINGNOTE.CONTAINERTYPE_ID = CONTAINERTYPE.CONTAINERTYPE_ID)
       LEFT OUTER JOIN ROUTECONTROL ON (PACKINGNOTE.ROUTECONTROL_ID = ROUTECONTROL.ROUTECONTROL_ID )
       LEFT OUTER JOIN CONSIGNMENTNOTE ON (PACKINGNOTE.CONSIGNMENTNOTE_ID = CONSIGNMENTNOTE.CONSIGNMENTNOTE_ID)
       --LEFT OUTER JOIN WEIGHINGCATEGORY ON (PACKINGNOTE.WEIGHINGCATEGORY_ID = WEIGHINGCATEGORY.WEIGHINGCATEGORY_ID),
       LEFT OUTER JOIN ROUTE ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID
              LEFT OUTER JOIN DEPOT ON DEPOT.DEPOT_ID=ROUTE.DEPOT_ID
              LEFT OUTER JOIN EMPLOYEE DRIVER ON DRIVER.EMPLOYEE_ID=ROUTE.DRIVER_ID,
       LANGUAGES
   WHERE
      PACKINGNOTE.TRANSPORTARTICLE_ID = TRANSPORTARTICLE.TRANSPORTARTICLE_ID
  AND PACKINGNOTE.STATUS_ID = STATUS.STATUS_ID
  AND STATUS.STATUSTYPE = 'PN'
  AND CAST(STATUS.CODE AS NUMERIC)<=20
  AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = ADDRESS.ADDRESS_ID
  AND PACKINGNOTE.PLANTDEPARTMENT_ID = PLANTDEPARTMENT.PLANTDEPARTMENT_ID
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
  AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  AND PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
  AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
  AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID

/
create or replace view V_PACKINGNOTE_SNG
 (PACKINGNOTEID, STATUSTYPE, DRIVINGDATE, DEPOTCODE, DEPOTDESCRIPTION, NOTENUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERLEGALNAME, STREET, STREET2, CITY, STATE, ZIPCODE, COUNTY, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, SEQUENCENUMBER, PACKINGDEPARTMENTCODE, PACKINGDEPARTMENTDESCRIPTION, TRANSPORTARTICLECODE, TRANSPORTARTICLEDESCRIPTION, OCCUPANCY, EMPLOYEENUMBER, EMPLOYEENAME
, PRODUCTIONDATE, DELIVERYDATE, STATUSCODE, STATUSDESCRIPTION, REMARK, PROCESSBUCODE, PROCESSBUDESCRIPTION, INVOICEBUCODE, INVOICEBUDESCRIPTION, ROUTENUMBER, ROUTEDESCRIPTION, LOADINGDOCK, CLEANRETURN, DEADLINE, CONSIGNMENTNOTENUMBER, SYSTEMUSER_ID, TIMESTAMP, CREATIONTIMESTAMP, ENDDATEFORUSE, DAYDESCRIPTION, WEEK, DRIVERNAME, DRIVERNUMBER, BULKPUTUPONPACKINGNOTE, YEAR, PACKINGNOTECOLUMNS, DELIVERGARMENTS, STOPNUMBER, PUTUPREPORTPERCUSTOMER, CUSTOMERLANGUAGE
, DEADLINEASNUMERIC, PACKINGDAY_ID)
as SELECT PACKINGNOTE.PACKINGNOTE_ID PACKINGNOTEID,STATUS.STATUSTYPE,  ROUTECONTROL.DRIVINGDATE, DEPOT.CODE DEPOTCODE, DEPOT.DESCRIPTION DEPOTDESCRIPTION,
 PACKINGNOTE.NOTENUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME CUSTOMERNAME, CUSTOMER.LEGALNAME CUSTOMERLEGALNAME,
 ADDRESS.STREET, ADDRESS.STREET2, ADDRESS.CITY, ADDRESS.STATE, ADDRESS.ZIPCODE, ADDRESS.COUNTY,
 DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
 DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION DISTRIBUTIONPOINTDESCRIPTION,
  DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESCRIPTION,
 PACKINGNOTE.SEQUENCENUMBER, PLANTDEPARTMENT.CODE PACKINGDEPARTMENTCODE, PLANTDEPARTMENT.DESCRIPTION PACKINGDEPARTMENTDESCRIPTION,
 TRANSPORTARTICLE.CODE TRANSPORTARTICLECODE,
 (SELECT A.DESCRIPTION FROM TRANSPORTARTICLE_DESC  A WHERE A.TRANSPORTARTICLE_ID = PACKINGNOTE.TRANSPORTARTICLE_ID AND A.LANGUAGE_ID = CUSTOMER.LANGUAGE_ID ) TRANSPORTARTICLEDESCRIPTION,
 PACKINGNOTE.OCCUPANCY, EMPLOYEE.EMPLOYEENUMBER, EMPLOYEE.NAME EMPLOYEENAME,
 PACKINGNOTE.PRODUCTIONDATE,
 PACKINGNOTE.DELIVERYDATE,
 STATUS.CODE STATUSCODE,
 (SELECT S.DESCRIPTION FROM STATUS_DESC S WHERE S.STATUS_ID = PACKINGNOTE.STATUS_ID AND S.LANGUAGE_ID = CUSTOMER.LANGUAGE_ID ) STATUSDESCRIPTION,
 PACKINGNOTE.PNREMARK REMARK, PROCESSBU.CODE PROCESSBUCODE, PROCESSBU.DESCRIPTION PROCESSBUDESCRIPTION,
 INVOICEBU.CODE INVOICEBUCODE, INVOICEBU.DESCRIPTION INVOICEBUDESCRIPTION,
 ROUTE.ROUTENUMBER, ROUTE.DESCRIPTION ROUTEDESCRIPTION,ROUTE.LOADINGDOCK,
 PACKINGNOTE.CLEANRETURN,
 PACKINGNOTE.DEADLINE,
 CONSIGNMENTNOTE.CONSIGNMENTNOTENUMBER,
 PACKINGNOTE.SYSTEMUSER_ID, PACKINGNOTE.TIMESTAMP,PACKINGNOTE.CREATIONTIMESTAMP,
 PACKINGNOTE.ENDDATEFORUSE,
 (SELECT UPPER(DD.DESCRIPTION) FROM DAY_DESC DD WHERE DD.LANGUAGE_ID = CUSTOMER.LANGUAGE_ID AND DD.DAY_ID = PACKINGNOTE.DAYNUMBER) DAYDESCRIPTION
,	CAST(PACKINGNOTE.WEEK AS VARCHAR2(2)) WEEK,-- LANGUAGES.CODE LANGUAGECODE,
  DRIVER.NAME DRIVERNAME,
  DRIVER.EMPLOYEENUMBER DRIVERNUMBER
  , CASE WHEN CUSTOMER.DELNOTEFORBULKPUTUPITEMS = 0 THEN  'N' ELSE 'Y' END BULKPUTUPONPACKINGNOTE,
  PACKINGNOTE.YEAR YEAR
  , (SELECT SS.VALUE FROM SYSTEMSETTING SS WHERE SS.PLANT_ID = PROCESSBU.PLANT_ID
            AND SS.NAME = 'PACKINGNOTECOLUMNS') PACKINGNOTECOLUMNS
  , (SELECT COUNT(*) FROM CUSTOMERDELIVERYDAY CDD WHERE CUSTOMER.CUSTOMER_ID = CDD.CUSTOMER_ID
        AND CDD.DAY_ID = PACKINGNOTE.DAYNUMBER AND CDD.TYPEOFMERCHADISE =2) DELIVERGARMENTS,
        PACKINGNOTE.STOPNUMBER, ROUTE.PUTUPREPORTPERCUSTOMER
, (SELECT CLAN.CODE FROM LANGUAGES CLAN WHERE CUSTOMER.LANGUAGE_ID = CLAN.LANGUAGE_ID) CUSTOMERLANGUAGE
, GETTIMEASNUMERIC(PACKINGNOTE.DEADLINE) DEADLINEASNUMERIC
, ROUTECONTROL.Packingday_Id
FROM CUSTOMER, DEPARTMENT, DISTRIBUTIONPOINT, PLANTDEPARTMENT,
       TRANSPORTARTICLE,STATUS, DELIVERYPOINT, ADDRESS,
       BUSINESSUNIT PROCESSBU, BUSINESSUNIT INVOICEBU,
       PACKINGNOTE
       LEFT OUTER JOIN EMPLOYEE ON (PACKINGNOTE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
       LEFT OUTER JOIN ROUTECONTROL ON (PACKINGNOTE.ROUTECONTROL_ID = ROUTECONTROL.ROUTECONTROL_ID )
       LEFT OUTER JOIN CONSIGNMENTNOTE ON (PACKINGNOTE.CONSIGNMENTNOTE_ID = CONSIGNMENTNOTE.CONSIGNMENTNOTE_ID)
       LEFT OUTER JOIN ROUTE ON PACKINGNOTE.ROUTE_ID = ROUTE.ROUTE_ID
              LEFT OUTER JOIN DEPOT ON DEPOT.DEPOT_ID=ROUTE.DEPOT_ID
              LEFT OUTER JOIN EMPLOYEE DRIVER ON DRIVER.EMPLOYEE_ID=ROUTE.DRIVER_ID--,       LANGUAGES
 	WHERE
      PACKINGNOTE.TRANSPORTARTICLE_ID = TRANSPORTARTICLE.TRANSPORTARTICLE_ID
  AND PACKINGNOTE.STATUS_ID = STATUS.STATUS_ID
  AND STATUS.STATUSTYPE = 'PN'
  AND CAST(STATUS.CODE AS NUMERIC)<=20
  AND PACKINGNOTE.DELIVERYPOINT_ID = DELIVERYPOINT.DELIVERYPOINT_ID
  AND DELIVERYPOINT.DELIVERYADDRESS_ID = ADDRESS.ADDRESS_ID
	AND PACKINGNOTE.PLANTDEPARTMENT_ID = PLANTDEPARTMENT.PLANTDEPARTMENT_ID
  AND PACKINGNOTE.PROCESSBUSINESSUNIT_ID = PROCESSBU.BUSINESSUNIT_ID
	AND PACKINGNOTE.INVOICEBUSINESSUNIT_ID = INVOICEBU.BUSINESSUNIT_ID
  AND PACKINGNOTE.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
	AND DISTRIBUTIONPOINT.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
	AND DEPARTMENT.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID

/
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_PAYBYLIST_BDE
 (INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, INVOICEDATE, INVOICENUMBER, INV_NR_CHAR, CONTACTPERSONNAME, SPLITUPCODE, SPLITUPDESCRIPTION, INVOICEFREQUENCYNUMBER, CURRENCYCODE, INVOICEHEADER_ID, CREDITSQUEEZEAMOUNT, INVOICEAMOUNTDECIMALS, CURRENCYDESCRIPTION, DECIMALS, STARTDATE, ENDDATE, PREBILLAMOUNT, TOTALAMOUNTEXCLVAT, BILLTOCOUNTRYDESCRIPTION, INVOICELAYOUTCODE, PARENTINVOICEHEADER_ID
, NEXTPERIODSTARTDATE, DIVISION_CODE, INVOICENUMBERPREFIX, PAYBY_NO, PAYBY_NAME, EXTRANAME2, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, HOUSENUMBER, HOUSENUMBEREXT, DUEDATE, PLANT_PHONE, PLANT_FAX, CONTACTPERSON_NAME, PARENT_PREBILLAMOUNT, PARENT_TOTALEXCLVAT, PARENT_NR, PARENT_NR_CHAR, PARENT_TYPE, PARENT_DATE, MAX_PERCENTAGE, PAYMENTTERMS_DESC, IS_IN_ADVANCE)
as select e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
       a.billtocustomernumber, a.billtocustomername, --pi.extraname2,
       a.deltocustomernumber, a.deltocustomername, a.invoicedate, a.invoicenumber, to_char(a.invoicenumber) Inv_Nr_char,
       --a.city, a.county, a.state, a.zipcode,a.street2, a.street, a.housenumber,a.housenumberext,
       --a.contactpersonname,
       (select cp.name from contactperson cp where cp.customer_id = a.billtocustomer_link_id and cp.invoicecontactperson = 'Y') contactpersonname,
       a.splitupcode, a.splitupdescription,
       a.invoicefrequency_id invoicefrequencynumber, b.code currencycode, a.invoiceheader_id,
       a.creditsqueezeamount, b.invoiceamountdecimals, b.description currencydescription,
       b.decimals, pi.startdate, pi.enddate, a.prebillamount, a.totalamountexclvat,
       ihextr.billtocountrydescription, --ihextr.paymenttermsdescription paymentterms_desc,
       ihextr.formlayoutcode invoicelayoutcode, a.parentinvoiceheader_id,
       a.NEXTPERIODSTARTDATE,
       (select d.code from division d where e.division_id = d.division_id) Division_code
, e.invoicenumberprefix
, PBCust.Customernumber PayBy_No , PBCust.Name PayBy_Name
, PBCust.Extraname2
, ad.city, ad.county, ad.state, ad.zipcode, ad.street2, ad.street, ad.housenumber, ad.housenumberext
, ihextr.paymenttermsduedate DueDate
--, procbu.code procbu_code, procbu.description procbu_desc
, pl.phoneno plant_phone, pl.faxno plant_fax
--, emp.name ContactPerson_name, emp.employeenumber
--, (select max(emp.name) from employee emp where PBCust.serviceemployee_id = emp.employee_id) ContactPerson_name
--, co.name ContactPerson_name
,(select o.name from contactperson o where o.customer_id = PBCust.Customer_Id and o.invoicecontactperson = 'Y') ContactPerson_name
--, cast(GETSUBSTRING(a.invoicenumber, -3) as varchar2(3)) Seq
, pi.prebillamount Parent_prebillamount, pi.totalamountexclvat Parent_totalexclvat
, pi.invoicenumber Parent_nr, to_char(pi.invoicenumber) Parent_nr_char, pi.invoicetype Parent_type, pi.invoicedate Parent_date,
       (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
, (select ptd.description from customerbillinginfo cbi, paymentterms_desc ptd where PBCust.Customer_Id=cbi.customer_id and
                          cbi.paymentterms_id=ptd.paymentterms_id and ptd.language_id=PBCust.Language_Id) paymentterms_desc
, case
  when ((a.parentinvoiceheader_id is null) or (a.parentinvoiceheader_id <> a.invoiceheader_id))
  then (case when a.nextperiodstartdate is null then 0 else 1 end)
  else ( select count(cih.nextperiodstartdate) from invoiceheader cih
  where cih.parentinvoiceheader_id = a.invoiceheader_id and cih.parentinvoiceheader_id <> cih.invoiceheader_id
        and cih.nextperiodstartdate is not null )
  end  Is_in_advance
from  customer PBCust, address ad, customer delto--, contactperson co
--        LEFT OUTER JOIN employee emp on delto.serviceemployee_id = emp.employee_id
      , currency b, status s, businessunit e, plant pl, invoiceheaderextrainfo ihextr,
      invoiceheader a
        LEFT OUTER JOIN invoiceheader pi on a.parentinvoiceheader_id = pi.invoiceheader_id
       ,customerbillinginfo cbi
where PBCust.Customer_Id = ihextr.paybycustomer_link_id
      and cbi.customer_id=PBCust.Customer_Id
      and a.invoiceheader_id = ihextr.invoiceheader_id
      and PBCust.Currency_Id = b.currency_id
      and a.documenttype = 1
      and s.code = '2'
      and a.invoicebusinessunit_id = e.businessunit_id
      and a.status_id = s.status_id
      and pl.plant_id = e.plant_id
      and PBCust.Invoiceaddress_Id = ad.address_id
      and a.deltocustomer_link_id = delto.customer_id
      and (cbi.paybycustomer =1 or cbi.paybycustomer =2)
--      and cbi.printinvoice = 1

/
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 cm.year year, cm.month month, cu.customernumber, cu.customer_id, max(cu.name) customername,
       delk.departmentnumber, max(delk.description) departmentdesc, webusersession.websession_id,
       wcu.webuser_id, dh.department_link_id web_department_id, dh.department_link_id,
       coalesce((select sum(pdy.patientdays)
                 from   patientday pdy, distributionpoint_link
                 where  distributionpoint_link.department_link_id = dh.department_link_id
                 and    distributionpoint_link.distributionpoint_link_id = pdy.distributionpoint_link_id
                 and    pdy.year = cm.year
                 and    pdy.month = cm.month
                 group  by distributionpoint_link.department_link_id), 0) patientdaysdep,
       coalesce(sum(dh.amountdelivered * case
                      when dh.pieceweight <> 0 then
                       dh.pieceweight
                      else F_GETTHEORETICALWEIGHT(p.theoreticalweight, dh.product_link_id, dh.sizedefinition_link_id)
                    end), 0) weight,
       coalesce((select sum(budget.amount)
                 from   budget
                 where  budget.department_link_id = dh.department_link_id
                 and    budget.year = cm.year
                 and    budget.month = cm.month
                 and budget.week = 0), 0) budget,
       coalesce(sum(dh.amountdelivered *
                     f_getcostreportprice(dh.customer_link_id, dh.product_link_id,
                                          dh.sizedefinition_link_id, dh.finishingmethod_id,
                                          dh.deliverydate, p.typeofmerchandise, p.weighingcategory_id,
                                          currency.decimals)), 0) actual,
       currency.invoiceamountdecimals, currency.decimals, currency.code currencycode,
       --languages.code languagecode,
       coalesce(max((select max(plpc.budgetrelevant)
            from  productlistpercustomer plpc
            where plpc.customer_id = dh.customer_link_id
            and   plpc.product_id = dh.product_link_id
            and   (plpc.sizedefinition_id = dh.sizedefinition_link_id or
                  plpc.sizedefinition_id in
                  (select szdef.sizedefinition_id from sizedefinition szdef where szdef.code = '*'))
            and    plpc.finishingmethod_id = dh.finishingmethod_id
            and    plpc.dateactive <= dh.deliverydate
            and    plpc.dateinactive >= dh.deliverydate)), 'N') budgetrelevant
from   customermonth cm
join   deliveryhistory dh
on     (dh.customer_link_id = cm.customer_id and dh.deliverydate between cm.startdate and cm.enddate)
join   customer cu
on     (cm.customer_id = cu.customer_id)
join   product p
on     (p.product_id = dh.product_link_id)
join   webusercustomer wcu
on     (dh.customer_link_id = wcu.customer_id)
left   outer join webuserdepartment wde
on     (wcu.webusercustomer_id = wde.webusercustomer_id and wde.department_id = dh.department_link_id)
join   webusersession
on     (webusersession.customer_id = dh.customer_link_id)
join   department_link delk
on     (dh.department_link_id = delk.department_link_id)
join   currency
on     (cu.currency_id = currency.currency_id)--, languages
where  dh.packindication <> 2
group  by cm.year, cm.month, cu.customernumber, cu.customer_id, delk.departmentnumber,
          webusersession.websession_id, wcu.webuser_id, dh.department_link_id,
          currency.invoiceamountdecimals, currency.decimals, currency.code, --languages.language_id,languages.code,
          dh.customer_link_id, dh.product_link_id, dh.sizedefinition_link_id, dh.finishingmethod_id

/
create or replace view V_PERIODACTUALBUDGET_ANG
 (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
, webusersession.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 * dh.pieceweight),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 *
          (  coalesce(dh.pieceweight * F_GETPOUNDPRICE(dh.product_link_id, dh.finishingmethod_id, dh.sizedefinition_link_id
                                         , dh.customer_link_id, prd.weighingcategory_id, dh.deliverydate),0)
             + F_RESTOCKINGPRICE_ANG(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
, webusersession, 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 = webusersession.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
, webusersession.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_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
, getcurrentdate() 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_PICKORDERCONVET_SMG
 (WORKORDERLINEEMBLEM_ID, EMBLEMTEMPLATELINE_ID, WORKORDERLINE_ID, WORKORDER_ID, EMBLEMTEMPLATE_ID, EMBLEMTEMPLATEDESCRIPTION, QUANTITY, EMBLEMTEMPLATELINEDESC, LANGUAGECODE, PRODUCTCODE, PRODUCTDESCRIPTION, PLACEMENTCODE, PLACEMENTDESCRIPTION)
as select
 -1 workorderlineemblem_id,
       etl.emblemtemplateline_id,
       wol.workorderline_id,
       wol.workorder_id,
       et.emblemtemplate_id,
       et.description emblemtemplatedescription,
       etl.qtypergarment quantity,
       etl.description emblemtemplatelinedesc,
       lan.code languagecode,
       p.code productcode,
      (select pd.description
          from product_desc pd
         where pd.product_id = etl.product_id
           and lan.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 = lan.language_id) placementdescription
  from
 workorder wo, workorderline wol, wearerinventory wi, wearerinventory wphasein,emblemtemplate et,emblemtemplateline etl,
 PhaseOutWearerInventory pco, productconversion pc,productconversionsize pcs,
 product destprod, sizedefinition destsize, qualitygrade qq, languages lan,placement pc , product p
where wo.workorder_id=wol.workorder_id
      and  wo.weareremployment_link_id= wi.weareremployment_id
      and wi.wearerinventory_id=pco.phaseoutwearerinventory_id
      and pco.phaseinwearerinventory_id=wphasein.wearerinventory_id
      and wphasein.weareremployment_id=wo.weareremployment_link_id
      and wphasein.product_id=destprod.product_id
      and wphasein.sizedefinition_id=destsize.sizedefinition_id
      and pc.sourceproduct_id=wol.product_link_id
      and wo.customer_link_id=pc.customer_link_id
      and pc.destinationproduct_id=destprod.product_id
      and pc.productconversion_id=pcs.productconversion_id
      and ((pcs.productconversionsize_id = pco.productconversionsize_id)or pco.Productconversionsize_Id is null)
      and wol.sizedefinition_link_id=pcs.sourcesizedefinition_id
      and pc.status=1
      and pc.startdate > wo.neededdate
      and wol.requestedgrade_id=qq.qualitygrade_id
      and wphasein.emblemtemplate_id=et.emblemtemplate_id
      and et.emblemtemplate_id=etl.emblemtemplate_id
      and etl.placement_id=pc.placement_id
      and etl.product_id = p.product_id
 union all
 select
  -1 workorderlineemblem_id,
       etl.emblemtemplateline_id,
       wol.workorderline_id,
       wol.workorder_id,
       et.emblemtemplate_id,
       et.description emblemtemplatedescription,
       etl.qtypergarment quantity,
       etl.description emblemtemplatelinedesc,
       lan.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 = lan.language_id) placementdescription
  from
 workorder wo, workorderline wol, wearerinventory wi, wearerinventory wphasein,emblemtemplate et,emblemtemplateline etl,
  PhaseOutWearerInventory pco, productconversion pc,productconversionsize pcs,
 product destprod, sizedefinition destsize, qualitygrade qq,placement pc ,languages lan
 where wo.workorder_id=wol.workorder_id
      and  wo.weareremployment_link_id= wi.weareremployment_id
      and wi.wearerinventory_id=pco.phaseoutwearerinventory_id
      and pco.phaseinwearerinventory_id=wphasein.wearerinventory_id
      and wphasein.weareremployment_id=wo.weareremployment_link_id
      and wphasein.product_id=destprod.product_id
      and wphasein.sizedefinition_id=destsize.sizedefinition_id
      and pc.sourceproduct_id=wol.product_link_id
      and wo.customer_link_id=pc.customer_link_id
      and pc.destinationproduct_id=destprod.product_id
      and pc.status=1
      and pc.startdate > wo.neededdate
      and pc.productconversion_id=pcs.productconversion_id
      and ((pcs.productconversionsize_id = pco.productconversionsize_id)or pco.Productconversionsize_Id is null)
      and wol.sizedefinition_link_id=pcs.sourcesizedefinition_id
      and wol.requestedgrade_id=qq.qualitygrade_id
      and wphasein.emblemtemplate_id=et.emblemtemplate_id
      and et.emblemtemplate_id=etl.emblemtemplate_id
      and etl.placement_id=pc.placement_id
      and etl.product_id is null

/
create or replace view V_PICKORDERCONVP_SMG
 (WORKORDERLINE_ID, DESTPRODCODE, PRODDESC, DESTSIZECODE, QCODE, ROWCODE, LOCATIONCODE, QUANTITYPHASEIN, LANCODE, OOSPRODUCT)
as select wol.workorderline_id,(select destprod.code from product destprod where destprod.product_id=wphasein.product_id) destprodcode,
( select pd.description from product_desc pd where pd.product_id=wphasein.product_id and pd.language_id=lan.language_id )  proddesc,
 destsize.code destsizecode,qq.code qcode
, f_getrowcodeloc_smg(wphasein.product_id,wphasein.sizedefinition_id,wol.requestedgrade_id,wo.processingstockroom_id,wol.codeuniquely, 'Y') rowcode
, f_getrowcodeloc_smg(wphasein.product_id,wphasein.sizedefinition_id, wol.requestedgrade_id, wo.processingstockroom_id, wol.codeuniquely, 'F') locationcode
,wol.quantityphasein, lan.code lancode
,(select coalesce( oosp.status,0)
                from  stockdefinitionperitem sdi,stockreservationpergrade srg
                left outer join outofserviceproduct oosp on srg.stockreservationpergrade_id=oosp.stockreservationpergrade_id
                where srg.stockdefinitionperitem_id=sdi.stockdefinitionperitem_id
                and sdi.stockroom_id=wo.processingstockroom_id
                and sdi.product_id=wol.product_link_id
                and sdi.sizedefinition_id=wol.sizedefinition_link_id
                and srg.qualitygrade_id=wol.requestedgrade_id
                and sdi.customer_id is null
                and (oosp.sequencenumber is null or oosp.sequencenumber=( select max(oosp1.sequencenumber) from outofserviceproduct oosp1
                where oosp1.stockreservationpergrade_id=srg.stockreservationpergrade_id)))OOSProduct
from  workorder wo, workorderline wol, wearerinventory wi, wearerinventory wphasein, PhaseOutWearerInventory pco
 , productconversion pc,  sizedefinition destsize, qualitygrade qq, languages lan
where wo.workorder_id=wol.workorder_id
      and wo.weareremployment_link_id= wi.weareremployment_id
      and wi.wearerinventory_id=pco.phaseoutwearerinventory_id
      and pco.phaseinwearerinventory_id=wphasein.wearerinventory_id
      and wo.weareremployment_link_id=wphasein.weareremployment_id
      and wphasein.product_id=pc.destinationproduct_id
      and wphasein.sizedefinition_id=destsize.sizedefinition_id
      and pc.sourceproduct_id=wol.product_link_id
      and wi.product_id = pc.sourceproduct_id
      and wi.sizedefinition_id=wol.sizedefinition_link_id
      and wi.product_id=wol.product_link_id
      and wo.customer_link_id=pc.customer_link_id
      and pc.status=1
      and wol.requestedgrade_id=qq.qualitygrade_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_PICKORDERRESERV_SMG
 (WORKORDERLINE_ID, PRODCODE, SDCODE, QGRADE, QTYRES, SEQUENCENUMBER, ROWCODE, LOCATIONCODE, STOCKRESERVATIONPERGRADE_ID, PRIORITY)
as select wol.workorderline_id, p.code prodcode, sd.code sdcode,  q.code qgrade, sum (wolr.quantity) qtyres, min(wolr.sequencenumber)sequencenumber
, f_getrowcodeloc_smg(p.product_id,sd.sizedefinition_id, q.qualitygrade_id, wo.processingstockroom_id, wol.codeuniquely, 'Y') rowcode
, f_getrowcodeloc_smg(p.product_id,sd.sizedefinition_id, q.qualitygrade_id, wo.processingstockroom_id, wol.codeuniquely, 'F') locationcode
, wolr.stockreservationpergrade_id, q.priority
from workorder wo, workorderline wol, workorderlinereservation wolr, stockreservationpergrade srg, stockdefinitionperitem sdi, product p, sizedefinition sd, qualitygrade q
where wo.workorder_id=wol.workorder_id
and  wol.workorderline_id=wolr.workorderline_id
and wolr.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=q.qualitygrade_id
group by  wo.workorder_id, wo.processingstockroom_id,wol.workorderline_id,p.product_id,
sd.sizedefinition_id, q.qualitygrade_id, p.code , sd.code,  q.code,q.priority,wol.codeuniquely,wolr.stockreservationpergrade_id

/
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_PICKUPFORM_SUM_SMG
 (REPORTPARAM_ID, COPY_NUMBER, CPL, CUSTOMERNUMBER, CUSTOMERNAME, CUSTNR, DEPARTMENTNUMBER, DEPARTMENTNAME, DISTRIBUTIONPOINT_ID, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTNUMBERNAME, PRODUCTCODE, PRODUCTDESC, CUSTOMCODE, CUSTOMDESCRIPTION, SIZECODE, CUSTOMER_ID, DELIVERYPOINT_ID, INTERNALPROCBU, BU_DESC, PLANTNAME, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTSTREET, PLANTZIP, PLANTCITY, DELPOINTCODE, PRODUCTGROUP, PRODUCTGROUPDESC, ACTIVITYCODE, ACTIVITYDESC, LEGALENTITY_ID, LEGALENTITY_LEGALNAME
, LEGALENTITY_STREET, LEGALENTITY_ZIP, LEGALENTITY_CITY, PLANTNAME_PART2)
as select   rp.reportparam_id
,        rp.copy_number
,        0 cpl
,        c.customernumber
,        max(c.name) customername
,        insertspace_after_x_characters(to_char(c.CUSTOMERNUMBER),3) custnr
,        t.departmentnumber
,        max(t.description) departmentname
,        dp.distributionpoint_id
,        dp.distributionpointnumber
,        max(dp.description) distributionpointnumbername
,        p.code productcode
,        max( ( select pd.description
                from   product_desc pd
                where  pd.product_id = plpd.product_id
                   and pd.language_id = c.language_id ) ) productdesc
,        max(l.customcode) customcode
,        max(l.customdescription) customdescription
,        sd.code sizecode
,        max(t.customer_id) customer_id
,        dp.deliverypoint_id
,        ( select min(bu.code)
           from   customeractivities ca
       ,      activity act
       ,      businessunit bu
           where  ca.customer_id = c.customer_id
              and ca.activity_id = act.activity_id
              and act.code = 'BK'
              and ca.internalprocessingbu_id = bu.businessunit_id ) internalprocbu
,        bu.description bu_desc
,        pl.name plantname
,        pl.phoneno plantphone
,        pl.faxno plantfax, pl.WEBSITE PLANTWEBSITE
,        ad.street plantstreet
,        ad.zipcode plantzip
,        ad.city plantcity
,        delp.code delpointcode
,        pg.code productgroup
,        ( select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id
             and pgd.language_id = c.language_id) productgroupdesc
,       act.code  activitycode
,        ( select ad.description from  activity_desc ad where   ad.activity_id = act.activity_id
                  and ad.language_id = c.language_id) activitydesc
, bu.Legalentity_Id, le.legalname LegalEntity_LegalName
, leadd.street LegalEntity_Street, leadd.zipcode LegalEntity_Zip, leadd.city LegalEntity_City
, case when pl.CODE = 'ARNO' then substr(pl.NAME, 25)
       when PL.CODE = 'CHEM' then substr(PL.NAME, 35)
       when PL.CODE = 'GRAZ' then substr(PL.NAME, 25)
       when PL.CODE = 'INZ' then substr(PL.NAME, 25)
       when PL.CODE = 'KRAM' then bu.Description--substr(PL.NAME, 25)
       when PL.CODE = 'LEOG' then substr(PL.NAME, 25)
       when PL.CODE = 'MATT' then substr(PL.NAME, 25)
       when PL.CODE = 'ORAD' then substr(PL.NAME, 27)
       when PL.CODE = 'PWSK' then substr(PL.NAME, 25)
       when PL.CODE = 'ROGA' then substr(PL.NAME, 36)
       when PL.CODE = 'SA14' then bu.Description--substr(PL.NAME, 25)
       when PL.CODE = 'SA22' then substr(PL.NAME, 25)
       when PL.CODE = 'SAWR' then substr(PL.NAME, 25)
       when PL.CODE = 'SCHI' then substr(PL.NAME, 25)
       when PL.CODE = 'SMA' then substr(PL.NAME, 25)
       when PL.CODE = 'SMB' then substr(PL.NAME, 20)
       when PL.CODE = 'SMHR' then substr(PL.NAME, 33)
       when PL.CODE = 'SMP' then substr(PL.NAME, 35)
       when PL.CODE = 'SMPL' then substr(PL.NAME, 31)
       when PL.CODE = 'SMRO' then substr(PL.NAME, 27)
       when PL.CODE = 'SMRS' then substr(PL.NAME, 31)
       when PL.CODE = 'SMS' then substr(PL.NAME, 25)
       when PL.CODE = 'SMSK' then substr(PL.NAME, 29)
       when PL.CODE = 'SMSL' then substr(PL.NAME, 36)
       when PL.CODE = 'SMTY' then substr(PL.NAME, 31)
       when PL.CODE = 'SMZL' then substr(PL.NAME, 25)
       when PL.CODE = 'SZOM' then substr(PL.NAME, 20)
else PL.NAME end PLANTNAME_PART2
from     productlistperdistribpoint plpd
,        distributionpoint dp
,        deliverypoint delp
,        department t
,        customer c
,        product p,productgroup pg,activity act
,        sizedefinition sd
,        standarddeliveryline stl
,        productlistpercustomer l
,        reportparam rp
,        businessunit bu
         left outer join legalentity le
              inner join address leadd on leadd.address_id = le.address_id
         on le.legalentity_id = bu.legalentity_id
,        plant pl
,        address ad
where plpd.distributionpoint_id=dp.distributionpoint_id
         and delp.deliverypoint_id = dp.deliverypoint_id
         and t.department_id = dp.department_id
         and c.customer_id = t.customer_id
         and p.product_id = plpd.product_id
         and p.productgroup_id=pg.productgroup_id
         and pg.activity_id=act.activity_id
         and plpd.sizedefinition_id=sd.sizedefinition_id
         and stl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
         and stl.productlistpercustomer_id = l.productlistpercustomer_id
         and ( l.productlistpercustomer_id = stl.productlistpercustomer_id and
                  l.soilcountmethod <> 0 and
                  l.straightevenexchange = 'N' )
         and l.customer_id=c.customer_id
        and l.product_id=p.product_id
        and rp.number_value = c.customer_id
        and ( rp.number_value4 = 0 or rp.number_value4 = dp.deliverypoint_id )
        and trunc(rp.number_value5) = bu.businessunit_id
        and bu.plant_id = pl.plant_id
        and ad.address_id = pl.address_id
        and rp.date_value1 between l.dateactive and l.dateinactive
        and rp.date_value1 between stl.dateactive and stl.dateinactive
        and (coalesce ((select sum(rqa.quantity)
              from   rentalqtyadjustment rqa
              where  rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
              and rqa.adjustmentdate < rp.date_value1),0)>0)
        and act.code not in ('TE','LW')
group by rp.reportparam_id
,        rp.copy_number
,        c.customer_id
,        c.customernumber
,        t.departmentnumber
,        dp.distributionpoint_id
,        dp.distributionpointnumber
,        p.code,pg.code,pg.productgroup_id, act.code, act.activity_id
,        sd.code
,        dp.deliverypoint_id
,        bu.description
,        pl.name
,        pl.phoneno
,        pl.faxno, pl.WEBSITE
,        ad.street
,        ad.zipcode
,        ad.city
,        delp.code,c.language_id, bu.legalentity_id, le.legalname
, leadd.street, leadd.zipcode, leadd.city, PL.CODE
union all
select   rp.reportparam_id
,        rp.copy_number
,        1 cpl
,        a.customernumber
,        a.name customername
,        insertspace_after_x_characters(to_char(a.customernumber),3) custnr
,        b.departmentnumber
,        b.description departmentname
,        c.distributionpoint_id
,        c.distributionpointnumber
,        c.description distributionpointnumbername
,        g.code productcode
,        ( select z.description
           from   product_desc z
           where  z.product_id = g.product_id
              and a.language_id = z.language_id ) productdesc
,        ( select max(plpc.customcode)
           from   productlistpercustomer plpc
           where  plpc.productlistpercustomer_id=e.productlistpercustomer_id ) customcode
,        ( select max(plpc.customdescription)
           from   productlistpercustomer plpc
           where  plpc.productlistpercustomer_id=e.productlistpercustomer_id ) customdescription
,      '*' sizecode
,        a.customer_id
,        dp.deliverypoint_id
,        ( select min(bu.code)
           from   customeractivities ca
       ,      activity act
       ,      businessunit bu
           where  ca.customer_id=a.customer_id
              and ca.activity_id=act.activity_id
              and act.code='BK'
              and ca.internalprocessingbu_id=bu.businessunit_id ) internalprocbu
,        bu.description bu_desc
,        pl.name plantname
,        pl.phoneno plantphone
,        pl.faxno plantfax, pl.WEBSITE PLANTWEBSITE
,        ad.street plantstreet
,        ad.zipcode plantzip
,        ad.city plantcity
,        dp.code delpointcode
,         pg.code  productgroup
,        ( select pgd.description  from productgroup_desc pgd  where pgd.productgroup_id = pg.productgroup_id
         and pgd.language_id = a.language_id) productgroupdesc
,         act.code  activitycode
,        ( select ad.description from   activity_desc ad  where   ad.activity_id = pg.activity_id
          and ad.language_id = a.language_id) activitydesc
, bu.Legalentity_Id, le.legalname LegalEntity_LegalName
, leadd.street LegalEntity_Street, leadd.zipcode LegalEntity_Zip, leadd.city LegalEntity_City
, case when pl.CODE = 'ARNO' then substr(pl.NAME, 25)
       when PL.CODE = 'CHEM' then substr(PL.NAME, 35)
       when PL.CODE = 'GRAZ' then substr(PL.NAME, 25)
       when PL.CODE = 'INZ' then substr(PL.NAME, 25)
       when PL.CODE = 'KRAM' then bu.Description--substr(PL.NAME, 25)
       when PL.CODE = 'LEOG' then substr(PL.NAME, 25)
       when PL.CODE = 'MATT' then substr(PL.NAME, 25)
       when PL.CODE = 'ORAD' then substr(PL.NAME, 27)
       when PL.CODE = 'PWSK' then substr(PL.NAME, 25)
       when PL.CODE = 'ROGA' then substr(PL.NAME, 36)
       when PL.CODE = 'SA14' then bu.Description--substr(PL.NAME, 25)
       when PL.CODE = 'SA22' then substr(PL.NAME, 25)
       when PL.CODE = 'SAWR' then substr(PL.NAME, 25)
       when PL.CODE = 'SCHI' then substr(PL.NAME, 25)
       when PL.CODE = 'SMA' then substr(PL.NAME, 25)
       when PL.CODE = 'SMB' then substr(PL.NAME, 20)
       when PL.CODE = 'SMHR' then substr(PL.NAME, 33)
       when PL.CODE = 'SMP' then substr(PL.NAME, 35)
       when PL.CODE = 'SMPL' then substr(PL.NAME, 31)
       when PL.CODE = 'SMRO' then substr(PL.NAME, 27)
       when PL.CODE = 'SMRS' then substr(PL.NAME, 31)
       when PL.CODE = 'SMS' then substr(PL.NAME, 25)
       when PL.CODE = 'SMSK' then substr(PL.NAME, 29)
       when PL.CODE = 'SMSL' then substr(PL.NAME, 36)
       when PL.CODE = 'SMTY' then substr(PL.NAME, 31)
       when PL.CODE = 'SMZL' then substr(PL.NAME, 25)
       when PL.CODE = 'SZOM' then substr(PL.NAME, 20)
else PL.NAME end PLANTNAME_PART2
from     customer a
,        department b
,        distributionpoint c
,        deliverypoint dp
,        productlistpercustomer e
,        address f
,        product g,productgroup pg,activity act
,        reportparam rp
,        businessunit bu
         left outer join legalentity le
              inner join address leadd on leadd.address_id = le.address_id
         on le.legalentity_id = bu.legalentity_id
,        plant pl
,        address ad,weareremployment we
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 e.customer_id = a.customer_id
     and e.product_id=g.product_id
     and g.productgroup_id=pg.productgroup_id
     and pg.activity_id=act.activity_id
     and g.typeofmerchandise = 2
     and we.distributionpoint_id = c.distributionpoint_id
     and exists(select 1 from   wearerinventory wi
            where wi.weareremployment_id=we.weareremployment_id
               and wi.product_id = g.product_id
               and wi.dateactive <= rp.date_value1
               and wi.dateinactive >= rp.date_value1
               and wi.circinventory+wi.freeofchargeqty> 0)
     and e.dateactive <= rp.date_value1
     and e.dateinactive > rp.date_value1
     and not exists ( select 1  from   productlistperdistribpoint plpd,  standarddeliveryline sdl
             where  plpd.distributionpoint_id = c.distributionpoint_id
                and plpd.productlistperdistribpoint_id=sdl.productlistperdistribpoint_id
                and sdl.productlistpercustomer_id=e.productlistpercustomer_id
                and plpd.product_id = g.product_id
                and e.soilcountmethod <> 0
                and e.straightevenexchange = 'N'
                and rp.date_value1 between sdl.dateactive and sdl.dateinactive )
     and e.dateactive <= rp.date_value1
     and e.dateinactive > rp.date_value1
     and ( b.active='Y' or c.active='Y' )
     and rp.number_value = a.customer_id
     and ( rp.number_value4 = 0 or rp.number_value4 = dp.deliverypoint_id )
     and trunc(rp.number_value5) = bu.businessunit_id
     and bu.plant_id = pl.plant_id
     and ad.address_id = pl.address_id
     and act.code not in ('TE','LW')

/
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 PLANT.CODE, PLANT.NAME, ADDRESS.STREET, ADDRESS.ZIPCODE, ADDRESS.CITY, ADDRESS.COUNTY,
  ADDRESS.STATE, COUNTRY.CODE countrycode, COUNTRY.DESCRIPTION countryname, PLANT.ACTIVE,
  HEADOFFICE.CODE headofficecode, HEADOFFICE.NAME headofficename, PLANT.PHONENO, PLANT.FAXNO,
  PLANT.EMAIL, PLANT.SYSTEMUSER_ID, PLANT.TIMESTAMP, PLANT.PLANT_ID, Z.VALUE WEIGHTUNIT
FROM PLANT, ADDRESS, COUNTRY,
  PLANT HEADOFFICE
    left outer join SYSTEMSETTING Z ON Z.PLANT_ID = HEADOFFICE.PLANT_ID AND Z.NAME = 'WEIGHTUNIT'
WHERE PLANT.ADDRESS_ID = ADDRESS.ADDRESS_ID
  and PLANT.COUNTRY_ID = COUNTRY.COUNTRY_ID
  and PLANT.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, NOTENUMBER, INTERNALBU_ID, INTERNALBU_CODE
, INTERNALBU_DESC, PROCESSBUSINESSUNIT_ID, PROCESSBU_CODE, PROCESSBU_DESC, PRODUCTIONDATE)
as select  -- 1 : pack
  1 linetype, 'Y' packProduct, depot.code depot, route.routenumber, upper(activity.code) activitycode
, ( select description from activity_desc where activity_desc.activity_id = activity.activity_id
  and activity_desc.language_id = languages.language_id ) activitydescription
, prd.code productcode, pk.deliverydate
, ( select day_desc.description from day_desc, day where pk.daynumber=day.daynumber
  and day_desc.day_id = day.day_id and day_desc.language_id = languages.language_id ) daydescription
, plantdepartment.code plantdepartmentCode ,plantdepartment.description plantdepartmentDescription
, ( select description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDescription
, sizedefinition.code sizecode, finishingmethod.code finishingmethodcode
, ( select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sizedefinition.sizedefinition_id
  and sdd.language_id = languages.language_id ) sizedesc
, ( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = finishingmethod.finishingmethod_id
  and fmd.language_id = languages.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 = plantdepartment.plant_id) ,productsize.packingamount) bundlesize
, productsize.theoreticalweight, prd.packingsequence, productgroup.code productgroupcode
, ( select description from productgroup_desc where productgroup_desc.productgroup_id = productgroup.productgroup_id
  and productgroup_desc.language_id = languages.language_id ) productgroupdescription
, route.route_id, route.plant_id, route.packingdeadline,languages.code languagecode
, (SELECT cu.customernumber FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customernumber,
(SELECT cu.name FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customername
, 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
from
  packingnote pk
    left outer join ( route left outer join depot on route.depot_id = depot.depot_id )
           on pk.route_id = route.route_id and route.active = 'Y'
    left outer join businessunit ibu on ibu.businessunit_id = pk.internalprocessingbu_id
, packingnoteline pkli, finishingmethod, sizedefinition
, product prd
    left outer join weighingcategory on prd.weighingcategory_id=weighingcategory.weighingcategory_id
, status,  plantdepartment, productgroup, productsize
, languages
, activity, businessunit pbu
where
    pk.status_id = status.status_id
    and status.statustype = 'PN'
        and status.code in ('10', '20')
and pk.plantdepartment_id = plantdepartment.plantdepartment_id
and pk.packingnote_id = pkli.packingnote_id
and pkli.product_id = prd.product_id
and pkli.sizedefinition_id = sizedefinition.sizedefinition_id
and pkli.finishingmethod_id = finishingmethod.finishingmethod_id
and pkli.sizedefinition_id = productsize.sizedefinition_id
    and productsize.product_id = pkli.product_id
and prd.productgroup_id = productgroup.productgroup_id
and productgroup.activity_id = activity.activity_id
and pbu.businessunit_id = pk.processbusinessunit_id
union all
select  -- 2 : content
  2 linetype, 'N' packProduct, depot.code depot, route.routenumber, upper(activity.code) activitycode
, ( select description from activity_desc where activity_desc.activity_id = activity.activity_id
  and activity_desc.language_id = languages.language_id ) activitydescription
, prd.code productcode--, CONCATENATE(' ',prd.code) productcode -- a space is required in front of contents by I-Tests 1 --now added the space inside the report
, pk.deliverydate
, ( select day_desc.description from day_desc, day where pk.daynumber=day.daynumber
  and day_desc.day_id = day.day_id and day_desc.language_id = languages.language_id ) daydescription
, plantdepartment.code plantdepartmentCode ,plantdepartment.description plantdepartmentDescription
, ( select description from product_desc where product_desc. product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDescription
, sizedefinition.code sizecode, finishingmethod.code finishingmethodcode
, ( select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sizedefinition.sizedefinition_id
  and sdd.language_id = languages.language_id ) sizedesc
, ( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = finishingmethod.finishingmethod_id
  and fmd.language_id = languages.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 = pkli.product_id
and ppss.sizedefinition_id = pkli.sizedefinition_id and ppss.plant_id = plantdepartment.plant_id) ,productsize.packingamount) bundlesize
, productsize.theoreticalweight, prd.packingsequence, productgroup.code productgroupcode
, ( select description from productgroup_desc where productgroup_desc.productgroup_id = productgroup.productgroup_id
  and productgroup_desc.language_id = languages.language_id ) productgroupdescription
, route.route_id, route.plant_id, route.packingdeadline,languages.code languagecode
, (SELECT cu.customernumber FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customernumber,
(SELECT cu.name FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customername
, 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
from
  packingnote pk
    left outer join ( route left outer join depot on route.depot_id = depot.depot_id )
           on pk.route_id = route.route_id and route.active = 'Y'
    left outer join businessunit ibu on ibu.businessunit_id = pk.internalprocessingbu_id
, packingnoteline pkli, packingnotelinecontent pkc, finishingmethod, sizedefinition
, product prd
    left outer join weighingcategory on prd.weighingcategory_id=weighingcategory.weighingcategory_id
, status,  plantdepartment, productgroup, productsize
, languages
, activity, businessunit pbu
where
    pk.status_id = status.status_id
    and status.statustype = 'PN'
        and status.code in ('10', '20')
and pk.plantdepartment_id = plantdepartment.plantdepartment_id
and pk.packingnote_id = pkli.packingnote_id
and pkli.packingnoteline_id = pkc.packingnoteline_id
and pkc.product_id = prd.product_id
and pkc.sizedefinition_id = sizedefinition.sizedefinition_id
and pkc.finishingmethod_id = finishingmethod.finishingmethod_id
and pkc.sizedefinition_id = productsize.sizedefinition_id
    and productsize.product_id = pkc.product_id
and prd.productgroup_id = productgroup.productgroup_id
and productgroup.activity_id = activity.activity_id
and pbu.businessunit_id = pk.processbusinessunit_id

/
create or replace view V_PLANTMERCHANDISEREQ_AMM
 (LINETYPE, PACKPRODUCT, DEPOT, ROUTENUMBER, ACTIVITYCODE, ACTIVITYDESCRIPTION, PRODUCTCODE, DELIVERYDATE, DAYDESCRIPTION, PLANTDEPARTMENTCODE, PLANTDEPARTMENTDESCRIPTION, PRODUCTDESCRIPTION, SIZECODE, FINISHINGMETHODCODE, SIZEDESC, FINISHINGMETHODDESC, TOTALQTY, BUNDLESIZE, THEORETICALWEIGHT, PACKINGSEQUENCE, PRODUCTGROUPCODE, FULLLOAD, PRODUCTGROUPDESCRIPTION, ROUTE_ID, PLANT_ID, PACKINGDEADLINE, LANGUAGECODE, CUSTOMERNUMBER, CUSTOMERNAME, NOTENUMBER, INTERNALBU_ID
, INTERNALBU_CODE, INTERNALBU_DESC, PROCESSBUSINESSUNIT_ID, PROCESSBU_CODE, PROCESSBU_DESC, PRODUCTIONDATE, DRIVINGDATE, SUPPPRODCODE)
as select  -- 1 : pack
  1 linetype, 'Y' packProduct, depot.code depot, route.routenumber, upper(activity.code) activitycode
, ( select description from activity_desc where activity_desc.activity_id = activity.activity_id
  and activity_desc.language_id = languages.language_id ) activitydescription
, prd.code productcode, pk.deliverydate
, ( select day_desc.description from day_desc, day where pk.daynumber=day.daynumber
  and day_desc.day_id = day.day_id and day_desc.language_id = languages.language_id ) daydescription
, plantdepartment.code plantdepartmentCode ,plantdepartment.description plantdepartmentDescription
, ( select description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDescription
, sizedefinition.code sizecode, finishingmethod.code finishingmethodcode
, ( select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sizedefinition.sizedefinition_id
  and sdd.language_id = languages.language_id ) sizedesc
, ( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = finishingmethod.finishingmethod_id
  and fmd.language_id = languages.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 = plantdepartment.plant_id) ,productsize.packingamount) bundlesize
, productsize.theoreticalweight, prd.packingsequence, productgroup.code productgroupcode, productgroup.fullload
, ( select description from productgroup_desc where productgroup_desc.productgroup_id = productgroup.productgroup_id
  and productgroup_desc.language_id = languages.language_id ) productgroupdescription
, route.route_id, route.plant_id, route.packingdeadline,languages.code languagecode
, (SELECT cu.customernumber FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customernumber,
(SELECT cu.name FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customername
, 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
, (SELECT rc.drivingdate from routecontrol rc where rc.routecontrol_id = pk.routecontrol_id) drivingdate
, (case when 'CA' = (select co.code from country co, plant pl
        where pl.plant_id = pbu.plant_id and co.country_id = pl.country_id)
  then (select max(dff.stringvalue) from dialogflexfields dff
         inner join characteristic ch on ch.characteristic_id = dff.characteristic_id
         inner join characteristicstempline cfl
               inner join characteristicstemplate cft on cft.characteristicstemplate_id = cfl.characteristicstemplate_id
         on cfl.characteristic_id = dff.characteristic_id
         where ch.dialog_id = 41 and ch.code = 'CASUP' and cft.code = 'SUPP' and dff.entity_id = prd.Product_Id) --CA code
  else (select max(dff.stringvalue) from dialogflexfields dff
         inner join characteristic ch on ch.characteristic_id = dff.characteristic_id
         inner join characteristicstempline cfl
               inner join characteristicstemplate cft on cft.characteristicstemplate_id = cfl.characteristicstemplate_id
         on cfl.characteristic_id = dff.characteristic_id
         where ch.dialog_id = 41 and ch.code = 'USSUP' and cft.code = 'SUPP' and dff.entity_id = prd.Product_Id) --US is the default code
    end) SuppProdCode
from
  packingnote pk
    left outer join ( route left outer join depot on route.depot_id = depot.depot_id )
           on pk.route_id = route.route_id and route.active = 'Y'
    left outer join businessunit ibu on ibu.businessunit_id = pk.internalprocessingbu_id
, packingnoteline pkli, finishingmethod, sizedefinition
, product prd
    left outer join weighingcategory on prd.weighingcategory_id=weighingcategory.weighingcategory_id
, status,  plantdepartment, productgroup, productsize
, languages
, activity, businessunit pbu
where
    pk.status_id = status.status_id
    and status.statustype = 'PN'
        and status.code in ('10', '20')
and pk.plantdepartment_id = plantdepartment.plantdepartment_id
and pk.packingnote_id = pkli.packingnote_id
and pkli.product_id = prd.product_id
and pkli.sizedefinition_id = sizedefinition.sizedefinition_id
and pkli.finishingmethod_id = finishingmethod.finishingmethod_id
and pkli.sizedefinition_id = productsize.sizedefinition_id
    and productsize.product_id = pkli.product_id
and prd.productgroup_id = productgroup.productgroup_id
and productgroup.activity_id = activity.activity_id
and pbu.businessunit_id = pk.processbusinessunit_id
union all
select  -- 2 : content
  2 linetype, 'N' packProduct, depot.code depot, route.routenumber, upper(activity.code) activitycode
, ( select description from activity_desc where activity_desc.activity_id = activity.activity_id
  and activity_desc.language_id = languages.language_id ) activitydescription
, prd.code productcode--, CONCATENATE(' ',prd.code) productcode -- a space is required in front of contents by I-Tests 1 --now added the space inside the report
, pk.deliverydate
, ( select day_desc.description from day_desc, day where pk.daynumber=day.daynumber
  and day_desc.day_id = day.day_id and day_desc.language_id = languages.language_id ) daydescription
, plantdepartment.code plantdepartmentCode ,plantdepartment.description plantdepartmentDescription
, ( select description from product_desc where product_desc. product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDescription
, sizedefinition.code sizecode, finishingmethod.code finishingmethodcode
, ( select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sizedefinition.sizedefinition_id
  and sdd.language_id = languages.language_id ) sizedesc
, ( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = finishingmethod.finishingmethod_id
  and fmd.language_id = languages.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 = pkli.product_id
and ppss.sizedefinition_id = pkli.sizedefinition_id and ppss.plant_id = plantdepartment.plant_id) ,productsize.packingamount) bundlesize
, productsize.theoreticalweight, prd.packingsequence, productgroup.code productgroupcode, productgroup.fullload
, ( select description from productgroup_desc where productgroup_desc.productgroup_id = productgroup.productgroup_id
  and productgroup_desc.language_id = languages.language_id ) productgroupdescription
, route.route_id, route.plant_id, route.packingdeadline,languages.code languagecode
, (SELECT cu.customernumber FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customernumber,
(SELECT cu.name FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customername
, 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
, (SELECT rc.drivingdate from routecontrol rc where rc.routecontrol_id = pk.routecontrol_id) drivingdate
, (case when 'CA' = (select co.code from country co, plant pl
        where pl.plant_id = pbu.plant_id and co.country_id = pl.country_id)
  then (select max(dff.stringvalue) from dialogflexfields dff
         inner join characteristic ch on ch.characteristic_id = dff.characteristic_id
         inner join characteristicstempline cfl
               inner join characteristicstemplate cft on cft.characteristicstemplate_id = cfl.characteristicstemplate_id
         on cfl.characteristic_id = dff.characteristic_id
         where ch.dialog_id = 41 and ch.code = 'CASUP' and cft.code = 'SUPP' and dff.entity_id = prd.Product_Id) --CA code
  else (select max(dff.stringvalue) from dialogflexfields dff
         inner join characteristic ch on ch.characteristic_id = dff.characteristic_id
         inner join characteristicstempline cfl
               inner join characteristicstemplate cft on cft.characteristicstemplate_id = cfl.characteristicstemplate_id
         on cfl.characteristic_id = dff.characteristic_id
         where ch.dialog_id = 41 and ch.code = 'USSUP' and cft.code = 'SUPP' and dff.entity_id = prd.Product_Id) --US is the default code
    end) SuppProdCode
from
  packingnote pk
    left outer join ( route left outer join depot on route.depot_id = depot.depot_id )
           on pk.route_id = route.route_id and route.active = 'Y'
    left outer join businessunit ibu on ibu.businessunit_id = pk.internalprocessingbu_id
, packingnoteline pkli, packingnotelinecontent pkc, finishingmethod, sizedefinition
, product prd
    left outer join weighingcategory on prd.weighingcategory_id=weighingcategory.weighingcategory_id
, status,  plantdepartment, productgroup, productsize
, languages
, activity, businessunit pbu
where
    pk.status_id = status.status_id
    and status.statustype = 'PN'
        and status.code in ('10', '20')
and pk.plantdepartment_id = plantdepartment.plantdepartment_id
and pk.packingnote_id = pkli.packingnote_id
and pkli.packingnoteline_id = pkc.packingnoteline_id
and pkc.product_id = prd.product_id
and pkc.sizedefinition_id = sizedefinition.sizedefinition_id
and pkc.finishingmethod_id = finishingmethod.finishingmethod_id
and pkc.sizedefinition_id = productsize.sizedefinition_id
    and productsize.product_id = pkc.product_id
and prd.productgroup_id = productgroup.productgroup_id
and productgroup.activity_id = activity.activity_id
and pbu.businessunit_id = pk.processbusinessunit_id

/
create or replace view V_PLANTMERCHANDISEREQ_LLG
 (LINETYPE, PACKPRODUCT, DEPOT, ROUTENUMBER, ACTIVITYCODE, ACTIVITYDESCRIPTION, PRODUCTCODE, DELIVERYDATE, DAYDESCRIPTION, PLANTDEPARTMENTCODE, PLANTDEPARTMENTDESCRIPTION, PRODUCTDESCRIPTION, SIZECODE, FINISHINGMETHODCODE, TOTALQTY, PACKEDQTY, THEORETICALWEIGHT, PACKINGSEQUENCE, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PROCESSBUSINESSUNIT_ID, ROUTE_ID, PLANT_ID, LANGUAGECODE, CUSTOMERNUMBER, NOTENUMBER, CUSTOMERNAME, PRODUCTIONDATE)
as select  -- 1 : pack
  1 linetype, 'Y' packProduct, depot.code depot, route.routenumber, upper(activity.code) activitycode
, ( select description from activity_desc where activity_desc.activity_id = activity.activity_id
  and activity_desc.language_id = languages.language_id ) activitydescription
, prd.code productcode, pk.deliverydate
, ( select day_desc.description from day_desc, day where pk.daynumber=day.daynumber
  and day_desc.day_id = day.day_id and day_desc.language_id = languages.language_id ) daydescription
, plantdepartment.code plantdepartmentCode ,plantdepartment.description plantdepartmentDescription
, ( select description from product_desc where product_desc. product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDescription
, sizedefinition.code sizecode, finishingmethod.code finishingmethodcode
, (CASE WHEN pk.origin = 7 THEN pkli.deliveredamount
ELSE  pkli.tobedeliveredamount END) totalqty
, (case when status.code = 30 then pkli.deliveredamount else 0 end) packedqty
/*, 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 = plantdepartment.plant_id) ,productsize.packingamount) bundlesize*/
, productsize.theoreticalweight, prd.packingsequence, productgroup.code productgroupcode
, ( select description from productgroup_desc where productgroup_desc.productgroup_id = productgroup.productgroup_id
  and productgroup_desc.language_id = languages.language_id ) productgroupdescription
, pk.processbusinessunit_id, route.route_id, route.plant_id,languages.code languagecode
, (SELECT cu.customernumber FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customernumber
, pk.notenumber,
(SELECT cu.name FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customername
, pk.productiondate
from
  packingnote pk
    left outer join ( route left outer join depot on route.depot_id = depot.depot_id )
           on pk.route_id = route.route_id and route.active = 'Y'
, packingnoteline pkli, finishingmethod, sizedefinition
, product prd
    --left outer join weighingcategory on prd.weighingcategory_id=weighingcategory.weighingcategory_id
, status
,  plantdepartment, productgroup, productsize
, languages
, activity
where
    pk.status_id = status.status_id
    and status.statustype = 'PN'
        and status.code in ('10', '20', '30')
and
pk.plantdepartment_id = plantdepartment.plantdepartment_id
and pk.packingnote_id = pkli.packingnote_id
and pkli.product_id = prd.product_id
and pkli.sizedefinition_id = sizedefinition.sizedefinition_id
and pkli.finishingmethod_id = finishingmethod.finishingmethod_id
and pkli.sizedefinition_id = productsize.sizedefinition_id
    and productsize.product_id = pkli.product_id
and prd.productgroup_id = productgroup.productgroup_id
and productgroup.activity_id = activity.activity_id
union all
select  -- 2 : content
  2 linetype, 'N' packProduct, depot.code depot, route.routenumber, upper(activity.code) activitycode
, ( select description from activity_desc where activity_desc.activity_id = activity.activity_id
  and activity_desc.language_id = languages.language_id ) activitydescription
, prd.code productcode--, CONCATENATE(' ',prd.code) productcode -- a space is required in front of contents by I-Tests 1 --now added the space inside the report
, pk.deliverydate
, ( select day_desc.description from day_desc, day where pk.daynumber=day.daynumber
  and day_desc.day_id = day.day_id and day_desc.language_id = languages.language_id ) daydescription
, plantdepartment.code plantdepartmentCode ,plantdepartment.description plantdepartmentDescription
, ( select description from product_desc where product_desc. product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDescription
, sizedefinition.code sizecode, finishingmethod.code finishingmethodcode
, (CASE WHEN pk.origin = 7 THEN pkli.deliveredamount*pkc.Quantity
ELSE pkli.tobedeliveredamount*pkc.Quantity END) totalqty
, (case when status.code = 30 then pkli.deliveredamount else 0 end) packedqty
/*, 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 = plantdepartment.plant_id) ,productsize.packingamount) bundlesize*/
, productsize.theoreticalweight, prd.packingsequence, productgroup.code productgroupcode
, ( select description from productgroup_desc where productgroup_desc.productgroup_id = productgroup.productgroup_id
  and productgroup_desc.language_id = languages.language_id ) productgroupdescription
, pk.processbusinessunit_id, route.route_id, route.plant_id,languages.code languagecode
, (SELECT cu.customernumber FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customernumber
, pk.notenumber,
(SELECT cu.name FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customername
, pk.productiondate
from
  packingnote pk
    left outer join ( route left outer join depot on route.depot_id = depot.depot_id )
           on pk.route_id = route.route_id and route.active = 'Y'
, packingnoteline pkli, packingnotelinecontent pkc, finishingmethod, sizedefinition
, product prd
   -- left outer join weighingcategory on prd.weighingcategory_id=weighingcategory.weighingcategory_id
, status
,  plantdepartment, productgroup, productsize
, languages
, activity
where
    pk.status_id = status.status_id
    and status.statustype = 'PN'
        and status.code in ('10', '20', '30')
and
pk.plantdepartment_id = plantdepartment.plantdepartment_id
and pk.packingnote_id = pkli.packingnote_id
and pkli.packingnoteline_id = pkc.packingnoteline_id
and pkc.product_id = prd.product_id
and pkc.sizedefinition_id = sizedefinition.sizedefinition_id
and pkc.finishingmethod_id = finishingmethod.finishingmethod_id
and pkc.sizedefinition_id = productsize.sizedefinition_id
    and productsize.product_id = pkc.product_id
and prd.productgroup_id = productgroup.productgroup_id
and productgroup.activity_id = activity.activity_id

/
create or replace view V_PLANTMERCHANDISEREQ_SMG
 (LINETYPE, PACKPRODUCT, DEPOT, ROUTENUMBER, ACTIVITYCODE, ACTIVITYDESCRIPTION, PRODUCTCODE, DELIVERYDATE, DAYDESCRIPTION, PLANTDEPARTMENTCODE, PLANTDEPARTMENTDESCRIPTION, PRODUCTDESCRIPTION, SIZECODE, FINISHINGMETHODCODE, TOTALQTY, PACKEDQTY, THEORETICALWEIGHT, PACKINGSEQUENCE, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, ROUTE_ID, PLANT_ID, LANGUAGECODE, CUSTOMERNUMBER, NOTENUMBER, INTERNALBU_ID, INTERNALBU_CODE, INTERNALBU_DESC, PROCESSBUSINESSUNIT_ID, PROCESSBU_CODE
, PROCESSBU_DESC, CUSTOMERNAME, PRODUCTIONDATE, STATUS_CODE)
as select  -- 1 : pack
  1 linetype, 'Y' packProduct, depot.code depot, route.routenumber, upper(activity.code) activitycode
, ( select description from activity_desc where activity_desc.activity_id = activity.activity_id
  and activity_desc.language_id = languages.language_id ) activitydescription
, prd.code productcode, pk.deliverydate
, ( select day_desc.description from day_desc, day where pk.daynumber=day.daynumber
  and day_desc.day_id = day.day_id and day_desc.language_id = languages.language_id ) daydescription
, plantdepartment.code plantdepartmentCode ,plantdepartment.description plantdepartmentDescription
, ( select description from product_desc where product_desc. product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDescription
, sizedefinition.code sizecode, finishingmethod.code finishingmethodcode
, (CASE WHEN pk.origin = 7 THEN pkli.deliveredamount
ELSE  pkli.tobedeliveredamount END) totalqty
, (case when status.code in ('20', '30') then pkli.deliveredamount else 0 end) packedqty
, productsize.theoreticalweight, prd.packingsequence, productgroup.code productgroupcode
, ( select description from productgroup_desc where productgroup_desc.productgroup_id = productgroup.productgroup_id
  and productgroup_desc.language_id = languages.language_id ) productgroupdescription
, route.route_id, route.plant_id,languages.code languagecode
, (SELECT cu.customernumber FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customernumber
, 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,
(SELECT cu.name FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customername
, pk.productiondate,  status.code  status_code
from
  packingnote pk
    left outer join ( route left outer join depot on route.depot_id = depot.depot_id )
           on pk.route_id = route.route_id and route.active = 'Y'
    left outer join businessunit ibu on ibu.businessunit_id = pk.internalprocessingbu_id
, packingnoteline pkli, finishingmethod, sizedefinition
, product prd
, status
, plantdepartment, productgroup, productsize
, languages
, activity
, businessunit pbu
where pk.status_id = status.status_id
        and status.statustype = 'PN'
        and status.code in ('10', '20', '30')
and pk.plantdepartment_id = plantdepartment.plantdepartment_id
and pk.packingnote_id = pkli.packingnote_id
and pkli.product_id = prd.product_id
and pkli.sizedefinition_id = sizedefinition.sizedefinition_id
and pkli.finishingmethod_id = finishingmethod.finishingmethod_id
and pkli.sizedefinition_id = productsize.sizedefinition_id
    and productsize.product_id = pkli.product_id
and prd.productgroup_id = productgroup.productgroup_id
and productgroup.activity_id = activity.activity_id
and pbu.businessunit_id = pk.processbusinessunit_id
union all
select  -- 2 : content
  2 linetype, 'N' packProduct, depot.code depot, route.routenumber, upper(activity.code) activitycode
, ( select description from activity_desc where activity_desc.activity_id = activity.activity_id
  and activity_desc.language_id = languages.language_id ) activitydescription
, prd.code productcode, pk.deliverydate
, ( select day_desc.description from day_desc, day where pk.daynumber=day.daynumber
  and day_desc.day_id = day.day_id and day_desc.language_id = languages.language_id ) daydescription
, plantdepartment.code plantdepartmentCode ,plantdepartment.description plantdepartmentDescription
, ( select description from product_desc where product_desc. product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDescription
, sizedefinition.code sizecode, finishingmethod.code finishingmethodcode
, (CASE WHEN pk.origin = 7 THEN pkli.deliveredamount*pkc.Quantity
ELSE pkli.tobedeliveredamount*pkc.Quantity END) totalqty
, (case when status.code in ('20', '30') then pkli.deliveredamount else 0 end) packedqty
, productsize.theoreticalweight, prd.packingsequence, productgroup.code productgroupcode
, ( select description from productgroup_desc where productgroup_desc.productgroup_id = productgroup.productgroup_id
  and productgroup_desc.language_id = languages.language_id ) productgroupdescription
, route.route_id, route.plant_id,languages.code languagecode
, (SELECT cu.customernumber FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customernumber
, 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,
(SELECT cu.name FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customername
, pk.productiondate,  status.code  status_code
from
  packingnote pk
    left outer join ( route left outer join depot on route.depot_id = depot.depot_id )
           on pk.route_id = route.route_id and route.active = 'Y'
    left outer join businessunit ibu on ibu.businessunit_id = pk.internalprocessingbu_id
, packingnoteline pkli, packingnotelinecontent pkc, finishingmethod, sizedefinition
, product prd
, status
,  plantdepartment, productgroup, productsize
, languages
, activity
, businessunit pbu
where pk.status_id = status.status_id
        and status.statustype = 'PN'
        and status.code in ('10', '20', '30')
and pk.plantdepartment_id = plantdepartment.plantdepartment_id
and pk.packingnote_id = pkli.packingnote_id
and pkli.packingnoteline_id = pkc.packingnoteline_id
and pkc.product_id = prd.product_id
and pkc.sizedefinition_id = sizedefinition.sizedefinition_id
and pkc.finishingmethod_id = finishingmethod.finishingmethod_id
and pkc.sizedefinition_id = productsize.sizedefinition_id
    and productsize.product_id = pkc.product_id
and prd.productgroup_id = productgroup.productgroup_id
and productgroup.activity_id = activity.activity_id
and pbu.businessunit_id = pk.processbusinessunit_id

/
create or replace view V_PLANTMERCHREQUIREMENT_DFD
 (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, NOTENUMBER, INTERNALBU_ID, INTERNALBU_CODE
, INTERNALBU_DESC, PROCESSBUSINESSUNIT_ID, PROCESSBU_CODE, PROCESSBU_DESC, PRODUCTIONDATE)
as select  -- 1 : pack
  1 linetype, 'Y' packProduct, depot.code depot, route.routenumber, upper(activity.code) activitycode
, ( select description from activity_desc where activity_desc.activity_id = activity.activity_id
  and activity_desc.language_id = languages.language_id ) activitydescription
, prd.code productcode, pk.deliverydate
, ( select day_desc.description from day_desc, day where pk.daynumber=day.daynumber
  and day_desc.day_id = day.day_id and day_desc.language_id = languages.language_id ) daydescription
, plantdepartment.code plantdepartmentCode ,plantdepartment.description plantdepartmentDescription
, ( select description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDescription
, sizedefinition.code sizecode, finishingmethod.code finishingmethodcode
, ( select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sizedefinition.sizedefinition_id
  and sdd.language_id = languages.language_id ) sizedesc
, ( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = finishingmethod.finishingmethod_id
  and fmd.language_id = languages.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 = plantdepartment.plant_id) ,productsize.packingamount) bundlesize
, productsize.theoreticalweight, prd.packingsequence, productgroup.code productgroupcode
, ( select description from productgroup_desc where productgroup_desc.productgroup_id = productgroup.productgroup_id
  and productgroup_desc.language_id = languages.language_id ) productgroupdescription
, route.route_id, route.plant_id, route.packingdeadline,languages.code languagecode
, (SELECT cu.customernumber FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customernumber,
(SELECT cu.name FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customername
, 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
from
  packingnote pk
    left outer join ( route left outer join depot on route.depot_id = depot.depot_id )
           on pk.route_id = route.route_id and route.active = 'Y'
    left outer join businessunit ibu on ibu.businessunit_id = pk.internalprocessingbu_id
, packingnoteline pkli, finishingmethod, sizedefinition
, product prd
    left outer join weighingcategory on prd.weighingcategory_id=weighingcategory.weighingcategory_id
, status,  plantdepartment, productgroup, productsize
, languages
, activity, businessunit pbu
where
    pk.status_id = status.status_id
    and status.statustype = 'PN'
        and status.code in ('10', '20','30')
and pk.plantdepartment_id = plantdepartment.plantdepartment_id
and pk.packingnote_id = pkli.packingnote_id
and pkli.product_id = prd.product_id
and pkli.sizedefinition_id = sizedefinition.sizedefinition_id
and pkli.finishingmethod_id = finishingmethod.finishingmethod_id
and pkli.sizedefinition_id = productsize.sizedefinition_id
    and productsize.product_id = pkli.product_id
and prd.productgroup_id = productgroup.productgroup_id
and productgroup.activity_id = activity.activity_id
and pbu.businessunit_id = pk.processbusinessunit_id
union all
select  -- 2 : content
  2 linetype, 'N' packProduct, depot.code depot, route.routenumber, upper(activity.code) activitycode
, ( select description from activity_desc where activity_desc.activity_id = activity.activity_id
  and activity_desc.language_id = languages.language_id ) activitydescription
, prd.code productcode--, CONCATENATE(' ',prd.code) productcode -- a space is required in front of contents by I-Tests 1 --now added the space inside the report
, pk.deliverydate
, ( select day_desc.description from day_desc, day where pk.daynumber=day.daynumber
  and day_desc.day_id = day.day_id and day_desc.language_id = languages.language_id ) daydescription
, plantdepartment.code plantdepartmentCode ,plantdepartment.description plantdepartmentDescription
, ( select description from product_desc where product_desc. product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDescription
, sizedefinition.code sizecode, finishingmethod.code finishingmethodcode
, ( select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sizedefinition.sizedefinition_id
  and sdd.language_id = languages.language_id ) sizedesc
, ( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = finishingmethod.finishingmethod_id
  and fmd.language_id = languages.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 = pkli.product_id
and ppss.sizedefinition_id = pkli.sizedefinition_id and ppss.plant_id = plantdepartment.plant_id) ,productsize.packingamount) bundlesize
, productsize.theoreticalweight, prd.packingsequence, productgroup.code productgroupcode
, ( select description from productgroup_desc where productgroup_desc.productgroup_id = productgroup.productgroup_id
  and productgroup_desc.language_id = languages.language_id ) productgroupdescription
, route.route_id, route.plant_id, route.packingdeadline,languages.code languagecode
, (SELECT cu.customernumber FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customernumber,
(SELECT cu.name FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customername
, 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
from
  packingnote pk
    left outer join ( route left outer join depot on route.depot_id = depot.depot_id )
           on pk.route_id = route.route_id and route.active = 'Y'
    left outer join businessunit ibu on ibu.businessunit_id = pk.internalprocessingbu_id
, packingnoteline pkli, packingnotelinecontent pkc, finishingmethod, sizedefinition
, product prd
    left outer join weighingcategory on prd.weighingcategory_id=weighingcategory.weighingcategory_id
, status,  plantdepartment, productgroup, productsize
, languages
, activity, businessunit pbu
where
    pk.status_id = status.status_id
    and status.statustype = 'PN'
        and status.code in ('10', '20', '30')
and pk.plantdepartment_id = plantdepartment.plantdepartment_id
and pk.packingnote_id = pkli.packingnote_id
and pkli.packingnoteline_id = pkc.packingnoteline_id
and pkc.product_id = prd.product_id
and pkc.sizedefinition_id = sizedefinition.sizedefinition_id
and pkc.finishingmethod_id = finishingmethod.finishingmethod_id
and pkc.sizedefinition_id = productsize.sizedefinition_id
    and productsize.product_id = pkc.product_id
and prd.productgroup_id = productgroup.productgroup_id
and productgroup.activity_id = activity.activity_id
and pbu.businessunit_id = pk.processbusinessunit_id

/
create or replace view V_PLANTMERCHREQUIREMENT_ECL
 (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, NOTENUMBER, INTERNALBU_ID, INTERNALBU_CODE
, INTERNALBU_DESC, PROCESSBUSINESSUNIT_ID, PROCESSBU_CODE, PROCESSBU_DESC, PRODUCTIONDATE, OUSTANDINGDV)
as select  -- 1 : pack
  1 linetype, 'Y' packProduct, depot.code depot, route.routenumber, upper(activity.code) activitycode
, ( select description from activity_desc where activity_desc.activity_id = activity.activity_id
  and activity_desc.language_id = languages.language_id ) activitydescription
, prd.code productcode, pk.deliverydate
, ( select day_desc.description from day_desc, day where pk.daynumber=day.daynumber
  and day_desc.day_id = day.day_id and day_desc.language_id = languages.language_id ) daydescription
, plantdepartment.code plantdepartmentCode ,plantdepartment.description plantdepartmentDescription
, ( select description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDescription
, sizedefinition.code sizecode, finishingmethod.code finishingmethodcode
, ( select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sizedefinition.sizedefinition_id
  and sdd.language_id = languages.language_id ) sizedesc
, ( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = finishingmethod.finishingmethod_id
  and fmd.language_id = languages.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 = plantdepartment.plant_id) ,productsize.packingamount) bundlesize
, productsize.theoreticalweight, prd.packingsequence, productgroup.code productgroupcode
, ( select description from productgroup_desc where productgroup_desc.productgroup_id = productgroup.productgroup_id
  and productgroup_desc.language_id = languages.language_id ) productgroupdescription
, route.route_id, route.plant_id, route.packingdeadline,languages.code languagecode
, (SELECT cu.customernumber FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customernumber,
(SELECT cu.name FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customername
, 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,
(select count(1) from deliveryvariations dv where dv.packingnote_id is null and dv.deliverydate<= pk.deliverydate) oustandingdv
from
  packingnote pk
    left outer join ( route left outer join depot on route.depot_id = depot.depot_id )
           on pk.route_id = route.route_id and route.active = 'Y'
    left outer join businessunit ibu on ibu.businessunit_id = pk.internalprocessingbu_id
, packingnoteline pkli, finishingmethod, sizedefinition
, product prd
    left outer join weighingcategory on prd.weighingcategory_id=weighingcategory.weighingcategory_id
, status,  plantdepartment, productgroup, productsize
, languages
, activity, businessunit pbu
where
    pk.status_id = status.status_id
    and status.statustype = 'PN'
        and status.code in ('10', '20')
and pk.plantdepartment_id = plantdepartment.plantdepartment_id
and pk.packingnote_id = pkli.packingnote_id
and pkli.product_id = prd.product_id
and pkli.sizedefinition_id = sizedefinition.sizedefinition_id
and pkli.finishingmethod_id = finishingmethod.finishingmethod_id
and pkli.sizedefinition_id = productsize.sizedefinition_id
    and productsize.product_id = pkli.product_id
and prd.productgroup_id = productgroup.productgroup_id
and productgroup.activity_id = activity.activity_id
and pbu.businessunit_id = pk.processbusinessunit_id
union all
select  -- 2 : content
  2 linetype, 'N' packProduct, depot.code depot, route.routenumber, upper(activity.code) activitycode
, ( select description from activity_desc where activity_desc.activity_id = activity.activity_id
  and activity_desc.language_id = languages.language_id ) activitydescription
, prd.code productcode--, CONCATENATE(' ',prd.code) productcode -- a space is required in front of contents by I-Tests 1 --now added the space inside the report
, pk.deliverydate
, ( select day_desc.description from day_desc, day where pk.daynumber=day.daynumber
  and day_desc.day_id = day.day_id and day_desc.language_id = languages.language_id ) daydescription
, plantdepartment.code plantdepartmentCode ,plantdepartment.description plantdepartmentDescription
, ( select description from product_desc where product_desc. product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productDescription
, sizedefinition.code sizecode, finishingmethod.code finishingmethodcode
, ( select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sizedefinition.sizedefinition_id
  and sdd.language_id = languages.language_id ) sizedesc
, ( select fmd.description from finishingmethod_desc fmd where fmd.finishingmethod_id = finishingmethod.finishingmethod_id
  and fmd.language_id = languages.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 = pkli.product_id
and ppss.sizedefinition_id = pkli.sizedefinition_id and ppss.plant_id = plantdepartment.plant_id) ,productsize.packingamount) bundlesize
, productsize.theoreticalweight, prd.packingsequence, productgroup.code productgroupcode
, ( select description from productgroup_desc where productgroup_desc.productgroup_id = productgroup.productgroup_id
  and productgroup_desc.language_id = languages.language_id ) productgroupdescription
, route.route_id, route.plant_id, route.packingdeadline,languages.code languagecode
, (SELECT cu.customernumber FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customernumber,
(SELECT cu.name FROM distributionpoint dp, department de, customer cu WHERE pk.distributionpoint_id = dp.distributionpoint_id
AND dp.department_id = de.department_id AND de.customer_id = cu.customer_id) customername
, 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, (select count(1) from deliveryvariations dv where dv.packingnote_id is null and dv.deliverydate<= pk.deliverydate) oustandingdv
from
  packingnote pk
    left outer join ( route left outer join depot on route.depot_id = depot.depot_id )
           on pk.route_id = route.route_id and route.active = 'Y'
    left outer join businessunit ibu on ibu.businessunit_id = pk.internalprocessingbu_id
, packingnoteline pkli, packingnotelinecontent pkc, finishingmethod, sizedefinition
, product prd
    left outer join weighingcategory on prd.weighingcategory_id=weighingcategory.weighingcategory_id
, status,  plantdepartment, productgroup, productsize
, languages
, activity, businessunit pbu
where
    pk.status_id = status.status_id
    and status.statustype = 'PN'
        and status.code in ('10', '20')
and pk.plantdepartment_id = plantdepartment.plantdepartment_id
and pk.packingnote_id = pkli.packingnote_id
and pkli.packingnoteline_id = pkc.packingnoteline_id
and pkc.product_id = prd.product_id
and pkc.sizedefinition_id = sizedefinition.sizedefinition_id
and pkc.finishingmethod_id = finishingmethod.finishingmethod_id
and pkc.sizedefinition_id = productsize.sizedefinition_id
    and productsize.product_id = pkc.product_id
and prd.productgroup_id = productgroup.productgroup_id
and productgroup.activity_id = activity.activity_id
and pbu.businessunit_id = pk.processbusinessunit_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
  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
, weighingcategory_link.code weighingcatCode
, ( select weighingcategory_link_desc.description from weighingcategory_link_desc
  where weighingcategory_link_desc.weighingcategory_link_id = weighinghistory.weighingcategory_link_id
  and weighingcategory_link_desc.language_id = languages.language_id ) weighingcategorydescription
, weighinghistory.weighingdate
, weighinghistory.year, weighinghistory.week, weighinghistory.daynumber
, weighinghistory.year*100 + weighinghistory.week yearweek
, month(weighinghistory.weighingdate) realmonth
, year(weighinghistory.weighingdate) realyear
, weighinghistory.soilweight, weighinghistory.cleanweight
,  weighinghistory.systemuser_id, weighinghistory.timestamp
, 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 '' 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_PLANT_LOGO_AMM
 (NAME, PLANT_ID, LOGO, LOGOCODE, BUSINESSUNIT_ID, BUSINESSUNIT_CODE)
as select s.name, s.plant_id,
       case
         when s.value = '201' then 'Canada'
         when s.value = '221' then 'Quebec'
         else 'AmeriPride'
       end as logo,
    to_number(s.value) as logocode,
    b.businessunit_id,
    b.code as businessunit_code
from systemsetting s, businessunit b
where s.plant_id = b.plant_id
  and s.name     = 'COMPANYCODE'
  and s.active   = 'Y'

/
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_PLPC_REMARK_LLG
 (CUSTOMER_ID, PRODUCT_ID, SIZEDEFINITION_ID, FINISHINGMETHOD_ID, REMARK)
as select plpc.customer_id, plpc.product_id, plpc.sizedefinition_id, plpc.finishingmethod_id, plpc.remark from productlistpercustomer plpc
where plpc.dateactive <= sysdate and plpc.dateinactive > sysdate

/
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, STAYDESC, PRODUCTCODE, PRODUCTDESC, SIZECODE, PRIMARYID, STAYCHANGEDATE, LASTSCANDATE, DAYS, SIZEDESC, CUSTOMERNUMBER, CUSTOMERNAME, CITY, DEPARTMENTNUMBER, DEPARTMENTDESC, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESC, LANGUAGECODE)
as SELECT 0 GRP, 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 = LANGUAGES.LANGUAGE_ID) STAYDESC,
  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, UI.PRIMARYID, UI.STAYCHANGEDATE, UI.LASTSCANDATE, GETCURRENTDATE() - GETDATEONLY(UI.STAYCHANGEDATE) DAYS,
  (SELECT sdd.DESCRIPTION FROM sizedefinition_desc sdd
     WHERE sdd.sizedefinition_id = sz.sizedefinition_id AND sdd.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDESC,
  CS.CUSTOMERNUMBER, CS.NAME CUSTOMERNAME, AD.CITY,
  DP.DEPARTMENTNUMBER, DP.DESCRIPTION DEPARTMENTDESC,
  DI.DISTRIBUTIONPOINTNUMBER, DI.DESCRIPTION DISTRIBUTIONPOINTDESC,
  LANGUAGES.CODE LANGUAGECODE
FROM UNIQUEITEM UI, BUSINESSUNIT BU, PRODUCT PR, SIZEDEFINITION SZ, STAY S, STATUS ST,
  CUSTOMER CS, DEPARTMENT DP, DISTRIBUTIONPOINT DI, ADDRESS AD,
  LANGUAGES
WHERE UI.BUSINESSUNIT_ID = BU.BUSINESSUNIT_ID
  AND UI.PRODUCT_ID = PR.PRODUCT_ID
  AND UI.SIZEDEFINITION_ID = SZ.SIZEDEFINITION_ID
  AND UI.STAY_ID = S.STAY_ID
  AND UI.STATUS_ID = ST.STATUS_ID--  AND ST.STATUSTYPE = 'UI'  -- UNIQUE ITEM
  AND ST.CODE = 20  -- IN CIRCULATION
  AND UI.POOLITEM = 1  -- POOL
  AND S.STAYTYPE = 1
  AND CS.CUSTOMER_ID = DP.CUSTOMER_ID
  AND DP.DEPARTMENT_ID = DI.DEPARTMENT_ID
  AND DI.DISTRIBUTIONPOINT_ID = UI.DISTRIBUTIONPOINT_ID
  AND CS.VISITADDRESS_ID = AD.ADDRESS_ID
  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)
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
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)
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 = LANGUAGES.LANGUAGE_ID) STAYDESC,
  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, UI.PRIMARYID, UI.STAYCHANGEDATE, GETCURRENTDATE() - GETDATEONLY(UI.STAYCHANGEDATE) DAYS,
  (SELECT szd.DESCRIPTION FROM sizedefinition_desc szd
     WHERE szd.SIZEDEFINITION_ID = sz.SIZEDEFINITION_ID AND szd.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDESC,
  LANGUAGES.CODE LANGUAGECODE
FROM UNIQUEITEM UI, BUSINESSUNIT BU, PRODUCT PR, SIZEDEFINITION SZ, STAY S, STATUS ST,
  LANGUAGES
WHERE UI.BUSINESSUNIT_ID = BU.BUSINESSUNIT_ID
  AND UI.PRODUCT_ID = PR.PRODUCT_ID
  AND UI.SIZEDEFINITION_ID = SZ.SIZEDEFINITION_ID
  AND UI.STAY_ID = S.STAY_ID
  AND UI.STATUS_ID = ST.STATUS_ID--  AND ST.STATUSTYPE = 'UI'  -- UNIQUE ITEM
  AND ST.CODE = 20  -- IN CIRCULATION
  AND UI.POOLITEM = 1  -- POOL
  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)
as select    -- 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
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
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_EMBLEMTEMP_LTS
 (PRICETYPE, CUSTOMER_ID, REPORTPARAM_ID, TIMESTAMP, DATE_VALUE1, PRODUCTCODE, SIZECODE, PRODUCTDESC, STARTDATE, PRICE, LANGUAGECODE, REASONCODE, REASONCODE_DESC, ACTIVITYDESCRIPTION, ACTIVITYCODE, OLDPRICE)
as select    -- 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 A.DESCRIPTION FROM ACTIVITY_DESC A, PRODUCTGROUP PG WHERE  A.ACTIVITY_ID = PG.ACTIVITY_ID AND PG.PRODUCTGROUP_ID = PRD.PRODUCTGROUP_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) ACTIVITYDESCRIPTION
,(SELECT AC.CODE FROM ACTIVITY AC, PRODUCTGROUP PG WHERE AC.ACTIVITY_ID = PG.ACTIVITY_ID AND PG.PRODUCTGROUP_ID = PRD.PRODUCTGROUP_ID) ACTIVITYCODE
,(select etplip2.price from emblemtemplatelineprice etplip2 where etplip2.emblemtemplateline_id=etplip.emblemtemplateline_id
and etplip2.startdate=(select max(emblemtemplatelineprice.startdate) from emblemtemplatelineprice
                     where emblemtemplatelineprice.startdate <= rp.date_value1-1 and emblemtemplatelineprice.emblemtemplateline_id = etpli.emblemtemplateline_id)) oldprice
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
,'' ACTIVITYDESCRIPTION,'' ACTIVITYCODE
,(select cpp2.price from customerprepcharge cpp2 where cpp2.customer_id=cpp.customer_id and  cpp2.reasoncode_id=cpp.reasoncode_id
and cpp2.startdate=( select max(customerprepcharge.startdate) from customerprepcharge
                             where customerprepcharge.customer_id = cpp.customer_id
                                   and customerprepcharge.startdate <= rp.date_value1-1
                                   and ((customerprepcharge.reasoncode_id = cpp.reasoncode_id)
                                   or(cpp.reasoncode_id is null and customerprepcharge.reasoncode_id is null ))))
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_HSOIL_LLG
 (CUSTOMER_ID, REPORTPARAM_ID, LANGUAGECODE, PRODUCTCODE, PRODUCTDESC, SIZECODE, FMCODE, STARTDATE, PRICE)
as select c.customer_id,
rp.reportparam_id,
l.code languagecode,
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 fmcode,
cwp.startdate,
cwp.price
from customerwashprice cwp
inner join productlistpercustomer plpc on cwp.productlistpercustomer_id = plpc.productlistpercustomer_id
inner join customer c on plpc.customer_id = c.customer_id
inner join product p on plpc.product_id = p.product_id
inner join sizedefinition sd on plpc.sizedefinition_id = sd.sizedefinition_id
inner join finishingmethod fm on plpc.finishingmethod_id = fm.finishingmethod_id
, languages l
, reportparam rp
where cwp.pricetype = 5
and rp.date_value1 >= cwp.startdate

/
create or replace view V_PRICECUSTOMER_INSURANCE
 (PRICETYPE, CUSTOMER_ID, REPORTPARAM_ID, TIMESTAMP, DATE_VALUE1, PRODUCTCODE, SIZECODE, FINISHINGMETCODE, PRODUCTDESC, PRICE_DETAILS, LANGUAGECODE, STARTDATE)
as select    -- 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
, 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_INSURANCE_LTS
 (PRICETYPE, CUSTOMER_ID, REPORTPARAM_ID, TIMESTAMP, DATE_VALUE1, PRODUCTCODE, SIZECODE, FINISHINGMETCODE, DESCRIPTION, PRODUCTDESC, PRICE_DETAILS, LANGUAGECODE, STARTDATE, ACTIVITYDESCRIPTION, ACTIVITYCODE, OLDPRICE)
as select    -- 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,fmd.description
, ( 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
, 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
,(SELECT A.DESCRIPTION FROM ACTIVITY_DESC A, PRODUCTGROUP PG WHERE  A.ACTIVITY_ID = PG.ACTIVITY_ID AND PG.PRODUCTGROUP_ID = PRD.PRODUCTGROUP_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) ACTIVITYDESCRIPTION
,(SELECT AC.CODE FROM ACTIVITY AC, PRODUCTGROUP PG WHERE AC.ACTIVITY_ID = PG.ACTIVITY_ID AND PG.PRODUCTGROUP_ID = PRD.PRODUCTGROUP_ID) ACTIVITYCODE
,cast(F_PRICEINSURANCE_DETAILS(pripc.customer_id, prd.product_id, sz.sizedefinition_id, fm.finishingmethod_id, rp.date_value1-1) as varchar2(30)) oldprice
from
  productlistpercustomer plpc, pricelistpercustomer pripc
, product prd, sizedefinition sz, finishingmethod fm,finishingmethod_desc fmd
, 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
and fm.finishingmethod_id=fmd.finishingmethod_id
and fmd.language_id=languages.language_id

/
create or replace view V_PRICECUSTOMER_INVOICE
 (PRICETYPE, CUSTOMER_ID, PRICE)
as select
  50 pricetype -- assign pricetype 50 TO 'minimuminvoiceamount' group
, cu.customer_id, cu.minimuminvoiceamount price
from
  customer cu
union
select
  60 pricetype -- assign pricetype 60 TO 'creditsqueezeperc' group
, cu.customer_id, cubi.creditsqueezeperc price
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)
as select    -- 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
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
                                       )
--and cullyp.price <> 0
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
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_LABEL_LTS
 (PRICETYPE, CUSTOMER_ID, REPORTPARAM_ID, TIMESTAMP, DATE_VALUE1, LABELTYPE, STARTDATE, PRICE, OLDPRICE)
as select    -- 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 cullyp2.price from customerlabellayoutprice cullyp2 where cullyp2.labeltype=cullyp.labeltype and cullyp2.customer_id=cullyp.customer_id
and cullyp2.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-1
                                       )) oldprice
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
                                       )
--and cullyp.price <> 0
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 f.amountdue from financecharge f where f.customer_link_id=financecharge.customer_link_id
and f.cutoffdate=(select max(fc.cutoffdate) from financecharge fc
                                   where financecharge.customer_link_id = fc.customer_link_id
                                     and fc.cutoffdate <= rp.date_value1
                                     )) oldprice
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_LOAN_LLG
 (CUSTOMER_ID, REPORTPARAM_ID, LANGUAGECODE, PRODUCTCODE, PRODUCTDESC, SIZECODE, FMCODE, STARTDATE, PRICE)
as select c.customer_id,
rp.reportparam_id,
l.code languagecode,
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 fmcode,
crp.startdate,
crp.price
from customerrentprice crp
inner join productlistpercustomer plpc on crp.productlistpercustomer_id = plpc.productlistpercustomer_id
inner join customer c on plpc.customer_id = c.customer_id
inner join product p on plpc.product_id = p.product_id
inner join sizedefinition sd on plpc.sizedefinition_id = sd.sizedefinition_id
inner join finishingmethod fm on plpc.finishingmethod_id = fm.finishingmethod_id
, languages l
, reportparam rp
where crp.typeofrent = 10
and rp.date_value1 >= crp.startdate

/
create or replace view V_PRICECUSTOMER_NOLOADING
 (PRICETYPE, CUSTOMER_ID, REPORTPARAM_ID, TIMESTAMP, DATE_VALUE1, PRODUCTCODE, SIZECODE, FINISHINGMETCODE, PRODUCTDESC, LANGUAGECODE)
as select distinct   -- 1 -- wash only piece price, rent, replacement, sales
  pripc.pricetype, pripc.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
, languages.code languageCode
from
  productlistpercustomer plpc, pricelistpercustomer pripc
, product prd, sizedefinition sz, finishingmethod fm
, reportparam rp, languages
where
    pripc.customer_id = plpc.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 in (1, 2, 3, 4)
and plpc.product_id = prd.product_id
and plpc.sizedefinition_id = sz.sizedefinition_id
and plpc.finishingmethod_id = fm.finishingmethod_id
union all
select distinct   -- 1 -- wash only COG price
  pripc.pricetype, pripc.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
, languages.code languageCode
from
  productlistpercustomer plpc, pricelistpercustomer pripc
, product prd, sizedefinition sz, finishingmethod fm
, reportparam rp, languages
where
    pripc.customer_id = plpc.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 = 1  -- wash, view is only for COG price
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_REPAIR
 (PRICETYPE, CUSTOMER_ID, REPORTPARAM_ID, TIMESTAMP, DATE_VALUE1, PRODUCTCODE, PRODUCTDESC, PRICE_DETAILS, LANGUAGECODE, STARTDATE)
as select    -- 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
, 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
, 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_REPAIR_LTS
 (PRICETYPE, CUSTOMER_ID, REPORTPARAM_ID, TIMESTAMP, DATE_VALUE1, PRODUCTCODE, PRODUCTDESC, PRICE_DETAILS, LANGUAGECODE, STARTDATE, ACTIVITYDESCRIPTION, ACTIVITYCODE, OLDPRICE)
as select    -- 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
, 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
,(SELECT A.DESCRIPTION FROM ACTIVITY_DESC A WHERE  A.ACTIVITY_ID = RTY.ACTIVITY_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) ACTIVITYDESCRIPTION
,(SELECT AC.CODE FROM ACTIVITY AC WHERE  AC.ACTIVITY_ID = RTY.ACTIVITY_ID) ACTIVITYCODE
, cast(F_PRICEREPAIR_DETAILS(pripc.customer_id, rty.repairtype_id, rp.date_value1-1, 1) as varchar2(30)) oldprice
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

/
create or replace view V_PRICECUSTOMER_SPECCHARGE_LTS
 (PRICETYPE, SUBTYPE, CUSTOMER_ID, REPORTPARAM_ID, TIMESTAMP, DATE_VALUE1, PRODUCTCODE, PRODUCTDESC, STARTDATE, PRICE, FREQUENCY, PRICE_TYPE, LANGUAGECODE, OLDPRICE)
as select    -- 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 = languages.language_id )  productDesc
, scg.timestamp 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 -- 1: per invoice, 2: once a week, 3: ...
, case scg.fixedamount when 'N' then 2 else 1 end price_type -- 2: percentage, 1: amount
, languages.code languageCode
, case scg.fixedamount when 'N'
then pack_price.SpecialCharge_Percentage(cuscg.customer_id, scg.specialcharge_id, rp.date_value1-1)
else pack_price.SpecialCharge_Price(cuscg.customer_id, scg.specialcharge_id, rp.date_value1-1)
end oldprice
from
  customerspecialcharge cuscg, specialcharge scg, reportparam rp, languages
where
  cuscg.specialcharge_id = scg.specialcharge_id
         --and scg.newamount <> 0 -- ! --
UNION ALL  -- 10 -- locker
select
  cast(950 + culop.pricetype as varchar2(3)) pricetype --  951(1): locker rent 952(2): locker service
, 0 subtype, culop.customer_id, rp.reportparam_id, rp.timestamp, rp.date_value1
, cast(( case culop.pricetype
          when 1 then culom.chargerent -- 1 : charge per fixed number of bk/lk   2: charge per occupied
            when 2 then culom.chargeservice -- 1: charge per lk   2: charge per garment per lk
                 end ) as varchar2(12)) productCode
, '' productDesc
, culop.startdate
, culop.price, null frequency
, culom.fixednumberbank price_details
, languages.code languageCode
,(select culop2.price from customerlockerprice culop2 where culop2.customer_id=culop.customer_id and culop2.pricetype=culop.pricetype
and culop2.startdate=(select customerlockerprice.startdate from customerlockerprice
                        where culop.customer_id = customerlockerprice.customer_id
                          and customerlockerprice.pricetype = culop.pricetype
                            and customerlockerprice.startdate <= rp.date_value1-1)) oldprice
from
 customerlockermanagement culom , customerlockerprice culop, reportparam rp, languages
where
   culom.customer_id = culop.customer_id
and 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 = languages.language_id ) productDesc
, cl.startdate
, cl.newamount price
, scg.frequency
, case cl.newamount when 0 then 2 else 1 end price_type
, languages.code languageCode
,cl.oldamount oldprice
from customer c, clientinvoicecategorycharge cl, clientinvoicecategory ci, specialcharge scg,
     reportparam rp, languages
where cl.clientinvoicecategory_id = ci.clientinvoicecategory_id
and ci.customer_id = c.customer_id
and scg.specialcharge_id = cl.specialcharge_id
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
, languages.code languageCode
,(select csc3.price from customerstockcharge csc3 where csc3.customer_id=csc.customer_id
and csc3.startdate = (select max(csc2.startdate) from customerstockcharge csc2
                           where csc2.customer_id = csc.customer_id
                           and csc2.startdate <= rp.date_value1-1)
) oldprice
from customerstockcharge csc, reportparam rp, languages
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 --0=LOG 1=COG
, languages.code languageCode
,(select csc3.price from customerservicecostsprice csc3 where csc3.customer_id=csc.customer_id and csc3.pricetype=csc.pricetype
and csc3.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-1)
) oldprice
from customerservicecostsprice csc, reportparam rp, languages
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_SPECIALCHARGE
 (PRICETYPE, SUBTYPE, CUSTOMER_ID, REPORTPARAM_ID, TIMESTAMP, DATE_VALUE1, PRODUCTCODE, PRODUCTDESC, STARTDATE, PRICE, FREQUENCY, PRICE_TYPE, LANGUAGECODE)
as select    -- 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 = languages.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 -- 1: per invoice, 2: once a week, 3: ...
, case scg.fixedamount when 'N' then 2 else 1 end price_type -- 2: percentage, 1: amount
, languages.code languageCode
from
  customerspecialcharge cuscg, specialcharge scg, reportparam rp, languages
where
  cuscg.specialcharge_id = scg.specialcharge_id
         --and scg.newamount <> 0 -- ! --
UNION ALL  -- 10 -- locker
select
  cast(950 + culop.pricetype as varchar2(3)) pricetype --  951(1): locker rent 952(2): locker service
, 0 subtype, culop.customer_id, rp.reportparam_id, rp.timestamp, rp.date_value1
, cast(( case culop.pricetype
          when 1 then culom.chargerent -- 1 : charge per fixed number of bk/lk   2: charge per occupied
            when 2 then culom.chargeservice -- 1: charge per lk   2: charge per garment per lk
                 end ) as varchar2(12)) productCode
, '' productDesc
, culop.startdate
, culop.price, null frequency
, culom.fixednumberbank price_details
, languages.code languageCode
from
 customerlockermanagement culom , customerlockerprice culop, reportparam rp, languages
where
   culom.customer_id = culop.customer_id
and 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 = languages.language_id ) productDesc
, cl.startdate
, cl.newamount price
, scg.frequency
, case cl.newamount when 0 then 2 else 1 end price_type
, languages.code languageCode
from customer c, clientinvoicecategorycharge cl, clientinvoicecategory ci, specialcharge scg,
     reportparam rp, languages
where cl.clientinvoicecategory_id = ci.clientinvoicecategory_id
and ci.customer_id = c.customer_id
and scg.specialcharge_id = cl.specialcharge_id
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
, languages.code languageCode
from customerstockcharge csc, reportparam rp, languages
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 --0=LOG 1=COG
, languages.code languageCode
from customerservicecostsprice csc, reportparam rp, languages
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)
as select 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
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
/*union all
select distinct   -- 1 -- wash only COG price
  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
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_WASH_LTS
 (PRICETYPE, CUSTOMER_ID, REPORTPARAM_ID, TIMESTAMP, DATE_VALUE1, PRODUCTCODE, SIZECODE, FINISHINGMETCODE, DESCRIPTION, PRODUCTDESC, PRICE_DETAILS, DISCOUNT, LANGUAGECODE, RPPRICESID, CHANGESPERWEEK, STARTDATE, GPLPRICETYPE, ACTIVITYDESCRIPTION, ACTIVITYCODE, TYPEOFMERCHANDISE, REGISTRATIONUNITDESCRIPTION, OLDPRICE)
as select 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,fmd.description
, ( 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
, f_lts_washpricetype(plpc.customer_id, plpc.product_id, plpc.sizedefinition_id, plpc.finishingmethod_id, rp.date_value1) gplpricetype
,(SELECT A.DESCRIPTION FROM ACTIVITY_DESC A, PRODUCTGROUP PG
         WHERE  A.ACTIVITY_ID = PG.ACTIVITY_ID AND PG.PRODUCTGROUP_ID = PRD.PRODUCTGROUP_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) ACTIVITYDESCRIPTION
,(SELECT AC.CODE FROM ACTIVITY AC, PRODUCTGROUP PG
         WHERE AC.ACTIVITY_ID = PG.ACTIVITY_ID AND PG.PRODUCTGROUP_ID = PRD.PRODUCTGROUP_ID) ACTIVITYCODE,prd.typeofmerchandise
,(select pd.registrationunitdescription from product_link_desc pd where pd.product_link_id =prd.product_id and pd.language_id = languages.language_id) registrationunitdescription
,case rpPrices.Copy_Number--pripc.pricetype
      when 1 then pack_price.Wash_Price(plpc.customer_id, plpc.product_id, plpc.sizedefinition_id, plpc.finishingmethod_id, rp.date_value1-1) --wash
      when 2 then pack_price.Rent_Price(plpc.customer_id,plpc.product_id,plpc.sizedefinition_id,plpc.finishingmethod_id,rp.date_value1-1)--rent
      when 3 then pack_price.Replacement_Price(plpc.customer_id,plpc.product_id,plpc.sizedefinition_id,plpc.finishingmethod_id,rp.date_value1-1)--replacement
      when 4 then pack_price.Sales_Price(plpc.customer_id,plpc.product_id,plpc.sizedefinition_id,rp.date_value1-1)--sales
        end oldprice
from
  productlistpercustomer plpc
, product prd, sizedefinition sz, finishingmethod fm
, reportparam rp, languages,finishingmethod_desc fmd
, 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
and fm.finishingmethod_id=fmd.finishingmethod_id
and fmd.language_id=languages.language_id
/
create or replace view V_PRICECUSTOMER_WEARER
 (CUSTOMER_ID, REPORTPARAM_ID, WEARERNUMBER, FULLNAME, ADMINNUMBER, PRODUCTCODE, SIZECODE, FINISHINGMETCODE, PRODUCTDESC, STARTDATE, PRICE, LANGUAGECODE)
as select
  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
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)
as select 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
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
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_PRICECUSTOMER_WEIGHT_LTS
 (PRICETYPE, CUSTOMER_ID, REPORTPARAM_ID, TIMESTAMP, DATE_VALUE1, PRODUCTCODE, SIZECODE, FINISHINGMETCODE, PRODUCTDESC, PRICE, PRICE_DETAILS, LENGTH_PRICE, DISCOUNT, LANGUAGECODE, ACTIVITYDESCRIPTION, ACTIVITYCODE, OLDPRICE, LENGTH_OLDPRICE)
as select 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
, LENGTH(LTRIM(RTRIM((substr(pack_price.Weight_Price_Details(pripc.customer_id, wgh.weighingcategory_id, 'Y', rp.date_value1), 1, 12))))) length_price
, pack_price.Weight_Discount_Display(pripc.customer_id, wgh.weighingcategory_id, 'Y', rp.date_value1) Discount
, languages.code languageCode
,(SELECT A.DESCRIPTION FROM ACTIVITY_DESC A WHERE  A.ACTIVITY_ID = wgh.ACTIVITY_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) ACTIVITYDESCRIPTION
,(SELECT AC.CODE FROM ACTIVITY AC WHERE  AC.ACTIVITY_ID = wgh.ACTIVITY_ID) ACTIVITYCODE
,pack_price.Weight_Price(pripc.customer_id, wgh.weighingcategory_id, 'Y', rp.date_value1-1) oldprice
,LENGTH(LTRIM(RTRIM((substr(pack_price.Weight_Price_Details(pripc.customer_id, wgh.weighingcategory_id, 'Y', rp.date_value1-1), 1, 12))))) length_oldprice
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
            and LENGTH(LTRIM(RTRIM((substr(pack_price.Weight_Price_Details(pripc.customer_id, wgh.weighingcategory_id, 'Y', rp.date_value1), 14, 8)))))>0
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, 'Y', rp.date_value1) price
, pack_price.Weight_Price_Details(pripc.customer_id, wgh.weighingcategory_id, 'N', rp.date_value1) price_details
, LENGTH(LTRIM(RTRIM((substr(pack_price.Weight_Price_Details(pripc.customer_id, wgh.weighingcategory_id, 'N', rp.date_value1), 1, 12))))) length_price
, pack_price.Weight_Discount_Display(pripc.customer_id, wgh.weighingcategory_id, 'N', rp.date_value1) Discount
, languages.code languageCode
,(SELECT A.DESCRIPTION FROM ACTIVITY_DESC A WHERE  A.ACTIVITY_ID = wgh.ACTIVITY_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) ACTIVITYDESCRIPTION
,(SELECT AC.CODE FROM ACTIVITY AC WHERE  AC.ACTIVITY_ID = wgh.ACTIVITY_ID) ACTIVITYCODE
,pack_price.Weight_Price(pripc.customer_id, wgh.weighingcategory_id, 'N', rp.date_value1-1) oldprice
,LENGTH(LTRIM(RTRIM((substr(pack_price.Weight_Price_Details(pripc.customer_id, wgh.weighingcategory_id, 'N', rp.date_value1-1), 1, 12))))) length_oldprice
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
            and LENGTH(LTRIM(RTRIM((substr(pack_price.Weight_Price_Details(pripc.customer_id, wgh.weighingcategory_id, 'N', rp.date_value1), 14, 8)))))>0

/
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, CPI_INCRPERC, CPIBASED, RENTPRICE, RENTPRICE_CHPERWEEK, WASHPRICE, REPLACEPRICE, SALESPRICE, WEIGHTPRICE, BILLINGMETHOD, CHANGESPERWEEK, STARTDATE, TYPEOFRENT, TYPEOFMERCHANDISE, LANGUAGECODE, COUNTWEARERS)
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 = l.language_id) productdesc,
nvl((select sum(rqa.quantity) from rentalqtyadjustment rqa, productlistperdistribpoint plpd
 where rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
 and plpd.product_id = plpc.product_id
 and plpd.sizedefinition_id = plpc.sizedefinition_id
 and plpd.finishingmethod_id = plpc.finishingmethod_id
 and plpd.distributionpoint_id = dp.distributionpoint_id
 and rqa.sampleitem = 'N'--only chargeable
 and rqa.adjustmentdate <= sysdate),0) rqaqty,
nvl((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 = 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,
(select ss.value from systemsetting ss, plant pl
   where ss.name = 'CPI_INCREASEPERCENTAGE' and pl.plant_id = bu.plant_id and ss.plant_id = pl.plant_id) cpi_incrperc,
cpc.cpibased,
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,
l.code languagecode,
nvl((select count(w.wearernumber) 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 = 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
from contractspercustomer cpc
inner join customer c on cpc.customer_id = c.customer_id
inner join (productlistpercustomer plpc left outer join customerrentprice crp on plpc.productlistpercustomer_id = crp.productlistpercustomer_id
            and crp.typeofrent = 2)
      on plpc.customer_id = c.customer_id
inner join product p on plpc.product_id = p.product_id
inner join sizedefinition sd on plpc.sizedefinition_id = sd.sizedefinition_id
inner join finishingmethod fm on plpc.finishingmethod_id = fm.finishingmethod_id
inner join department d on c.customer_id = d.customer_id
inner join distributionpoint dp on dp.department_id = d.department_id
inner join businessunit bu on c.defaultbusinessunit_id = bu.businessunit_id,
languages l
where cpc.nextanniversarydate <> to_date('31-12-2099','dd-mm-yyyy')
and (c.dateactive <> to_date('31-12-2099','dd-mm-yyyy') and c.dateinactive > cpc.nextanniversarydate)
and (crp.startdate = (select max(crp2.startdate) from customerrentprice crp2 where crp2.productlistpercustomer_id = plpc.productlistpercustomer_id)
or crp.startdate is null)

/
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, PERMITINVOICEADJUST, 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.PERMITINVOICEADJUST,
  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-- Changed HVH 21/10/2008--, sum(il.amount*ilp.pricefactor) billedamount, sum(il.billedqty) billedqty, sum(ilp.deliveredqty) deliveredqty
, 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--
, ss.value SETTLEMENTACTIVE, sy.value 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 outer 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
, status, invoiceline il, invoicelinetype ilt
, turnovergroup tg, invoicelineproduct ilp, product prd, sizedefinition sz, productsize prdsz, finishingmethod fm
, businessunit inBu, plant, systemsetting ss, systemsetting sy, currency cur
, languages
where
ih.status_id = status.status_id
    and status.statustype = 'IN'
        and status.code = 2
and ih.invoiceheader_id = il.invoiceheader_id
    and il.invoicelinetype_id = ilt.invoicelinetype_id
and il.turnovergroup_id=tg.turnovergroup_id
and il.extend='Y' -- Added HVH 21/10/2008
and il.invoiceline_id = ilp.invoiceline_id
    and ilp.product_link_id = prd.product_id
    and ilp.sizedefinition_link_id = sz.sizedefinition_id
    and ilp.finishingmethod_id = fm.finishingmethod_id
        and prd.product_id = prdsz.product_id
        and sz.sizedefinition_id = prdsz.sizedefinition_id
and ih.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'
and ih.currency_id=cur.currency_id
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, ss.value, sy.value, languages.language_id, languages.code
, cur.decimals, cur.invoiceamountdecimals
, sa.salesarea_id, sa.code
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_PRODUCTSTATISTIC_SMG
 (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(coalesce(ilc.amount, b.amount))
         else
          sum(coalesce(ilc.amount, 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
     left outer join invoicelinecurrency ilc on ilc.invoiceline_id = b.invoiceline_id and ilc.invoicecurrencytype = 2, --Plant Currency
  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 <= GETCURRENTDATETIME())) 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_PURCHASEORDEREMBL_JWR
 (PURCHASEORDERHEADER_ID, PURCHASEORDERLINE_ID, CUSTOMERNUMBER, NAME, WORKORDERLINE_ID, WEARERNUMBER, FULLNAME, EMBLEMNAME, EMBLEMTYPE, QTYREQUESTED)
as select poh.purchaseorderheader_id,
       pol.purchaseorderline_id,
       c.customernumber,
       c.name,
       wol.workorderline_id,
       we.wearernumber,
       we.fullname,
       we.emblemname,
       em.emblemtype,
       wole.qtyrequested
  from purchaseorderline pol
  left outer join emblemproduct em
    on pol.product_link_id = em.product_id, 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 GETCURRENTDATE()
                          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 GETCURRENTDATE() - ( case when ph.exportdate = GETABSMAXDATE()
                                       then ph.approvaldate + spprd.deliverydays
                                            else ph.exportdate + spprd.deliverydays end )
                 else GETCURRENTDATE() - 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)
                                       < GETCURRENTDATE() )
    or
     ( ph.confirmeddate <> GETABSMAXDATE() and ph.confirmeddate < GETCURRENTDATE() ))
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_PURCHASEORDERLINE_AMM
 (PURCHASEORDERHEADER_ID, PURCHASEORDERLINE_ID, WORKORDERNUMBER, CUSTOMERNUMBER, CUSTOMERNAME, WEARERNUMBER, FULLNAME, NEEDEDDATE, PRODUCT_CODE, CODE, WO_QTY_ORDERED, REASON_CODE)
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,
       p.code as product_code,
       sd.code,
       wokli.quantityordered wo_qty_ordered,
       r.code as reason_code
from
  purchaseorderline pli, workorderline wokli, reasoncode r, product p, sizedefinition sd,
  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
and pli.product_link_id = p.product_id
and pli.sizedefinition_link_id= sd.sizedefinition_id
and wokli.product_link_id =  p.product_id
and wokli.sizedefinition_link_id = sd.sizedefinition_id
and wokli.reasoncode_id = r.reasoncode_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,
       p.code as product_code,
       sd.code,
       wokli.quantityordered wo_qty_ordered,
       r.code as reason_code
from
  purchaseorderline pli, workorderlineemblem wokem, workorderline wokli, reasoncode r, product p, sizedefinition sd,
  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
and pli.product_link_id = p.product_id
and pli.sizedefinition_link_id= sd.sizedefinition_id
and wokli.product_link_id =  p.product_id
and wokli.sizedefinition_link_id = sd.sizedefinition_id
and wokli.reasoncode_id = r.reasoncode_id

/
create or replace view V_PURCHASEORDERLINE_AUJ
 (PURCHASEORDERHEADER_ID, PURCHASEORDERLINE_ID, WORKORDERNUMBER, PRODUCTCODE, SIZECODE, PRODUCTDESC, LANGCODE)
as select distinct
  pli.purchaseorderheader_id, pli.purchaseorderline_id, wok.workordernumber
/*, (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*/
, prl.code productcode, sd.code sizecode
, (select pld.description from product_link_desc pld where pld.product_link_id = wokli.product_link_id and pld.language_id = lan.language_id) productdesc
, lan.code langcode
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*/
, product_link prl, sizedefinition_link sd, languages lan
where
    pli.purchaseorderline_id = wokli.purchaseorderline_id
and wokli.workorder_id = wok.workorder_id
and wokli.product_link_id = prl.product_link_id
and wokli.sizedefinition_link_id = sd.sizedefinition_link_id
union
select distinct
  pli.purchaseorderheader_id, pli.purchaseorderline_id, wok.workordernumber
, prl.code productcode, sd.code sizecode
, (select pld.description from product_link_desc pld where pld.product_link_id = wokli.product_link_id and pld.language_id = lan.language_id) productdesc
, lan.code langcode
from
  purchaseorderline pli, workorderline wokli, workorderlinepurchordline wolpol
, workorder wok, product_link prl, sizedefinition_link sd, languages lan
where pli.purchaseorderline_id=wolpol.workorderlinepurchordline_id and wokli.workorderline_id=wolpol.workorderline_id
and wokli.workorder_id = wok.workorder_id
and wokli.product_link_id = prl.product_link_id
and wokli.sizedefinition_link_id = sd.sizedefinition_link_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*/
, prl.code productcode, sd.code sizecode
, (select pld.description from product_link_desc pld where pld.product_link_id = wokem.product_id and pld.language_id = lan.language_id) productdesc
, lan.code langcode
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*/
, product_link prl, sizedefinition_link sd, languages lan
where
    pli.purchaseorderline_id = wokem.purchaseorderline_id
and wokem.workorderline_id = wokli.workorderline_id
and wokli.workorder_id = wok.workorder_id
and wokem.product_id = prl.product_id
and wokem.sizedefinition_id = sd.sizedefinition_id
union
select distinct
  pli.purchaseorderheader_id, pli.purchaseorderline_id, wok.workordernumber
, prl.code productcode, sd.code sizecode
, (select pld.description from product_link_desc pld where pld.product_link_id = wokem.product_id and pld.language_id = lan.language_id) productdesc
, lan.code langcode
from
  purchaseorderline pli, workorderlineemblem wokem, workorderline wokli, workorderlinepurchordline wolpol
, workorder wok, product_link prl, sizedefinition_link sd, languages lan
where pli.purchaseorderline_id=wolpol.workorderlinepurchordline_id and wokli.workorderline_id=wolpol.workorderline_id
and pli.purchaseorderline_id = wokem.purchaseorderline_id
and wokem.workorderline_id = wokli.workorderline_id
and wokli.workorder_id = wok.workorder_id
and wokem.product_id = prl.product_id
and wokem.sizedefinition_id = sd.sizedefinition_id

/
create or replace view V_PURCHASEORDER_AUJ
 (SUPPNUMBER, SUPPNAME, SUPPLIERTYPE, STOCKREMARK, PURCHASEORDERNUMBER, ORDERDATE, REQUESTEDDATE, PHREMARK, PHREMARK_NULL, PRODUCTLINKCODE, SUPPLIERPRODUCTCODE, SUPPLIERSIZECODE, SUPPLIERPRODUCTDESC, PRODUCTDESC, UNIQUEITEM, QUANTITYORDERED, PRINTPRICEONPO, PURCHASEPRICE, PLIREMARK, PLIREMARK_NULL, PURCHASEORDERHEADER_ID, PURCHASEORDERLINE_ID, ORIGIN, APPROVALDATE, APPROVALUSER_ID, CREATEDBY, APPROVEDBY, QUANTITYRECEIVED, QUANTITYCANCELLED, QUANTITYCONFIRMED, LANGUAGECODE
, LAUNDRYSIZECODE, STOCKZIPCODE, STOCKCITY, STOCKSTREET, STOCKNAME, ORDERFORMREMARK, CREDITORNUMBER, HASPRIO2, HASPRIO0COLOR24, PAYMENTTERMS)
as select
  supplier.suppliernumber suppNumber, supplier.name suppName
, supplier.suppliertype suppliertype
, sk.remark stockremark
, ph.purchaseordernumber, ph.orderdate, ph.requesteddate
, ph.remark PHRemark,  case when ph.remark is null then 'Y' else 'N' end PHRemark_null
, product_link.code productLinkCode, pli.supplierproductcode, pli.suppliersizecode
, coalesce
  (( select splprd.supplierproductdescription from supplierproduct splprd
          where pli.supplierproductcode = splprd.supplierproductcode
             and pli.suppliersizecode = splprd.suppliersizecode
                 and supplier.supplier_id = splprd.supplier_id)
   ,( select product_desc.description from product_desc where product_desc.product_id = pli.product_link_id
            and product_desc.language_id = languages.language_id )) supplierProductDesc
, ( select product_desc.description from product_desc where product_desc.product_id = pli.product_link_id
            and product_desc.language_id = languages.language_id )  ProductDesc
, pli.uniqueitem, pli.quantityordered
, supplier.printPriceOnPO
, pli.purchaseprice
, pli.remark PLIRemark, case when pli.remark is null then 'Y' else 'N' end PLIRemark_null
, ph.purchaseorderheader_id, pli.purchaseorderline_id
, ph.origin, ph.approvaldate, ph.approvaluser_id
, (select su.fullname from systemuser su where su.systemuser_id = ph.orderuser_id) createdby
, (select su.fullname from systemuser su where su.systemuser_id = ph.approvaluser_id) approvedby
, pli.quantityreceived, pli.quantitycancelled, pli.quantityconfirmed
, languages.code languageCode
, sizedefinition_link.code LaundrySizeCode
, a.zipcode stockzipcode
, a.city stockcity
, a.street stockstreet
, sk.name stockname
, supplier.orderformremark
, supplier.creditornumber
, (select count(1) from product p, productranking pr
          where p.productranking_id = pr.productranking_id
          and product_link.product_id = p.product_id
          and pr.priority = 2) hasPrio2
, (select count(1) from product p, productranking pr
         where p.productranking_id = pr.productranking_id
         and pr.priority = 0
         and product_link.product_id = p.product_id
         and p.color_id in (select c.color_id from color c where c.code in ('2', '4'))) hasPrio0Color24
, supplier.paymentterms
from
  purchaseorderheader ph
    left outer join
         (stockroom sk inner join address a on sk.deliveryaddress_id = a.address_id) on ph.stockroom_id = sk.stockroom_id
    left outer join
         ( purchaseorderline pli
                             join product_link on pli.product_link_id = product_link.product_link_id
                             join sizedefinition_link on pli.sizedefinition_link_id = sizedefinition_link.sizedefinition_link_id
         ) on ph.purchaseorderheader_id = pli.purchaseorderheader_id
, supplier, languages
where ph.supplier_id = supplier.supplier_id

/
create or replace view V_PURCHASEORDER_CSC
 (SUPPNUMBER, SUPPNAME, SUPPSTREET, SUPPZIPCODE, SUPPCITY, SUPPPHONE, SUPPSTATECOUNTY, SUPPFAX, SUPPEMAIL, SUPPLIERTYPE, BUYERCODE, STOCKCODE, STOCKNAME, PLANTBUNAME, STOCKSTREET, STOCKZIPCODE, STOCKCITY, STOCKSTATECOUNTY, PLANTBUPHONE, PLANTBUFAX, PLANTBUEMAIL, PLANTCOMPANY_ID, PLANTCOMPANYCODE, PLANTCOMPANYNAME, PCYSTREET, PCYZIPCODE, PCYCITY, PCYSTATECOUNTY, PLANTCOMPANYPHONE, PLANTCOMPANYFAX, PLANTCOMPANYEMAIL, PLANTCOMPANYVAT, PURCHASEORDERNUMBER, ORDERDATE, REQUESTEDDATE
, DISCOUNTPERCOVERALL, DISCOUNTPERCDAYS, DISCOUNTWITHINDAYS, PAYMENTTERMS, DELIVERYTERMS, PHREMARK, PHREMARK_NULL, 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, SIZESEQNR, PH_BUCODE, PH_BUDESC, PH_PLANTCODE, PH_PLANTNAME, PH_PLANTPHONENO, PH_PLANTFAXNO, PH_PLANTEMAIL, PH_PLANTSTREET, PH_PLANTSTREET2, PH_PLANTCITY, PH_PLANTZIPCODE, PH_PLANTSTATE)
as select
  supplier.suppliernumber suppNumber, supplier.name suppName, addressSup.Street SuppStreet
, addressSup.Zipcode SuppZipCode, addressSup.City SuppCity, supplier.phone SuppPhone
, cast(CONCATENATEWITHBLANK3(addressSup.State,'/',addressSup.County) as varchar2(255)) SuppStateCounty
, supplier.fax Suppfax, supplier.email Suppemail, supplier.suppliertype suppliertype
, sksp.buyercode, sk.code stockCode, sk.name stockName, plantBU.name plantBUName, cast(CONCATENATEWITHBLANK(addressSK.Street, addressSK.Street2) as varchar2(255)) STOCKstreet
, addressSK.Zipcode STOCKzipcode, addressSK.City STOCKcity
, cast(CONCATENATEWITHBLANK3(addressSK.State,'/',addressSK.County) as varchar2(255)) STOCKStateCounty
, plantBU.phoneno plantBUPhone, plantBU.Faxno plantBUFax, plantBU.email plantBUEmail
, plantcompany.plantcompany_id, plantcompany.code plantcompanyCode, plantcompany.name plantcompanyName, addressPCY.Street PCYStreet
, addressPCY.Zipcode PCYZipCode, addressPCY.City PCYCity
, cast(CONCATENATEWITHBLANK3(addressPCY.State,'/',addressPCY.County) as varchar2(255)) PCYStateCounty
, plantcompany.phone plantcompanyPhone, plantcompany.fax plantcompanyFax, plantcompany.email plantcompanyEmail, plantcompany.vatnumber plantcompanyVAT
, ph.purchaseordernumber, ph.orderdate, ph.requesteddate
, supplier.discountpercoverall, supplier.discountpercdays, supplier.discountwithindays
, supplier.paymentterms, supplier.deliveryterms
, ph.remark PHRemark,  case when ph.remark is null then 'Y' else 'N' end PHRemark_null
, product.code productLinkCode, pli.supplierproductcode, pli.suppliersizecode
, coalesce
  (( select splprd.supplierproductdescription from supplierproduct splprd
          where pli.supplierproductcode = splprd.supplierproductcode
             and pli.suppliersizecode = splprd.suppliersizecode
                 and supplier.supplier_id = splprd.supplier_id)
   ,( select product_desc.description from product_desc where product_desc.product_id = pli.product_link_id
            and product_desc.language_id = languages.language_id )) supplierProductDesc
, pli.uniqueitem, pli.quantityordered
, supplier.printPriceOnPO
, pli.purchaseprice, (pli.quantityordered * pli.purchaseprice) amount
, pli.remark PLIRemark, case when pli.remark is null then 'Y' else 'N' end PLIRemark_null
, currency.code currencyCode, currency.decimals pricedecimals, currency.invoiceamountdecimals amountdecimals
, ph.purchaseorderheader_id, pli.purchaseorderline_id
, status.code statusCode, ph.origin, ph.approvaldate, ph.approvaluser_id
, ( select status_desc.description from status_desc where status_desc.status_id = status.status_id
  and status_desc.language_id = languages.language_id ) statusDesc
, pli.quantityreceived, pli.quantitycancelled, pli.quantityconfirmed
, languages.code languageCode
, sizedefinition_link.code LaundrySizeCode
, (select qg.Code from QualityGrade qg where pli.requestedgrade_id = qg.qualitygrade_id) QualityGradeCode
, (select spst.sequencenumber from sizespersizetype spst where sizedefinition_link.sizedefinition_id = spst.sizedefinition_id
and spst.sizetype_id = product.sizetype_id) SizeSeqNR
, phbu.code PH_BuCode, phbu.description PH_BuDesc, phpl.code PH_PlantCode, phpl.name PH_PlantName
, phpl.phoneno PH_PlantPhoneno, phpl.faxno PH_PlantFaxno, phpl.email PH_PlantEmail
, phpla.street PH_PlantStreet, phpla.street2 PH_PlantStreet2
, phpla.city PH_PlantCity, phpla.zipcode PH_PlantZipCode, phpla.state PH_PlantState
from
  purchaseorderheader ph
    left outer join
         ( plantcompany join address addressPCY on plantcompany.address_id = addressPCY.Address_Id
         ) on ph.plantcompany_id = plantcompany.plantcompany_id
    left outer join stockroomsupplier sksp
          on ph.stockroom_id = sksp.stockroom_id and ph.supplier_id = sksp.supplier_id
    left outer join
         ( stockroom sk
                join ( businessunit bu join plant plantBU on bu.plant_id = plantBU.plant_id )
                  on sk.managedbybu_id = bu.businessunit_id
                join address addressSK on sk.deliveryaddress_id = addressSK.address_id
          ) on ph.stockroom_id = sk.stockroom_id
    left outer join
         ( purchaseorderline pli
                             join product on pli.product_link_id = product.product_id
                             join sizedefinition_link on pli.sizedefinition_link_id = sizedefinition_link.sizedefinition_link_id
         ) on ph.purchaseorderheader_id = pli.purchaseorderheader_id
, status, supplier, address addressSup, currency, languages
, businessunit  phbu, plant phpl, address phpla
where ph.supplier_id = supplier.supplier_id
and supplier.address_id = addressSup.address_id
and ph.status_id = status.status_id
and ph.currency_id = currency.currency_id
and ph.businessunit_id = phbu.businessunit_id
and phbu.plant_id = phpl.plant_id
and phpl.address_id = phpla.address_id

/
create or replace view V_PURCHASEORDER_CVL
 (WOLQTYORDERED1, WOLQTYORDERED2, PURCHASEORDERLINE_ID, MODIF, QUANTITYORDERED, QUANTITYCANCELLED, SUPPNUMBER, SUPPNAME, SUPPSTREET, SUPPZIPCODE, SUPPCITY, SUPPPHONE, SUPPFAX, SUPPEMAIL, SUPPLIERTYPE, BUYERCODE, STOCKNAME, PLANTBUNAME, STOCKSTREET, STOCKZIPCODE, STOCKCITY, STOCKSTATECOUNTY, PLANTBUPHONE, PLANTBUFAX, PLANTBUEMAIL, PLANTCOMPANY_ID, PLANTCOMPANYCODE, PLANTCOMPANYNAME, PCYSTREET, PCYZIPCODE, PCYCITY, PCYSTATECOUNTY, POAYSTATECOUNTY, PLANTCOMPANYPHONE, PLANTCOMPANYFAX, PLANTCOMPANYEMAIL
, PLANTCOMPANYVAT, PURCHASEORDERNUMBER, ORDERDATE, REQUESTEDDATE, DISCOUNTPERCOVERALL, DISCOUNTPERCDAYS, DISCOUNTWITHINDAYS, PAYMENTTERMS, DELIVERYTERMS, PHREMARK, PHREMARK_NULL, SUPPSTATECOUNTY, PRODUCTLINKCODE, SUPPLIERPRODUCTCODE, SUPPLIERSIZECODE, SUPPLIERPRODUCTDESC, UNIQUEITEM, PRINTPRICEONPO, PURCHASEPRICE, PLIREMARK, PLIREMARK_NULL, CURRENCYCODE, PRICEDECIMALS, PURCHASEORDERHEADER_ID, ORIGIN, LANGUAGECODE, LAUNDRYSIZECODE, QUALITYGRADECODE, ADDRESSINAME
, ADDRESSISTREET1, ADDRESSIZIPCODE, ADDRESSICITY, EMBLEMPO, TOTALAMOUNT)
as select nvl(sum(wokli.quantityordered - wokli.quantitycancelled),0) wolqtyordered1, nvl(sum(wol.quantityordered - wokli.quantitycancelled),0) wolqtyordered2, pli.purchaseorderline_id,
   coalesce( (SELECT modification_desc.description
        FROM   modification_desc
        WHERE  modification_desc.modification_id =
               modification.modification_id
               AND modification_desc.language_id = languages.language_id), modification.code )modif,pli.quantityordered, pli.quantitycancelled,
  supplier.suppliernumber suppNumber, supplier.name suppName, addressSup.Street SuppStreet
, addressSup.Zipcode SuppZipCode, addressSup.City SuppCity, supplier.phone SuppPhone
, supplier.fax Suppfax, supplier.email Suppemail, supplier.suppliertype suppliertype
, sksp.buyercode, sk.name stockName, plantBU.name plantBUName, /*cast(*/CONCATENATEWITHBLANK(addressSK.Street, addressSK.Street2) /*as varchar2(60))*/ STOCKstreet
, addressSK.Zipcode STOCKzipcode, addressSK.City STOCKcity
, /*cast(*/CONCATENATEWITHBLANK3(addressSK.State,'/',addressSK.County)/* as varchar2(60))*/ STOCKStateCounty
, plantBU.phoneno plantBUPhone, plantBU.Faxno plantBUFax, plantBU.email plantBUEmail
, plantcompany.plantcompany_id, plantcompany.code plantcompanyCode, plantcompany.name plantcompanyName, addressPCY.Street PCYStreet
, addressPCY.Zipcode PCYZipCode, addressPCY.City PCYCity
, /*cast(*/CONCATENATEWITHBLANK3(addressPCY.State,'/',addressPCY.County) /*as varchar2(60))*/ PCYStateCounty
, /*cast(*/CONCATENATEWITHBLANK3(poai.state,'/',poai.county) /*as varchar2(255))*/ POAYStateCounty
, plantcompany.phone plantcompanyPhone, plantcompany.fax plantcompanyFax, plantcompany.email plantcompanyEmail, plantcompany.vatnumber plantcompanyVAT
, ph.purchaseordernumber, ph.orderdate,  ph.requesteddate
, supplier.discountpercoverall, supplier.discountpercdays, supplier.discountwithindays
, /*cast(*/supplier.paymentterms/* as varchar2(60)) paymentterms*/,/* cast(*/supplier.deliveryterms/* as varchar2(60))*/ deliveryterms
, ph.remark PHRemark,  case when ph.remark is null then 'Y' else 'N' end PHRemark_null,
 cast(CONCATENATEWITHBLANK3(addressSup.State,'/',addressSup.County) as varchar2(255)) SuppStateCounty
, product_link.code productLinkCode, pli.supplierproductcode, pli.suppliersizecode
, coalesce
  (( select splprd.supplierproductdescription from supplierproduct splprd
          where pli.supplierproductcode = splprd.supplierproductcode
             and pli.suppliersizecode = splprd.suppliersizecode
                 and supplier.supplier_id = splprd.supplier_id)
   ,( select product_desc.description from product_desc where product_desc.product_id = pli.product_link_id
            and product_desc.language_id = languages.language_id )) supplierProductDesc
, pli.uniqueitem
, supplier.printPriceOnPO
, pli.purchaseprice
, pli.remark PLIRemark, case when pli.remark is null then 'Y' else 'N' end PLIRemark_null
, currency.code currencyCode, currency.decimals pricedecimals
, ph.purchaseorderheader_id
, ph.origin
, languages.code languageCode
, sizedefinition_link.code LaundrySizeCode
, /*cast(*/(select qg.Code from QualityGrade qg where pli.requestedgrade_id = qg.qualitygrade_id) /*as varchar2(60))*/QualityGradeCode
, poai.name addressiname, poai.street1 addressistreet1, poai.zipcode addressizipcode, poai.city addressicity,
      coalesce((select count(p.product_id) from product p where pli.product_link_id=p.product_id and p.typeofmerchandise=4),0) emblempo,
      (select sum((pol.quantityordered-pol.quantitycancelled)) from purchaseorderheader poh2 join purchaseorderline pol on poh2.purchaseorderheader_id=pol.purchaseorderheader_id where poh2.purchaseorderheader_id=ph.purchaseorderheader_id) totalamount
from
  purchaseorderheader ph
    left outer join
         ( plantcompany join address addressPCY on plantcompany.address_id = addressPCY.Address_Id
         ) on ph.plantcompany_id = plantcompany.plantcompany_id
    left outer join stockroomsupplier sksp
          on ph.stockroom_id = sksp.stockroom_id and ph.supplier_id = sksp.supplier_id
    left outer join
         ( stockroom sk
                join ( businessunit bu join plant plantBU on bu.plant_id = plantBU.plant_id )
                  on sk.managedbybu_id = bu.businessunit_id
                join address addressSK on sk.deliveryaddress_id = addressSK.address_id
          ) on ph.stockroom_id = sk.stockroom_id
    left outer join
         ( purchaseorderline pli
                             join product_link on pli.product_link_id = product_link.product_link_id
                             join sizedefinition_link on pli.sizedefinition_link_id = sizedefinition_link.sizedefinition_link_id
                             left outer join workorderline wokli on (wokli.purchaseorderline_id=pli.purchaseorderline_id )
                             left outer join workorderlinepurchordline wolpol on wolpol.purchaseorderline_id=pli.purchaseorderline_id
                                             left outer join workorderline wol on wol.workorderline_id=wolpol.workorderline_id
                             LEFT   OUTER JOIN(workorderlinemodification
                             INNER JOIN   modification ON workorderlinemodification.modification_id = modification.modification_id)
                             ON  workorderlinemodification.workorderline_id=nvl(wokli.workorderline_id, wol.workorderline_id)
         ) on ph.purchaseorderheader_id = pli.purchaseorderheader_id
    left outer join  purchaseorderaddressinfo poai on poai.purchaseorderheader_id=ph.purchaseorderheader_id
, status, supplier, address addressSup, currency, languages
where ph.supplier_id = supplier.supplier_id
and supplier.address_id = addressSup.address_id
and ph.status_id = status.status_id
and ph.currency_id = currency.currency_id
group by supplier.suppliernumber, supplier.name, addressSup.Street, addressSup.Zipcode, addressSup.City, supplier.phone, supplier.fax, supplier.email, supplier.suppliertype
, sksp.buyercode, sk.name, plantBU.name,addressSK.Street, addressSK.Street2, addressSK.Zipcode, addressSK.City
,addressSK.State,addressSK.County
, plantBU.phoneno, plantBU.Faxno, plantBU.email, plantcompany.plantcompany_id, plantcompany.code, plantcompany.name, addressPCY.Street, addressPCY.Zipcode, addressPCY.City
, addressPCY.State,addressPCY.County
,poai.state,poai.county
, plantcompany.phone, plantcompany.fax, plantcompany.email, plantcompany.vatnumber
, ph.purchaseordernumber, ph.orderdate,  ph.requesteddate
, supplier.discountpercoverall, supplier.discountpercdays, supplier.discountwithindays
, supplier.paymentterms,supplier.deliveryterms
, ph.remark,
 addressSup.State,addressSup.County, product_link.code, pli.supplierproductcode, pli.suppliersizecode,
 pli.uniqueitem, pli.quantityordered, supplier.printPriceOnPO, pli.purchaseprice
, pli.remark,supplier.supplier_id, pli.product_link_id,
 currency.code, currency.decimals
, ph.purchaseorderheader_id, pli.purchaseorderline_id
, ph.origin, pli.quantitycancelled
, languages.code,sizedefinition_link.code,pli.requestedgrade_id, poai.name, poai.street1, poai.zipcode, poai.city, languages.language_id,  modification.modification_id,modification.code

/
create or replace view V_PURCHASEORDER_HOW
 (SUPPNUMBER, SUPPNAME, SUPPSTREET, SUPPZIPCODE, SUPPCITY, SUPPPHONE, SUPPSTATECOUNTY, SUPPFAX, SUPPEMAIL, SUPPLIERTYPE, BUYERCODE, STOCKCODE, STOCKNAME, PLANTBUNAME, STOCKSTREET, STOCKZIPCODE, STOCKCITY, STOCKSTATECOUNTY, PLANTBUPHONE, PLANTBUFAX, PLANTBUEMAIL, PLANTCOMPANY_ID, PLANTCOMPANYCODE, PLANTCOMPANYNAME, PCYSTREET, PCYZIPCODE, PCYCITY, PCYSTATECOUNTY, PLANTCOMPANYPHONE, PLANTCOMPANYFAX, PLANTCOMPANYEMAIL, PLANTCOMPANYVAT, PURCHASEORDERNUMBER, ORDERDATE, REQUESTEDDATE
, DISCOUNTPERCOVERALL, DISCOUNTPERCDAYS, DISCOUNTWITHINDAYS, PAYMENTTERMS, DELIVERYTERMS, PHREMARK, PHREMARK_NULL, 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, SHOWMODIFICATIONS, LANGUAGECODE, ADDRESSINAME, ADDRESSISTREET1, ADDRESSIZIPCODE, ADDRESSICITY)
as select supplier.suppliernumber suppNumber, supplier.name suppName, addressSup.Street SuppStreet
, addressSup.Zipcode SuppZipCode, addressSup.City SuppCity, supplier.phone SuppPhone
, cast(CONCATENATEWITHBLANK3(addressSup.State,'/',addressSup.County) as varchar2(255)) SuppStateCounty
, supplier.fax Suppfax, supplier.email Suppemail,supplier.suppliertype suppliertype
, sksp.buyercode, sk.code stockCode, sk.name stockName, plantBU.name plantBUName, cast(CONCATENATEWITHBLANK(addressSK.Street, addressSK.Street2) as varchar2(255)) STOCKstreet
, addressSK.Zipcode STOCKzipcode, addressSK.City STOCKcity
, cast(CONCATENATEWITHBLANK3(addressSK.State,'/',addressSK.County) as varchar2(255)) STOCKStateCounty
, plantBU.phoneno plantBUPhone, plantBU.Faxno plantBUFax, plantBU.email plantBUEmail
, plantcompany.plantcompany_id, plantcompany.code plantcompanyCode, plantcompany.name plantcompanyName, addressPCY.Street PCYStreet
, addressPCY.Zipcode PCYZipCode, addressPCY.City PCYCity
, cast(CONCATENATEWITHBLANK3(addressPCY.State,'/',addressPCY.County) as varchar2(255)) PCYStateCounty
, plantcompany.phone plantcompanyPhone, plantcompany.fax plantcompanyFax, plantcompany.email plantcompanyEmail, plantcompany.vatnumber plantcompanyVAT
, ph.purchaseordernumber, ph.orderdate, ph.requesteddate
, supplier.discountpercoverall, supplier.discountpercdays, supplier.discountwithindays
, supplier.paymentterms, supplier.deliveryterms
, ph.remark PHRemark,  case when ph.remark is null then 'Y' else 'N' end PHRemark_null
, product_link.code productLinkCode, pli.supplierproductcode, pli.suppliersizecode
, coalesce
  (( select splprd.supplierproductdescription from supplierproduct splprd
          where pli.supplierproductcode = splprd.supplierproductcode
             and pli.suppliersizecode = splprd.suppliersizecode
                 and supplier.supplier_id = splprd.supplier_id)
   ,( select product_desc.description from product_desc where product_desc.product_id = pli.product_link_id
            and product_desc.language_id = languages.language_id )) supplierProductDesc
, pli.uniqueitem, pli.quantityordered
, supplier.printPriceOnPO
, pli.purchaseprice, (pli.quantityordered * pli.purchaseprice) amount
, pli.remark PLIRemark, case when pli.remark is null then 'Y' else 'N' end PLIRemark_null
, currency.code currencyCode, currency.decimals pricedecimals, currency.invoiceamountdecimals amountdecimals
, ph.purchaseorderheader_id, pli.purchaseorderline_id
, status.code statusCode, ph.origin, ph.approvaldate, ph.approvaluser_id
, ( select status_desc.description from status_desc where status_desc.status_id = status.status_id
  and status_desc.language_id = languages.language_id ) statusDesc
, pli.quantityreceived, pli.quantitycancelled, pli.quantityconfirmed
, (select count(*) from workorderline wl, workorderlinemodification wm
   where wl.purchaseorderline_id = pli.purchaseorderline_id
     and wl.workorderline_id = wm.workorderline_id
   having sum(wl.quantityordered - wl.quantityfilled) > 0) +
   (select count(*) from workorderline wl, workorderlinemodification wm, workorderlinepurchordline wolpol
   where pli.purchaseorderline_id=wolpol.workorderlinepurchordline_id and wl.workorderline_id=wolpol.workorderline_id
     and wl.workorderline_id = wm.workorderline_id
   having sum(wl.quantityordered - wl.quantityfilled) > 0) showmodifications
/*, coalesce((select count(*) from workorderline wl, workorderlinemodification wm
   where wl.purchaseorderline_id = pli.purchaseorderline_id
     and wl.workorderline_id = wm.workorderline_id
   having sum(wl.quantityordered - wl.quantitycancelled - wl.quantityfilled) > 0),0) showmodifications  */
, languages.code languageCode
,poai.name addressiname, poai.street1 addressistreet1, poai.zipcode addressizipcode, poai.city addressicity
from
  purchaseorderheader ph
    left outer join
         ( plantcompany join address addressPCY on plantcompany.address_id = addressPCY.Address_Id
         ) on ph.plantcompany_id = plantcompany.plantcompany_id
    left outer join stockroomsupplier sksp
          on ph.stockroom_id = sksp.stockroom_id and ph.supplier_id = sksp.supplier_id
    left outer join
         ( stockroom sk
                join ( businessunit bu join plant plantBU on bu.plant_id = plantBU.plant_id )
                  on sk.managedbybu_id = bu.businessunit_id
                join address addressSK on sk.deliveryaddress_id = addressSK.address_id
          ) on ph.stockroom_id = sk.stockroom_id
    left outer join
         ( purchaseorderline pli join product_link on pli.product_link_id = product_link.product_link_id
         ) on ph.purchaseorderheader_id = pli.purchaseorderheader_id
    left outer join  purchaseorderaddressinfo poai on poai.purchaseorderheader_id=ph.purchaseorderheader_id
, status, supplier, address addressSup, currency, languages
where
        ph.supplier_id = supplier.supplier_id
    and supplier.address_id = addressSup.address_id
and ph.status_id = status.status_id
and ph.currency_id = currency.currency_id

/
create or replace view V_PURCHASEORDER_POS
 (SUPPNUMBER, SUPPNAME, SUPPSTREET, SUPPHOUSENUMBER, SUPPHOUSENUMBEREXT, SUPPZIPCODE, SUPPCITY, SUPPPHONE, SUPPSTATE, SUPPSTATECOUNTY, SUPPFAX, SUPPEMAIL, SUPPLIERTYPE, BUYERCODE, STOCKCODE, STOCKNAME, PLANTBUNAME, STOCKSTREET, STOCKSTREET2, STOCKZIPCODE, STOCKCITY, STOCKSTATE, STOCKHOUSENUMBER, STOCKHOUSENUMBEREXT, STOCKSTATECOUNTY, PLANTBUPHONE, PLANTBUFAX, PLANTBUEMAIL, PLANTCOMPANY_ID, PLANTCOMPANYCODE, PLANTCOMPANYNAME, PCYSTREET, PCYZIPCODE, PCYCITY, PCYSTATECOUNTY, PLANTCOMPANYPHONE
, PLANTCOMPANYFAX, PLANTCOMPANYEMAIL, PLANTCOMPANYVAT, PURCHASEORDERNUMBER, ORDERDATE, REQUESTEDDATE, DISCOUNTPERCOVERALL, DISCOUNTPERCDAYS, DISCOUNTWITHINDAYS, PAYMENTTERMS, DELIVERYTERMS, PHREMARK, PHREMARK_NULL, 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, SUPPCONTACTPERS, PLANTCODE, PLANTNAME, PLANTPHONE, PLANTFAX, PLANTEMAIL, PLANTCONTACTPERS, POSBUYERNAME, POSBUYEREMAIL, UNIT, LAYOUTCODE)
as select
  supplier.suppliernumber suppNumber, supplier.name suppName, addressSup.Street SuppStreet, addressSup.Housenumber SuppHousenumber, addressSup.Housenumberext SuppHousenumberext
, addressSup.Zipcode SuppZipCode, addressSup.City SuppCity, supplier.phone SuppPhone, addressSup.State SuppState
, cast(CONCATENATEWITHBLANK3(addressSup.State,'/',addressSup.County) as varchar2(255)) SuppStateCounty
, supplier.fax Suppfax, supplier.email Suppemail,supplier.suppliertype suppliertype
, sksp.buyercode, sk.code stockCode, sk.name stockName, plantBU.name plantBUName
--, cast(CONCATENATEWITHBLANK(addressSK.Street, addressSK.Street2) as varchar2(255)) STOCKstreet
, addressSK.Street STOCKstreet, addressSK.Street2 STOCKstreet2
, addressSK.Zipcode STOCKzipcode, addressSK.City STOCKcity, addressSK.State STOCKstate
, addressSK.Housenumber StockHousenumber, addressSK.Housenumberext StockHousenumberext
, cast(CONCATENATEWITHBLANK3(addressSK.State,'/',addressSK.County) as varchar2(255)) STOCKStateCounty
, plantBU.phoneno plantBUPhone, plantBU.Faxno plantBUFax, plantBU.email plantBUEmail
, plantcompany.plantcompany_id, plantcompany.code plantcompanyCode, plantcompany.name plantcompanyName, addressPCY.Street PCYStreet
, addressPCY.Zipcode PCYZipCode, addressPCY.City PCYCity
, cast(CONCATENATEWITHBLANK3(addressPCY.State,'/',addressPCY.County) as varchar2(255)) PCYStateCounty
, plantcompany.phone plantcompanyPhone, plantcompany.fax plantcompanyFax, plantcompany.email plantcompanyEmail, plantcompany.vatnumber plantcompanyVAT
, ph.purchaseordernumber, ph.orderdate, ph.requesteddate
, supplier.discountpercoverall, supplier.discountpercdays, supplier.discountwithindays
, supplier.paymentterms, supplier.deliveryterms
, ph.remark PHRemark,  case when ph.remark is null then 'Y' else 'N' end PHRemark_null
, product_link.code productLinkCode, pli.supplierproductcode, pli.suppliersizecode
, coalesce ((select product_desc.longdescription
    from product_desc where product_desc.product_id = pli.product_link_id
    and product_desc.language_id  = languages.language_id    )
    ,(select splprd.supplierproductdescription
    from supplierproduct splprd where pli.supplierproductcode = splprd.supplierproductcode
    and pli.suppliersizecode = splprd.suppliersizecode and supplier.supplier_id = splprd.supplier_id)
    ) supplierproductdesc
, pli.uniqueitem, pli.quantityordered
, supplier.printPriceOnPO
, pli.purchaseprice, (pli.quantityordered * pli.purchaseprice) amount
, pli.remark PLIRemark, case when pli.remark is null then 'Y' else 'N' end PLIRemark_null
, currency.code currencyCode, currency.decimals pricedecimals, currency.invoiceamountdecimals amountdecimals
, ph.purchaseorderheader_id, pli.purchaseorderline_id
, status.code statusCode, ph.origin, ph.approvaldate, ph.approvaluser_id
, ( select status_desc.description from status_desc where status_desc.status_id = status.status_id
  and status_desc.language_id = languages.language_id ) statusDesc
, pli.quantityreceived, pli.quantitycancelled, pli.quantityconfirmed
, languages.code languageCode
, sizedefinition_link.code LaundrySizeCode
, (select min(c.name) from contactperson c where c.supplier_id = supplier.supplier_id and c.contactpersonnumber in (select min(cp.contactpersonnumber) from contactperson cp where cp.supplier_id = supplier.supplier_id)) SuppContactPers
, pl.code PlantCode, pl.name PlantName, pl.phoneno PlantPhone, pl.faxno PlantFax, pl.email PlantEMail
, (select emp.name from employee emp where sk.responsibleemployee_id = emp.employee_id) PlantContactPers
, su.fullname POSBuyerName, su.remark POSBuyerEmail
--, (select rud.description from registrationunit_desc rud, product prod where product_link.product_link_id = prod.product_id and prod.registrationunit_id = rud.registrationunit_id and rud.language_id = pl.language_id) Unit
, case when pli.packing = 0 then 'Each'
       when pli.packing = 1 then 'Box'
       when pli.packing = 2 then 'Case'
       when pli.packing = 3 then 'Dozen'
            else '' end Unit
, (select fm.code from formlayout fm where supplier.formlayout_id = fm.formlayout_id) layoutcode
from
  purchaseorderheader ph
    left outer join
         ( plantcompany join address addressPCY on plantcompany.address_id = addressPCY.Address_Id
         ) on ph.plantcompany_id = plantcompany.plantcompany_id
    left outer join stockroomsupplier sksp
          on ph.stockroom_id = sksp.stockroom_id and ph.supplier_id = sksp.supplier_id
    left outer join
         ( stockroom sk
                join ( businessunit bu join plant plantBU on bu.plant_id = plantBU.plant_id )
                  on sk.managedbybu_id = bu.businessunit_id
                join address addressSK on sk.deliveryaddress_id = addressSK.address_id
          ) on ph.stockroom_id = sk.stockroom_id
    left outer join
         ( purchaseorderline pli
                             join product_link on pli.product_link_id = product_link.product_link_id
                             join sizedefinition_link on pli.sizedefinition_link_id = sizedefinition_link.sizedefinition_link_id
         ) on ph.purchaseorderheader_id = pli.purchaseorderheader_id
    left outer join systemuser su on ph.approvaluser_id = su.systemuser_id
, status, supplier, address addressSup, currency, languages
, businessunit phbu, plant pl
where
        ph.supplier_id = supplier.supplier_id
    and supplier.address_id = addressSup.address_id
and ph.status_id = status.status_id
and ph.currency_id = currency.currency_id
and ph.businessunit_id = phbu.businessunit_id
and phbu.plant_id = pl.plant_id

/
create or replace view V_PURCHASEORDER_VEN
 (SUPPNUMBER, SUPPNAME, SUPPSTREET, SUPPZIPCODE, SUPPCITY, SUPPPHONE, SUPPSTATECOUNTY, SUPPFAX, SUPPEMAIL, SUPPLIERTYPE, BUYERCODE, STOCKCODE, STOCKNAME, PLANTBUNAME, STOCKSTREET, STOCKZIPCODE, STOCKCITY, STOCKSTATECOUNTY, PLANTBUPHONE, PLANTBUFAX, PLANTBUEMAIL, PLANTCOMPANY_ID, PLANTCOMPANYCODE, PLANTCOMPANYNAME, PCYSTREET, PCYZIPCODE, PCYCITY, PCYSTATECOUNTY, PLANTCOMPANYPHONE, PLANTCOMPANYFAX, PLANTCOMPANYEMAIL, PLANTCOMPANYVAT, PURCHASEORDERNUMBER, ORDERDATE, REQUESTEDDATE
, DISCOUNTPERCOVERALL, DISCOUNTPERCDAYS, DISCOUNTWITHINDAYS, PAYMENTTERMS, DELIVERYTERMS, PHREMARK, PHREMARK_NULL, PRODUCTLINKCODE, SUPPLIERPRODUCTCODE, SUPPLIERSIZECODE, SUPPLIERPRODUCTDESC, UNIQUEITEM, QUANTITYORDERED, PRINTPRICEONPO, PURCHASEPRICE, AMOUNT, PLIREMARK, PLIREMARK_NULL, CURRENCYCODE, PRICEDECIMALS, AMOUNTDECIMALS, PURCHASEORDERHEADER_ID, PURCHASEORDERLINE_ID, STATUSCODE, ORIGIN, APPROVALDATE, APPROVALUSER_ID, SYU_FULLNAME, STATUSDESC, QUANTITYRECEIVED
, QUANTITYCANCELLED, QUANTITYCONFIRMED, CONFIRMEDDATE, LANGUAGECODE)
as select
  supplier.suppliernumber suppNumber, supplier.name suppName, addressSup.Street SuppStreet
, addressSup.Zipcode SuppZipCode, addressSup.City SuppCity, supplier.phone SuppPhone
, cast(CONCATENATEWITHBLANK3(addressSup.State,'/',addressSup.County) as varchar2(255)) SuppStateCounty
, supplier.fax Suppfax, supplier.email Suppemail,supplier.suppliertype suppliertype
, sksp.buyercode, sk.code stockCode, sk.name stockName, plantBU.name plantBUName, cast(CONCATENATEWITHBLANK(addressSK.Street, addressSK.Street2) as varchar2(255)) STOCKstreet
, addressSK.Zipcode STOCKzipcode, addressSK.City STOCKcity
, cast(CONCATENATEWITHBLANK3(addressSK.State,'/',addressSK.County) as varchar2(255)) STOCKStateCounty
, plantBU.phoneno plantBUPhone, plantBU.Faxno plantBUFax, plantBU.email plantBUEmail
, plantcompany.plantcompany_id, plantcompany.code plantcompanyCode, plantcompany.name plantcompanyName, addressPCY.Street PCYStreet
, addressPCY.Zipcode PCYZipCode, addressPCY.City PCYCity
, cast(CONCATENATEWITHBLANK3(addressPCY.State,'/',addressPCY.County) as varchar2(255)) PCYStateCounty
, plantcompany.phone plantcompanyPhone, plantcompany.fax plantcompanyFax, plantcompany.email plantcompanyEmail, plantcompany.vatnumber plantcompanyVAT
, ph.purchaseordernumber, ph.orderdate, ph.requesteddate
, supplier.discountpercoverall, supplier.discountpercdays, supplier.discountwithindays
, supplier.paymentterms, supplier.deliveryterms
, ph.remark PHRemark,  case when ph.remark is null then 'Y' else 'N' end PHRemark_null
, product_link.code productLinkCode, pli.supplierproductcode, pli.suppliersizecode
, coalesce
  (( select splprd.supplierproductdescription from supplierproduct splprd
          where pli.supplierproductcode = splprd.supplierproductcode
             and pli.suppliersizecode = splprd.suppliersizecode
                 and supplier.supplier_id = splprd.supplier_id)
   ,( select product_desc.description from product_desc where product_desc.product_id = pli.product_link_id
            and product_desc.language_id = languages.language_id )) supplierProductDesc
, pli.uniqueitem, pli.quantityordered
, supplier.printPriceOnPO
, pli.purchaseprice, (pli.quantityordered * pli.purchaseprice) amount
, pli.remark PLIRemark, case when pli.remark is null then 'Y' else 'N' end PLIRemark_null
, currency.code currencyCode, currency.decimals pricedecimals, currency.invoiceamountdecimals amountdecimals
, ph.purchaseorderheader_id, pli.purchaseorderline_id
, status.code statusCode, ph.origin, ph.approvaldate, ph.approvaluser_id
, (select syu.fullname from systemuser syu where syu.systemuser_id = ph.approvaluser_id ) syu_fullname
, ( select status_desc.description from status_desc where status_desc.status_id = status.status_id
  and status_desc.language_id = languages.language_id ) statusDesc
, pli.quantityreceived, pli.quantitycancelled, pli.quantityconfirmed, pli.confirmeddate
, languages.code languageCode
from
  purchaseorderheader ph
    left outer join
         ( plantcompany join address addressPCY on plantcompany.address_id = addressPCY.Address_Id
         ) on ph.plantcompany_id = plantcompany.plantcompany_id
    left outer join stockroomsupplier sksp
          on ph.stockroom_id = sksp.stockroom_id and ph.supplier_id = sksp.supplier_id
    left outer join
         ( stockroom sk
                join ( businessunit bu join plant plantBU on bu.plant_id = plantBU.plant_id )
                  on sk.managedbybu_id = bu.businessunit_id
                join address addressSK on sk.deliveryaddress_id = addressSK.address_id
          ) on ph.stockroom_id = sk.stockroom_id
    left outer join
         ( purchaseorderline pli join product_link on pli.product_link_id = product_link.product_link_id
         ) on ph.purchaseorderheader_id = pli.purchaseorderheader_id
, status, supplier, address addressSup, currency, languages
where
        ph.supplier_id = supplier.supplier_id
    and supplier.address_id = addressSup.address_id
and ph.status_id = status.status_id
and ph.currency_id = currency.currency_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, LANGUAGECODE, REJECTEDQTY)
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) REJECTEDQTY
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 = 3
    AND DV.ORIGIN = 1
GROUP BY CN.CONSIGNMENTNOTENUMBER, CN.CONSIGNMENTNOTE_ID
, PRD.CODE, PRD.PRODUCT_ID, LANGUAGES.LANGUAGE_ID, LANGUAGES.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, rp.date_value1, p.typeofmerchandise) price,
  dh.pieceweight,
  F_GETPOUNDPRICE(p.product_id, f.finishingmethod_id, sl.sizedefinition_link_id, cu.customer_id, p.weighingcategory_id, rp.date_value1) 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, rp.date_value1,
    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_QUANTITIESRESTOCKINGNEW_ANG
 (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)
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
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_QUANTITIESRESTOCKING_ANG
 (WEBSESSION_ID, WEBUSER_ID, WEBUSERDEPARTMENT_ID, DEPARTMENT_ID, CUSTOMERNAME, CUSTOMERNUMBER, DEPARTMENTDESC, DEPARTMENTNUMBER, DISTRIBUTIONPOINTDESC, DISTRIBUTIONPOINTNUMBER, AMOUNTDELIVERED, THEORETICALWEIGHT, PRODUCTDESC, PRODUCTCODE, PRODUCTGROUPCODE, SIZECODE, SIZEDESC, FINISHINGMETHODCODE, ACTIVITYCODE, FINISHINGMETHODDESC, PRICE, PIECEWEIGHT, POUNDPRICE, 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,
  (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.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
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_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, GETDATEONLY(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_RAGGEDITEMSFROMCIRC_POS
 (BUSINESSUNIT, BUSINESSUNITDESCRIPTION, CUSTOMERNUMBER, CUSTOMERNAME, WEARERNUMBER, WEARERNAME, RAGGEDITEMDATE, PRODUCTCODE, PRODUCTDESC, SIZECODE, PRIMARYID, REASONCODE, REASONCODE_DESC, FIRSTISSUEDATE, WASHESTOTAL, RESIDUALVALUE, REPLACEMENTID, REPLACEMENTDATE, RAGGINGFEE, PREPCHARGE, RAGREASON, DEPARTMENTNUMBER, DEPARTMENTDESC, LANGUAGE_ID, LANGUAGECODE, STREET, STREET2, ZIPCODE, CITY, STATE, REPLACEMENTWORKORDER_ID, CHAIN_CODE)
as select bu.code businessunit
,      bu.description businessunitdescription
,      coalesce(c.customernumber, cl.customernumber)  customernumber
,      coalesce(c.name, cl.name) customername
,      coalesce(w.wearernumber, wl.wearernumber) wearernumber
,      coalesce(w.fullname, wl.wearername) wearername
,      trunc(ri.ragtimestamp) raggeditemdate
,      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
,      ri.primaryid
,      rs.code reasoncode
,      (select rsd.description from ragreason_desc rsd where rsd.ragreason_id = ri.ragreason_id and rsd.language_id = l.language_id) reasoncode_desc
,      ri.lastissuedate firstissuedate
,      ri.washestotal
, case when ri.ragreason_id in (select rr.ragreason_id from ragreason rr where rr.chargeresidualvalue = 'N')
then 0 else ri.residualvalue end residualvalue--, null replacementid, null replacementdate
, nvl((select max(ui.primaryid) from uniqueitemfixedinfo uif, uniqueitem ui
where uif.issuedbyworkorder_id = ri.replacementworkorder_id and uif.uniqueitem_id = ui.uniqueitem_id)
 ,(select max(r.primaryid) from raggeditem r where r.issuedbyworkorder_id=ri.replacementworkorder_id)
) replacementid
, (select max(uif.lastissuedate) from uniqueitemfixedinfo uif, uniqueitem ui
where uif.issuedbyworkorder_id = ri.replacementworkorder_id and uif.uniqueitem_id = ui.uniqueitem_id) replacementdate
,        ( select pack_price.SpecialCharge_Price(csp.customer_id, csp.specialcharge_id, ri.ragtimestamp)
         from   customerspecialcharge csp, specialcharge sp
         where  csp.customer_id = c.customer_id
            and sp.specialcharge_id = csp.specialcharge_id and sp.fixedamount = 'Y'
            and ( select count(1)
                  from   invoicelinetypecharge ilc
                  where  ilc.specialcharge_id = csp.specialcharge_id
                     and ilc.invoicelinetype_id = 10) = 1) raggingfee
, case when rs.allowprepcharges <> 'Y' then 0
else
coalesce( ( select cpc.price
              from   customerprepcharge cpc, workorder wor
              where  cpc.customer_id = c.customer_id
                     and ri.replacementworkorder_id = wor.workorder_id
                 and cpc.reasoncode_id = wor.reasoncode_id
                 and cpc.startdate = ( select max(cpc2.startdate)
                                       from   customerprepcharge cpc2
                                       where  cpc2.customer_id = cpc.customer_id
                                          and cpc2.startdate <= ri.ragtimestamp
                                          and cpc2.reasoncode_id = cpc.reasoncode_id))
         ,  ( select cpc.price
         from   customerprepcharge cpc
         where  cpc.customer_id = c.customer_id
            and cpc.reasoncode_id is null
            and cpc.startdate = ( select max(cpc2.startdate)
                                  from   customerprepcharge cpc2
                                  where  cpc2.customer_id = cpc.customer_id
                                     and cpc2.startdate <= ri.ragtimestamp
                                     and cpc2.reasoncode_id is null))
        , 0)
end prepcharge-->>null replacementid, null replacementdate, both now always NULL-->>Both will be determined once workorderline_id is linked to raggeditem in version > 8.02.01
,      ( select rr.code
         from   ragreason rr
         where  rr.ragreason_id = ri.ragreason_id ) ragreason
,  coalesce( ( select dep.departmentnumber
         from   department dep
         where  dep.department_id = (select dp.department_id
                                     from   distributionpoint dp
                                     where  dp.distributionpoint_id = we.distributionpoint_id))
        , del.departmentnumber) departmentnumber
,  coalesce((select dep.description
         from   department dep
         where  dep.department_id = (select dp.department_id
                                     from   distributionpoint dp
                                     where  dp.distributionpoint_id = we.distributionpoint_id))
           , del.description) departmentdesc
, c.language_id
, l.code languagecode
, a.street, a.street2, a.zipcode, a.city, a.state
, ri.replacementworkorder_id,
(select ch.code from chain ch where ch.chain_id = c.chain_id) chain_code
from raggeditem ri
         left outer join distributionpoint_link dpl
                     inner join department_link del
                           inner join customer_link cl
                           on del.customer_link_id = cl.customer_link_id
                     on dpl.department_link_id = del.department_link_id
         on ri.distributionpoint_link_id = dpl.distributionpoint_link_id,
weareremployment_link wl
         left outer join (weareremployment we
                            inner join wearer w
                         on we.wearer_id = w.wearer_id)
            on we.weareremployment_id = wl.weareremployment_id
, businessunit bu, product_link p, sizedefinition s, reasoncode rs, status st
, customer c, address a, languages l
where    ri.businessunit_id = bu.businessunit_id
     and ri.weareremployment_link_id = wl.weareremployment_link_id
     and ri.product_link_id = p.product_id
     and ri.sizedefinition_link_id = s.sizedefinition_id
     and rs.reasoncode_id= coalesce((select wor.reasoncode_id from workorder wor where wor.workorder_id=ri.replacementworkorder_id), ri.reasoncode_id)
     and ri.prevstatus_id = st.status_id
         and (st.statustype <> 'UI' or st.code <> '10')
     and c.customer_id = coalesce(w.customer_id, cl.customer_id)
     and c.visitaddress_id = a.address_id
     and l.language_id = c.language_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)
as select och.outofcirculationhistory_id,
  cu.customernumber, cu.name CustomerName, we.wearernumber
, we.fullname, 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
, siz.code SizeCode
, (select sizedefinition_desc.description from sizedefinition_desc where sizedefinition_desc.sizedefinition_id = siz.sizedefinition_id
  and sizedefinition_desc.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
, 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--, su.username
, (select su.username from systemuser su where och.systemuser_id = su.systemuser_id) username
, DEPARTMENT.Departmentnumber, distributionpoint_link.distributionpointnumber ConsumptionPoint
, och.invoiceheader_id InvoicedYN, och.ragreason_id RaggedReturnedYN
, languages.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)) washestotal
from
 outofcirculationhistory och
       left outer join weareremployment wey
            inner join wearer we on we.wearer_id = wey.wearer_id
       on och.weareremployment_link_id = wey.weareremployment_id
, customer cu, product prd
, sizedefinition siz, reasoncode, DEPARTMENT, distributionpoint_link, productgroup
, languages, reportparam rp
where
    och.chargetype = 1
and och.customer_link_id = cu.customer_id
and och.product_link_id = prd.product_id
    and prd.productgroup_id = productgroup.productgroup_id
and och.sizedefinition_link_id = siz.sizedefinition_id
and och.reasoncode_id = reasoncode.reasoncode_id
and och.distributionpoint_link_id = distributionpoint_link.distributionpoint_link_id
    and distributionpoint_link.department_link_id = DEPARTMENT.Department_Id
        and DEPARTMENT.Customer_Id = cu.customer_id
and cu.customernumber >= rp.number_value1
and cu.customernumber <= rp.number_value2
and DEPARTMENT.Departmentnumber >= rp.number_value3
and DEPARTMENT.Departmentnumber <= rp.number_value4
and distributionpoint_link.distributionpointnumber >= rp.number_value5
and distributionpoint_link.distributionpointnumber <= rp.number_value6
and languages.code = rp.string_value
--and TRUNC(OCH.outofcircdate) >= rp.date_value1--moved in the report for peformance
--and TRUNC(OCH.outofcircdate) <= rp.date_value2
--and productgroup.code >= rp.string_value1
--and productgroup.code <= rp.string_value2
--and prd.code >= rp.string_value3
--and prd.code <= rp.string_value4
--and reasoncode.code >= rp.string_value5
--and reasoncode.code <= rp.string_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_RAGGEDRETURNEDITEMS_AUJ
 (OUTOFCIRCULATIONHISTORY_ID, REPORTPARAM_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, WASHESTOTAL)
as select och.outofcirculationhistory_id, rp.reportparam_id,
  cu.customernumber, cu.name CustomerName, we.wearernumber
, we.fullname, 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
, siz.code SizeCode
, (select sizedefinition_desc.description from sizedefinition_desc where sizedefinition_desc.sizedefinition_id = siz.sizedefinition_id
  and sizedefinition_desc.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
, 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--, su.username
, (select su.username from systemuser su where och.systemuser_id = su.systemuser_id) username
, DEPARTMENT.Departmentnumber, distributionpoint_link.distributionpointnumber ConsumptionPoint
, och.invoiceheader_id InvoicedYN, och.ragreason_id RaggedReturnedYN
, languages.code LanguageCode, och.customer_link_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)) washestotal
from
 outofcirculationhistory och
       left outer join weareremployment wey
            inner join wearer we on we.wearer_id = wey.wearer_id
       on och.weareremployment_link_id = wey.weareremployment_id
, customer cu, product prd
, sizedefinition siz, reasoncode, DEPARTMENT, distributionpoint_link, productgroup
, languages, reportparam rp
where
    och.chargetype = 1
and och.customer_link_id = cu.customer_id
and och.product_link_id = prd.product_id
    and prd.productgroup_id = productgroup.productgroup_id
and och.sizedefinition_link_id = siz.sizedefinition_id
and och.reasoncode_id = reasoncode.reasoncode_id
and och.distributionpoint_link_id = distributionpoint_link.distributionpoint_link_id
    and distributionpoint_link.department_link_id = DEPARTMENT.Department_Id
        and DEPARTMENT.Customer_Id = cu.customer_id
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, WEARERACTIVE, COSTCENTERCODE, COSTCENTERDESC, PRIMARYID, PRODUCTCODE, PRODUCTDESC, SIZECODE, SIZEDESC, FIRSTISSUEDATE, LASTISSUEDATE, WASHESTOTAL, REPAIRSTOTAL, REWASHTOTAL, DAYSINCIRCULATION, WEEKSINCIRCULATION
, MODIFICATIONS, CUSTOMEROWNED, REASONCODE, RAGREASONCODE, RAGREASONDESC, RIRESIDUALVALUE, CUSTOMERLANGUAGE_ID, LANGUAGE_ID, LANGUAGECODE, BUSINESSUNIT_ID, RESIDUALVALUE, TIMESTAMP, SYSTEM_USER)
as select
  ragi.ragtimestamp, GETDATEONLY(ragi.ragtimestamp) ragDate, cu.customernumber, cu.name customerName, address.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
, GETDATEDIFF(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) wearerActive
, cc.code costcenterCode, cc.description costcenterDesc
, 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
, 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 sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sz.sizedefinition_id
  and sdd.language_id = languages.language_id ) sizeDesc
, ragi.firstissuedate, ragi.lastissuedate, ragi.washestotal, ragi.repairstotal, ragi.rewashtotal
, ragi.daysincirculation, GETROUNDTOINTEGER(ragi.daysincirculation/7) weeksInCirculation
, ( select count(*) from wearerinventorymodification weim, wearerinventory weinv
    where ragi.weareremployment_link_id = weinv.weareremployment_id
    and ragi.product_link_id = weinv.product_id
        and ragi.sizedefinition_link_id = weinv.sizedefinition_id
    and weim.wearerinventory_id = weinv.wearerinventory_id) modifications
, ragi.customerowned, reasoncode.Code reasonCode, ragreason.code ragreasonCode
, ( select ragreason_desc.description from ragreason_desc where ragreason_desc.ragreason_id = ragreason.ragreason_id
  and ragreason_desc.language_id = languages.language_id ) ragreasonDesc, ragi.residualvalue RIresidualvalue
, cu.language_id customerlanguage_id, languages.language_id, languages.code languageCode
, ragi.businessunit_id
, coalesce((select max(ochy.tobechargedpercentage) from outofcirculationhistory ochy, uniqueitem_link uil
   where ochy.weareremployment_link_id = wemp.weareremployment_id and ochy.reasoncode_id = reasoncode.reasoncode_id and
  ochy.customer_link_id = cu.customer_id and ochy.distributionpoint_link_id = dip.distributionpoint_id and
  ochy.product_link_id = prd.product_id and ochy.ragreason_id = ragreason.ragreason_id and
  ochy.sizedefinition_link_id = sz.sizedefinition_id and
  ochy.uniqueitem_link_id = uil.uniqueitem_link_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 outer join reasoncode on ragi.reasoncode_id = reasoncode.reasoncode_id
, weareremployment wemp
    left outer join garmentdispenser gd on wemp.garmentdispenser_id = gd.garmentdispenser_id
    left outer join locker lk on wemp.locker_id = lk.locker_id
    left outer join wearerfunction wef on wemp.wearerfunction_id = wef.wearerfunction_id
, wearer we, customer cu, distributionpoint dip, department de, costcenter cc,
  product prd, sizedefinition sz, ragreason, address
, languages
, businessunit bu
where
    ragi.poolitem = 2
and ragi.weareremployment_link_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 ragi.distributionpoint_link_id = dip.distributionpoint_id
    and dip.department_id = de.department_id
        and dip.costcenter_id = cc.costcenter_id
and ragi.product_link_id = prd.product_id
and ragi.sizedefinition_link_id = sz.sizedefinition_id
and ragi.ragreason_id = ragreason.ragreason_id
and bu.businessunit_id = cu.defaultbusinessunit_id

/
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, GETDATEONLY(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_RECEIVEDITEMSFROMSUPPL_SMG
 (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, OOSPRODUCT)
as select
  sk.code stockCode, sk.name stockName, sk.stockroom_id, recSkhis.Receivedate, GETDATEONLY(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
, (select coalesce(oosp.status,0)
                from stockdefinitionperitem sdi,stockreservationpergrade srg
                left outer join outofserviceproduct oosp on srg.stockreservationpergrade_id = oosp.stockreservationpergrade_id
                where 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 srg.qualitygrade_id = recSkhis.Qualitygrade_Id
                and sdi.customer_id is null
                and (oosp.sequencenumber is null or oosp.sequencenumber = (select max(oosp1.sequencenumber) from outofserviceproduct oosp1
                where oosp1.stockreservationpergrade_id = srg.stockreservationpergrade_id))) OOSProduct
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, GETDATEONLY(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, GETDATEONLY(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_REFERENCE_CN_CIW
 (REMARKONDELIVERYNOTE, CONSIGNMENTNOTE_ID, CUSTOMER_ID, DISTRIBUTIONPOINT_ID)
as select distinct pn.remark remarkondeliverynote, cn.consignmentnote_id, c.customer_id, dp.distributionpoint_id
from distributionpoint dp, consignmentnote cn, customer c, department d, packingnote pn
where dp.department_id = d.department_id
and d.customer_id = c.customer_id
and cn.customer_link_id = c.customer_id
and cn.consignmentnote_id = pn.consignmentnote_id
and pn.distributionpoint_id = dp.distributionpoint_id
order by dp.distributionpoint_id

/
create or replace view V_REJECTEDSCANS
 (CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, TRANSACTIONTYPE_ID, TRANSACTIONTYPEDESC, WORKSTATIONCODE, WORKSTATIONDESC, USERNAME, FULLNAME, SCANTIMESTAMP, SCANDATE, SCANTIME_NUMBER, PRIMARYID, BUSINESSUNITCODE, BUSINESSUNIT_ID, BUSINESSUNITDESC, LANGUAGECODE, MULTIREADEXCEPTIONREASON_ID, REASON_CODE, SCANTIME_CHAR, REPORTPARAM_ID, NUMBER_VALUE5, NUMBER_VALUE6, PRODUCT_LINK_CODE, PRODUCT_LINK_DESC)
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(wst.code, ' ') workstationCode, wst.description workstationDesc
, 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
, rp.reportparam_id, rp.number_value5, rp.number_value6
, (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
from
  rejectedscan rs left outer join workstation wst on rs.scanstation = wst.code
       left outer join customer culk on culk.customer_id = rs.customer_link_id
, businessunit bu, SYSTEMUSER sy , languages, reportparam rp, transactiontype tt, multireadexceptionreason mre
where rs.businessunit_id = bu.businessunit_id
and rs.systemuser_id = sy.systemuser_id
and nvl(sy.username,' ') >= nvl(rp.string_value2,' ') and nvl(sy.username,' ') <= nvl(rp.string_value3,'ZZZZZZZZZZZZZZZZZZZZZ' )
and (coalesce(wst.code, ' ') >= coalesce(rp.string_value4, ' ') )
and (coalesce(wst.code, ' ') <= coalesce(rp.string_value5, 'ZZZZZZZZZZZZ') )
and rs.transactiontype_id = tt.transactiontype_id
and tt.transactiontype_id between rp.number_value1 and rp.number_value2
and rs.multireadexceptionreason_id = mre.multireadexceptionreason_id
and mre.multireadexceptionreason_id between rp.number_value3 and rp.number_value4
and trunc(rs.scantimestamp) >= TRUNC(rp.date_value1) and trunc(rs.scantimestamp) < TRUNC(rp.date_value2)
and languages.code = rp.string_value
and
(
(upper(rp.string_value1) = 'TRUE' and bu.businessunit_id = rp.number_value9)
or
  (upper(rp.string_value1) <> '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_REJECTEDSCANSPEREXCEPTION
 (CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, TRANSACTIONTYPE_ID, TRANSACTIONTYPEDESC, WORKSTATIONCODE, WORKSTATIONDESC, USERNAME, FULLNAME, SCANTIMESTAMP, SCANDATE, SCANTIME_NUMBER, PRIMARYID, BUSINESSUNITCODE, BUSINESSUNIT_ID, BUSINESSUNITDESC, LANGUAGECODE, MULTIREADEXCEPTIONREASON_ID, REASON_CODE, SCANTIME_CHAR, REPORTPARAM_ID, NUMBER_VALUE5, NUMBER_VALUE6)
as select culk.customer_id, culk.customernumber, culk.name CustomerName, rs.transactiontype_id
, (select transactiontype_desc.description from transactiontype_desc where transactiontype_desc.transactiontype_id = rs.transactiontype_id
  and transactiontype_desc.language_id = languages.language_id) transactiontypeDesc
, coalesce(wst.code, ' ') workstationCode, wst.description workstationDesc
, 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
, rp.reportparam_id, rp.number_value5, rp.number_value6
from
  rejectedscan rs left outer join workstation wst on rs.scanstation = wst.code
       left outer join customer culk on culk.customer_id = rs.customer_link_id
, businessunit bu, SYSTEMUSER sy , languages, reportparam rp, transactiontype tt, multireadexceptionreason mre
where rs.businessunit_id = bu.businessunit_id
and rs.systemuser_id = sy.systemuser_id
and nvl(sy.username,' ') >= nvl(rp.string_value2,' ') and nvl(sy.username,' ') <= nvl(rp.string_value3,'ZZZZZZZZZZZZZZZZZZZZZ' )
and (coalesce(wst.code, ' ') >= coalesce(rp.string_value4, ' ') )
and (coalesce(wst.code, ' ') <= coalesce(rp.string_value5, 'ZZZZZZZZZZZZ') )
and rs.transactiontype_id = tt.transactiontype_id
and tt.transactiontype_id between rp.number_value1 and rp.number_value2
and rs.multireadexceptionreason_id = mre.multireadexceptionreason_id
and mre.multireadexceptionreason_id between rp.number_value3 and rp.number_value4
and trunc(rs.scantimestamp) >= TRUNC(rp.date_value1) and trunc(rs.scantimestamp) < TRUNC(rp.date_value2)
and languages.code = rp.string_value
and
(
(upper(rp.string_value1) = 'TRUE' and bu.businessunit_id = rp.number_value9)
or
  (upper(rp.string_value1) <> '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_REJECTEDSCANSPERWORKSTATION
 (TRANSACTIONTYPE_ID, TRANSACTIONTYPEDESC, WORKSTATIONCODE, WORKSTATIONDESC, USERNAME, FULLNAME, SCANDATE, SCANTIME_NUMBER, BUSINESSUNITCODE, BUSINESSUNIT_ID, BUSINESSUNITDESC, MULTIREADEXCEPTIONREASON_ID, REASON_CODE, REPORTPARAM_ID, NUMBER_VALUE5, NUMBER_VALUE6)
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(wst.code, ' ') workstationCode,
       wst.description workstationDesc,
       sy.username,
       sy.fullname,
       trunc(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,
       rp.reportparam_id,
       rp.number_value5,
       rp.number_value6
  from rejectedscan rs left outer join workstation wst on rs.scanstation = wst.code,
    businessunit bu, SYSTEMUSER sy,
 languages, reportparam rp, transactiontype tt,
 multireadexceptionreason mre
 where rs.businessunit_id = bu.businessunit_id
   and rs.systemuser_id = sy.systemuser_id
   and nvl(sy.username, ' ') >= nvl(rp.string_value2, ' ')
   and nvl(sy.username, ' ') <= nvl(rp.string_value3, 'ZZZZZZZZZZZZZZZZZZZZZ')
   and (coalesce(wst.code, ' ') >= coalesce(rp.string_value4, ' '))
   and (coalesce(wst.code, ' ') <= coalesce(rp.string_value5, 'ZZZZZZZZZZZZ'))
   and rs.transactiontype_id = tt.transactiontype_id
   and tt.transactiontype_id between rp.number_value1 and rp.number_value2
   and rs.multireadexceptionreason_id = mre.multireadexceptionreason_id
   and mre.multireadexceptionreason_id between rp.number_value3 and rp.number_value4
   and trunc(rs.scantimestamp) >= TRUNC(rp.date_value1)
   and trunc(rs.scantimestamp) < TRUNC(rp.date_value2)
   and languages.code = rp.string_value
   and ((upper(rp.string_value1) = 'TRUE' and
       bu.businessunit_id = rp.number_value9) or
       (upper(rp.string_value1) <> '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_RENTALAGREEMENTS
 (DEPARTMENTNUMBER, DEP_DESP, DISTRIBUTIONPOINTNUMBER, DISTRIBPOINT_DESC, PRODUCTCODE, PRODUCTDESC, RENTINGPERIOD, DSCODE, QUANTITY, PRICE, DATEACTIVE, DATEINACTIVE, CUSTOMER_ID, PRODUCT_ID, SIZEDEFINITION_ID, FINISHINGMETHOD_ID, LAGUAGECODE, LASTINVOICESTARTDATE, LASTINVOICEENDDATE, AMOUNT)
as select dep.departmentnumber, dep.description Dep_desp, dp.distributionpointnumber, dp.description DistribPoint_desc
       , p.code ProductCode, (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
       ,ds.code dscode
       , (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 <= GETCURRENTDATE())
       end) Quantity
       --, f_rentprice(plpc.customer_id, p.product_id, plpc.sizedefinition_id, plpc.finishingmethod_id) Price
       , pack_price.Rent_Price(cu.customer_id, p.product_id, plpd.sizedefinition_id, plpd.finishingmethod_id, NULL, ds.frequency) Price
       , sdl.dateactive, sdl.dateinactive
       , cu.customer_id, plpd.product_id, plpd.sizedefinition_id, plpd.finishingmethod_id
       , lan.code LaguageCode
, (select coalesce(ih.nextperiodstartdate, ih.startdate) from invoiceheader ih where ih.invoiceheader_id =
  (select max(ih.invoiceheader_id)
    from invoiceheader ih, status st, invoiceline il, invoicelineproduct ilp
    where ih.status_id = st.status_id and st.statustype = 'IN' and st.code = '2' and ih.documenttype = 1
          and ih.invoiceheader_id = il.invoiceheader_id and il.invoicelinetype_id = 1
          and il.invoiceline_id = ilp.invoiceline_id
          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, status st, invoiceline il, invoicelineproduct ilp
    where ih.status_id = st.status_id and st.statustype = 'IN' and st.code = '2' and ih.documenttype = 1
          and ih.invoiceheader_id = il.invoiceheader_id and il.invoicelinetype_id = 1
          and il.invoiceline_id = ilp.invoiceline_id
          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, invoiceline il, invoicelineproduct ilp where ih.invoiceheader_id = il.invoiceheader_id
  and il.invoicelinetype_id = 1 and ilp.invoiceline_id = il.invoiceline_id 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, status st, invoiceline il, invoicelineproduct ilp
    where ih.status_id = st.status_id and st.statustype = 'IN' and st.code = '2' and ih.documenttype = 1
          and ih.invoiceheader_id = il.invoiceheader_id and il.invoicelinetype_id = 1
          and il.invoiceline_id = ilp.invoiceline_id
          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
from StandardDeliveryLine sdl, ProductListPerCustomer plpc, ProductListPerDistribPoint plpd,
     Distributionpoint dp, Department dep, Customer cu, Product p, Languages lan, deliveryscheme ds
where sdl.productlistpercustomer_id = plpc.productlistpercustomer_id and sdl.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
      and plpd.distributionpoint_id = dp.distributionpoint_id and dp.department_id = dep.department_id
      and dep.customer_id = cu.customer_id and plpc.product_id = p.product_id
      and plpc.billingmethod in (1, 3)
      and sdl.deliveryscheme_id=ds.deliveryscheme_id--used in report Customer Detail Recap, in subreport Rental Agreements

/
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
 a.year, a.week,
 e.departmentnumber, e.description departmentdesc,
 (case when (p.category = 1 and a.weareremployment_link_id is not null) then 1
       when (p.category = 1 and a.weareremployment_link_id is null) then 2
       when (p.category = 2 and a.weareremployment_link_id is not null) then 3
       when (p.category = 2 and a.weareremployment_link_id is null) then 4
      else 5
  end) groupingno,
 --w.wearernumber, w.wearername,
 (case when a.weareremployment_link_id is null
       then null
       else w.wearernumber end) wearernumber,
(case when a.weareremployment_link_id is null
       then null
       else w.wearername end) wearername,
 --d.distributionpointnumber, d.description distpointdesc,
(case when a.distributionpoint_link_id is null
       then null
       else d.distributionpointnumber end) distributionpointnumber,
(case when a.distributionpoint_link_id is null
       then null
       else d.description end) distpointdesc,
 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, languages.language_id,p.category, a.quantity, a.customerowned
from repairhistory a
 left outer join weareremployment_link w on (a.weareremployment_link_id = w.weareremployment_link_id)
 left outer join distributionpoint_link d on (a.distributionpoint_link_id = d.distributionpoint_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
 and a.amount <> 0 --todo 23122

/
create or replace view V_REPAIRHISTORYCC
 (YEAR, WEEK, DEPARTMENTNUMBER, DEPARTMENTDESC, WEARERNUMBER, WEARERNAME, REPAIRCODE, REPAIRDESC, MINUTES, UNITPRICE, PRICEPERMINUTE, AMOUNT, INVOICEHEADER_ID, LANGUAGECODE, CC_CODE_DESC, QUANTITY)
as select
 a.year, a.week,
 e.departmentnumber, e.description departmentdesc,
 w.wearernumber, w.wearername,
 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_REPAIRHISTORYPERCUSTOMER
 (LINETYPE, REPAIRHISTORY_ID, QUANTITY, YEAR, WEEK, YEARWEEK, CUSTOMERNUMBER, CUSTOMERNAME, 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, LOGDATE)
as select
  1 linetype, a.repairhistory_id, a.quantity, a.year, a.week, (a.year * 100 + a.week) yearweek,
  cl.customernumber, cl.name customername,
  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
, (select max(rh.repairdate) from repairhistory rh where rh.uniqueitem_link_id = a.uniqueitem_link_id
   and rh.repairtype_id = 63 and rh.repairdate <= a.repairdate) logdate   --wbo added
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
  and a.repairtype_id <> 63
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,
  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
, (select max(rh.repairdate) from repairhistory rh where rh.uniqueitem_link_id = a.uniqueitem_link_id
   and rh.repairtype_id = 63 and rh.repairdate <= a.repairdate) logdate --wbo added
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
  and a.repairtype_id <> 63

/
create or replace view V_REPAIRHISTORYPERCUSTOMER_POS
 (LINETYPE, REPAIRHISTORY_ID, QUANTITY, YEAR, WEEK, YEARWEEK, CUSTOMERNUMBER, CUSTOMERNAME, 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, LOGDATE, INVOICENUMBER)
as select
  1 linetype, a.repairhistory_id, a.quantity quantity, a.year, a.week, (a.year * 100 + a.week) yearweek,
  cl.customernumber, cl.name customername,
  e.departmentnumber, e.description departmentdesc,
  d.distributionpointnumber, d.description distributionpointdesc,
  wl.wearernumber, wl.wearername,
  wf.code functioncode,
  p.code repairtypecode, a.status,
  (select 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
, (select max(rh.repairdate) from repairhistory rh
 where rh.uniqueitem_link_id=a.uniqueitem_link_id
 and rh.repairtype_id=63
 and rh.repairdate<=a.repairdate) logdate   --wbo added
 , (select ih.invoicenumber from invoiceheader ih where a.invoiceheader_id = ih.invoiceheader_id) invoicenumber
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
      left join address ad on cs.visitaddress_id = ad.address_id
      left outer 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
  and a.repairtype_id<>63
union
select
  2 linetype, a.repairhistory_id, a.quantity quantity, a.year, a.week, (a.year * 100 + a.week) yearweek,
  cl.customernumber, cl.name customername,
  e.departmentnumber, e.description departmentdesc,
  d.distributionpointnumber, d.description distributionpointdesc,
  wl.wearernumber, wl.wearername,
  wf.code functioncode,
  p.code repairtypecode, a.status,
  (select 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
, (select max(rh.repairdate) from repairhistory rh
 where rh.uniqueitem_link_id=a.uniqueitem_link_id
 and rh.repairtype_id=63
 and rh.repairdate<=a.repairdate) logdate --wbo added
 , (select ih.invoicenumber from invoiceheader ih where a.invoiceheader_id = ih.invoiceheader_id) invoicenumber
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
      left join address ad on cs.visitaddress_id = ad.address_id
      left outer 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 is null
  and a.distributionpoint_link_id = d.distributionpoint_link_id
  and e.customer_link_id = cl.customer_link_id
  and a.repairtype_id<>63

/
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
 (LINETYPE, BUSINESSUNIT_ID, REPAIRDATE, CHAINCODE, CHAINNAME, NATIONALACCOUNTCODE, NATIONALACCOUNTNAME, CUSTOMERNUMBER, CUSTOMERNAME, WEARERNUMBER, WEARERNAME, WEARERSEARCHNAME, PRODUCT_LINKCODE, PRODUCT_DESC, REPAIRTYPECODE, NROFWASHES, MINUTES, QUANTITY, CUSTOMEROWNED, STATUS, LANGUAGECODE, LANGUAGE_ID, REPORTPARAM_ID)
as select 1 linetype
, rh.businessunit_id, rh.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
, t.code RepairTypeCode
, 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)
     , product pl, 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
, repairtype t, languages lan
, reportparam rp
where rh.repairtype_id = t.repairtype_id
      and rh.product_link_id = pl.product_id and rh.customer_link_id = cu.customer_id
      and pl.typeofmerchandise in (1, 2)
      and lan.code = rp.string_value and rh.businessunit_id = rp.number_value
      and rh.repairdate >= rp.date_value1 and 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 (t.code >= rp.string_value7 and t.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, 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, 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, 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 =  to_char(wo.deliverydate, 'D')) 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,
       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_REPORTORDER_CBD
 (WEBORDERNUMBER, DELIVERYDATE, WEBORDER_ID, DAYDESC, CUSTOMERREFERENCE, QUANTITYORDERED, WEBUSERDEPARTMENT_ID, WEBUSER_ID, WEBSESSION_ID, PRODUCTCODE, PRODUCTDESC, SIZECODE, FM_CODE, DISTRIBUTIONPOINTNUMBER, DISTR_DESC, DEPARTMENTNUMBER, DEP_DESC, DEPARTMENT_ID, LANGUAGECODE)
as select wo.webordernumber, wo.deliverydate, wo.weborder_id,
       (case when (select x.value from nls_session_parameters x where x.parameter = 'NLS_TERRITORY') = 'AMERICA'
          then (select dd.description from day_desc dd where dd.language_id = lan.language_id and dd.day_id =  to_char(wo.deliverydate-1, 'D'))
         else (select dd.description from day_desc dd where dd.language_id = lan.language_id and dd.day_id =  to_char(wo.deliverydate, 'D'))
        end )
          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,
       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_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_RESIDENTIALSCANSTATISTIC_CBD
 (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, CLIENTNUMBER, CL_NAME, CODE, DESCRIPTION)
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, cl.clientnumber, cl.name CL_NAME, p.code, pd.description
from ResidentialItemScan RIS
     left outer join Customer CU on RIS.Customer_Link_Id = Cu.Customer_Id
     left outer join client cl on Ris.Client_Id = Cl.Client_Id
     left outer join product p on Ris.Product_Link_Id = P.Product_Id
     left outer join product_desc pd on Ris.Product_Link_Id = Pd.Product_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 Pd.Language_Id = Lan.Language_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
, GETDATEONLY(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
, GETDATEONLY(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_RESIDUALVALUECHARGES_NAF
 (CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMER_ID, CITY, REASONCODE, REASONDESC, PRODECTLKCODE, PRODECTLKDESC, OUTOFCIRCDATE, STATUS, AMOUNT, PRIMARYID, FORBUSINESSUNIT_ID, LANGUAGECODE, PROCESSBUSINESSUNIT_ID)
as select
 rvc.customernumber
, rvc.customername
, rvc.customer_id
, rvc.city
, rvc.reasonCode
,rvc.reasonDesc
, rvc.prodectLKcode
--, rvc.product_link_id
, rvc.prodectLKdesc
, rvc.outofcircdate
, rvc.status
, sum(rvc.amount) amount
, rvc.primaryid
, rvc.forbusinessunit_id
, rvc.languagecode
, rvc.processbusinessunit_id
from (
select distinct(cu.customer_id)
, cu.customernumber
, cu.name customerName
, address.city
, rc.code reasonCode
, ( select rc_d.description from reasoncode_desc rc_d
   where rc_d.reasoncode_id = rc.reasoncode_id   and languages.language_id = rc_d.language_id ) reasonDesc
, rc.reasoncode_id
, prd_lk.code prodectLKcode
, ( select description from product_link_desc prd_lk_d where prd_lk_d.product_link_id = prd_lk.product_link_id   and prd_lk_d.language_id = languages.language_id ) prodectLKdesc
, GETDATEONLY(och.outofcircdate) outofcircdate
, och.status
, och.primaryid
, och.amount -- sum(och.amount) amount
, och.forbusinessunit_id
, languages.code languageCode
, languages.language_id languageID
, och.processbusinessunit_id
from
  OutOfCirculationHistory och, customer cu, reasoncode rc, product_link prd_lk
, address, languages
where
    och.chargetype = 1  -- ! --
and och.customer_link_id = cu.customer_id
and och.reasoncode_id = rc.reasoncode_id
    and 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
and och.product_link_id = prd_lk.product_link_id
and cu.visitaddress_id = address.address_id
) rvc
group by
 rvc.customernumber
, rvc.customername
, rvc.customer_id
, rvc.city
, rvc.reasoncode
, rvc.reasonDesc
, rvc.prodectLKcode
, rvc.prodectLKdesc
, rvc.outofcircdate
, rvc.status
, rvc.primaryid
, rvc.forbusinessunit_id
, rvc.languagecode
, rvc.processbusinessunit_id

/
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)
as select
  cu.customernumber, cu.name customerName, address.street, address.zipcode, address.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 product_desc.description from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.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
, currency.invoiceamountdecimals, languages.code languageCode
from
  customer cu, wearer we, weareremployment wey, wearerinventory weinv
, uniqueitemnonpool uqnp, uniqueitem uq, uniqueitemfixedinfo uqfx
, product prd, sizedefinition sz, 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.wearerinventory_id = uqnp.wearerinventory_id
            and weinv.weareremployment_id = uqnp.weareremployment_id
                and uqnp.uniqueitem_id = uq.uniqueitem_id
                    and uq.customerowned = 'N'
                    and uq.uniqueitem_id = uqfx.uniqueitem_id
        and uq.product_id = prd.product_id
        and uq.sizedefinition_id = sz.sizedefinition_id
and cu.visitaddress_id = address.address_id
and cu.currency_id = currency.currency_id

/
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)
as select cu.customer_id,
       cu.customernumber,
       cu.name customerName,
       address.street,
       address.zipcode,
       address.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 = languages.language_id) sizedesc,
       (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,
       uqfx.daysincircprevissue,
       uq.lastscandate,
       uq.washestotal,
       currency.invoiceamountdecimals,
       languages.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
  from customer            cu,
       department          dp,
       distributionpoint   cp,
       uniqueitemfixedinfo uqfx,
       uniqueitem          uq
  left outer join finishingmethod fm on fm.finishingmethod_id = uq.finishingmethod_id,
 product prd, sizedefinition sz,
 address, currency, languages,
 reportparam rp, residualvaluescheme rsc
 where cu.customer_id = dp.customer_id
   and dp.department_id = cp.department_id
   and cp.distributionpoint_id = uq.distributionpoint_id
   and uq.customerowned = 'N'
   and uq.poolitem = 1
   and uq.uniqueitem_id = uqfx.uniqueitem_id
   and uq.product_id = prd.product_id
   and uq.sizedefinition_id = sz.sizedefinition_id
   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.visitaddress_id = address.address_id
   and cu.currency_id = currency.currency_id
   and cu.customernumber = rp.number_value
   and languages.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 rsc.residualvaluescheme_id =
       coalesce((select 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
   and (((rp.string_value5 = ' ') and (rp.string_value6 = 'ZZZZZZ'))  -- if all flags then no filter on items with a flag
     or ((rp.string_value5 <> ' ') or (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_RESIDVALPERWEARERPRD_CBD
 (CUSTOMERNUMBER, CUSTOMERNAME, STREET, ZIPCODE, CITY, WEARERINVENTORY_ID, WEARERNUMBER, WEARERFULLNAME, PRODUCT_ID, PRODUCTCODE, SIZECODE, DATEACTIVE, DATEINACTIVE, PRODUCTDESC, QTYTOBERETURNEDREPLACEMENT, QTYTOBERETURNEDDECREASEMAX, UNIQUEITEM_ID, PRIMARYID, LASTISSUEDATE, DAYSINCIRCPREVISSUE, LASTSCANDATE, INVOICEAMOUNTDECIMALS, LANGUAGECODE, SECONDARYID)
as select
  cu.customernumber, cu.name customerName, address.street, address.zipcode, address.city, weinv.wearerinventory_id
, we.wearernumber, we.fullname wearerfullname
, prd.product_id, 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
, 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
, currency.invoiceamountdecimals, languages.code languageCode, SUQ.SECONDARYID
from
  customer cu, wearer we, weareremployment wey, wearerinventory weinv
, uniqueitemnonpool uqnp, uniqueitem uq left outer join Secondaryuniqueitem suq on Uq.Uniqueitem_Id = Suq.Uniqueitem_Id
, uniqueitemfixedinfo uqfx
, product prd, sizedefinition sz, 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.wearerinventory_id = uqnp.wearerinventory_id
            and weinv.weareremployment_id = uqnp.weareremployment_id
                and uqnp.uniqueitem_id = uq.uniqueitem_id
                    and uq.customerowned = 'N'
                    and uq.uniqueitem_id = uqfx.uniqueitem_id
        and uq.product_id = prd.product_id
        and uq.sizedefinition_id = sz.sizedefinition_id
and cu.visitaddress_id = address.address_id
and cu.currency_id = currency.currency_id

/
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_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 >= getcurrentdate()-28 and ih1.invoicedate <= getcurrentdate()
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 >= getcurrentdate()-91 and ih1.invoicedate <= getcurrentdate()
group by ih1.deltocustomer_link_id

/
create or replace view V_REVENUEPERCUSTOMER
 (INVOICEDATE, CURRENCYCODE, DELTOCITY, BILLTOCITY, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, DC_TOTALAMOUNT, DC_TOTALINVOICEAMOUNTEXCLVAT, BC_TOTALAMOUNT, BC_TOTALINVOICEAMOUNTEXCLVAT, INV_YEAR, INV_WEEK, INV_MONTH, PAYTHISAMOUNT, TOTALAMOUNTEXCLVAT, REPORTPARAM_ID, DELIVERYZIPCODE, PARENTINVOICEHEADER_ID, INVOICEHEADER_ID, MSCODE)
as select ih.invoicedate,
cr.code currencycode, ih.deltocity, ih.city billtocity,
  dcu.customernumber deltocustomernumber, dcu.name deltocustomername,
  bcu.customernumber billtocustomernumber, bcu.name billtocustomername,
  (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.deltocity = ih.deltocity
       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.deltocity = ih.deltocity
       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.deltocity = ih.deltocity
       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.deltocity = ih.deltocity
       and ih1.invoicebusinessunit_id = ih.invoicebusinessunit_id) bc_totalinvoiceamountexclvat,
  ih.invoiceyear inv_year, ih.invoiceweek inv_week,
	MONTH(ih.invoicedate) inv_month,
  ih.paythisamount, ih.totalamountexclvat,
  rp.reportparam_id
  , (select a.zipcode from address a where dcu.visitaddress_id=a.address_id) DeliveryZipCode --todo 4675
  , ih.parentinvoiceheader_id, ih.invoiceheader_id --todo 22165
  , ms.code mscode
from invoiceheader ih, customer dcu, customer bcu, currency cr, status st,
  marketsegment ms, salesarea sa, reportparam rp
where ih.deltocustomer_link_id = dcu.customer_id
  and ih.billtocustomer_link_id = bcu.customer_id
  and dcu.currency_id = cr.currency_id
  and dcu.marketsegment_id = ms.marketsegment_id
  and dcu.salesarea_id = sa.salesarea_id
  and ih.status_id = st.status_id
  and st.code = '2'
  AND ih.documenttype = 1 --invoice
  and ih.invoicedate between rp.date_value1 and rp.date_value2
  and ih.invoicebusinessunit_id = rp.number_value1
  and sa.code between rp.string_value1 and rp.string_value2
  --and ms.code between rp.string_value3 and rp.string_value4 --commented with todo 22140
  and ih.billtocustomernumber between rp.number_value2 and rp.number_value4

/
create or replace view V_REVENUEPERCUSTOMER_AMM
 (LINENUMBER, INVOICEDATE, CURRENCYCODE, DELTOCITY, BILLTOCITY, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, DC_TOTALAMOUNT, DC_TOTALINVOICEAMOUNTEXCLVAT, BC_TOTALAMOUNT, BC_TOTALINVOICEAMOUNTEXCLVAT, INV_YEAR, INV_WEEK, INV_MONTH, PAYTHISAMOUNT, TOTALAMOUNTEXCLVAT, REPORTPARAM_ID, DELIVERYZIPCODE)
as select 1 LineNumber,
ih.invoicedate,
cr.code currencycode, ih.deltocity, ih.city billtocity,
  dcu.customernumber deltocustomernumber, dcu.name deltocustomername,
  bcu.customernumber billtocustomernumber, bcu.name billtocustomername,
  (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.deltocity = ih.deltocity
       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.deltocity = ih.deltocity
       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.deltocity = ih.deltocity
       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.deltocity = ih.deltocity
       and ih1.invoicebusinessunit_id = ih.invoicebusinessunit_id) bc_totalinvoiceamountexclvat,
  YEAR(ih.invoicedate) inv_year, ih.invoiceweek inv_week, --GETISOWEEK(ih.invoicedate) inv_week,
	MONTH(ih.invoicedate) inv_month,
  ih.paythisamount, ih.totalamountexclvat,
  rp.reportparam_id
  , (select a.zipcode from address a where dcu.visitaddress_id=a.address_id) DeliveryZipCode --todo 4675
from invoiceheader ih, customer dcu, customer bcu, currency cr, status st,
  marketsegment ms, salesarea sa, reportparam rp
where ih.deltocustomer_link_id = dcu.customer_id
  and ih.billtocustomer_link_id = bcu.customer_id
  and dcu.currency_id = cr.currency_id
  and dcu.marketsegment_id = ms.marketsegment_id
  and dcu.salesarea_id = sa.salesarea_id
  and ih.status_id = st.status_id
  and st.code = '2'
  AND ih.documenttype = 1 --invoice
  and ih.invoicedate between rp.date_value1 and rp.date_value2
  and ih.invoicebusinessunit_id = rp.number_value1
  and sa.code between rp.string_value1 and rp.string_value2
  and ms.code between rp.string_value3 and rp.string_value4
  and bcu.customernumber between rp.number_value2 and rp.number_value4
--group by cr.code, dcu.customernumber, dcu.name, ih.deltocity, rp.reportparam_id
and (ih.parentinvoiceheader_id is null or ih.parentinvoiceheader_id = ih.invoiceheader_id)
--single invoices and consolidated parents for the billto level
UNION ALL
select 2 LineNumber,
ih.invoicedate,
cr.code currencycode, ih.deltocity, ih.city billtocity,
  dcu.customernumber deltocustomernumber, dcu.name deltocustomername,
  bcu.customernumber billtocustomernumber, bcu.name billtocustomername,
  (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.deltocity = ih.deltocity
       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.deltocity = ih.deltocity
       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.deltocity = ih.deltocity
       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.deltocity = ih.deltocity
       and ih1.invoicebusinessunit_id = ih.invoicebusinessunit_id) bc_totalinvoiceamountexclvat,
  YEAR(ih.invoicedate) inv_year, ih.invoiceweek inv_week, --GETISOWEEK(ih.invoicedate) inv_week,
	MONTH(ih.invoicedate) inv_month,
    ih.paythisamount,
  ih.totalamountexclvat,
  rp.reportparam_id,
  (select a.zipcode from address a where dcu.visitaddress_id=a.address_id) DeliveryZipCode --todo 4675
from invoiceheader ih, customer dcu, customer bcu, currency cr, status st,
  marketsegment ms, salesarea sa, reportparam rp
where ih.deltocustomer_link_id = dcu.customer_id
  and ih.billtocustomer_link_id = bcu.customer_id
  and dcu.currency_id = cr.currency_id
  and dcu.marketsegment_id = ms.marketsegment_id
  and dcu.salesarea_id = sa.salesarea_id
  and ih.status_id = st.status_id
  and st.code = '2'
  AND ih.documenttype = 1 --invoice
  and ih.invoicedate between rp.date_value1 and rp.date_value2
  and ih.invoicebusinessunit_id = rp.number_value1
  and sa.code between rp.string_value1 and rp.string_value2
  and ms.code between rp.string_value3 and rp.string_value4
  and bcu.customernumber between rp.number_value2 and rp.number_value4
--group by cr.code, dcu.customernumber, dcu.name, ih.deltocity, rp.reportparam_id
and (ih.parentinvoiceheader_id is null or ih.parentinvoiceheader_id <> ih.invoiceheader_id)

/
create or replace view V_REVENUEPERCUSTOMER_DFD
 (MARKETSEGMENTCODE, PRODUCTGROUPCODE, INVOICEMONTH, INVOICEYEAR, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, INVOICEDATE, ROUTENUMBER, ILCODE, DESCRIPTION, BILLEDQTY, PRICE, AMOUNT, SALESJOURNALCODE, TURNOVERGROUPCODE, ILTYPEDESC, INVOICEHEADER_ID, PARENTINVOICEHEADER_ID, INVOICELINETYPE_ID)
as select (select ms.code from marketsegment ms where c.marketsegment_id = ms.marketsegment_id ) marketsegmentcode,
       prodlink.productgroupcode,
       month(ih.invoicedate) invoicemonth, ih.invoiceyear, ih.billtocustomernumber, ih.billtocustomername, ih.invoicedate, --ih.invoiceweek,
       ih.routenumber, il.code ilcode, il.description, sum(il.billedqty) billedqty, il.price, sum(il.amount) amount,
       sjg.code salesjournalcode, tg.code turnovergroupcode,
       (select ildesc.description from invoicelinetype_desc ildesc where il.invoicelinetype_id = ildesc.invoicelinetype_id and ildesc.language_id = c.language_id) iltypedesc,
       ih.invoiceheader_id, ih.parentinvoiceheader_id, il.invoicelinetype_id
from invoiceheader ih
     , invoiceline il
                   left outer join (turnovergroup tg
                                                  join salesjournalgroup sjg
                                                  on tg.salesjournalgroup_id = sjg.salesjournalgroup_id)
                   on il.turnovergroup_id = tg.turnovergroup_id
                   left outer join (invoicelineproduct ilp join product_link prodlink on ilp.product_link_id = prodlink.product_link_id)
                   on ilp.invoiceline_id = il.invoiceline_id
     , customer c
where ih.invoiceheader_id = il.invoiceheader_id
      and ih.billtocustomer_link_id = c.customer_id
      and il.invoicelinetype_id <> 18
group by tg.code, sjg.code, c.marketsegment_id, ih.routenumber, ih.billtocustomernumber, ih.billtocustomername, c.language_id,
         ih.parentinvoiceheader_id, ih.invoiceheader_id, ih.invoicedate, ih.invoiceyear, prodlink.productgroupcode, il.code, il.description, il.price, il.invoicelinetype_id

/
create or replace view V_REVENUEPERCUSTOMER_LLG
 (INVOICEDATE, CURRENCYCODE, DELTOCITY, BILLTOCITY, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, DC_TOTALAMOUNT, DC_TOTALINVOICEAMOUNTEXCLVAT, BC_TOTALAMOUNT, BC_TOTALINVOICEAMOUNTEXCLVAT, INV_YEAR, INV_WEEK, INV_MONTH, PAYTHISAMOUNT, TOTALAMOUNTEXCLVAT, REPORTPARAM_ID, DELIVERYZIPCODE, PARENTINVOICEHEADER_ID, INVOICEHEADER_ID, MSCODE)
as select ih.invoicedate,
cr.code currencycode, ih.deltocity, ih.city billtocity,
  dcu.customernumber deltocustomernumber, dcu.name deltocustomername,
  bcu.customernumber billtocustomernumber, bcu.name billtocustomername,
  (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.deltocity = ih.deltocity
       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.deltocity = ih.deltocity
       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.deltocity = ih.deltocity
       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.deltocity = ih.deltocity
       and ih1.invoicebusinessunit_id = ih.invoicebusinessunit_id) bc_totalinvoiceamountexclvat,
  ih.invoiceyear inv_year, ih.invoiceweek inv_week,
	MONTH(ih.invoicedate) inv_month,
  ih.paythisamount, ih.totalamountexclvat,
  rp.reportparam_id
  , (select a.zipcode from address a where dcu.visitaddress_id=a.address_id) DeliveryZipCode --todo 4675
  , ih.parentinvoiceheader_id, ih.invoiceheader_id --todo 22165
  , ms.code mscode
from invoiceheader ih, customer dcu, customer bcu, currency cr, status st,
  marketsegment ms, salesarea sa, reportparam rp
where ih.deltocustomer_link_id = dcu.customer_id
  and ih.billtocustomer_link_id = bcu.customer_id
  and dcu.currency_id = cr.currency_id
  and dcu.marketsegment_id = ms.marketsegment_id
  and dcu.salesarea_id = sa.salesarea_id
  and ih.status_id = st.status_id
  and st.code = '2'
  AND ih.documenttype = 1 --invoice
  and ih.invoicedate between rp.date_value1 and rp.date_value2
  and ih.invoicebusinessunit_id = rp.number_value1
  and sa.code between rp.string_value1 and rp.string_value2
  --and ms.code between rp.string_value3 and rp.string_value4 --commented with todo 22140
  and ih.billtocustomernumber between rp.number_value2 and rp.number_value4

/
create or replace view V_REVENUEPERCUSTOMER_SGS
 (INVOICEDATE, CURRENCYCODE, DELTOCITY, BILLTOCITY, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, DC_TOTALAMOUNT, DC_TOTALINVOICEAMOUNTEXCLVAT, BC_TOTALAMOUNT, BC_TOTALINVOICEAMOUNTEXCLVAT, INV_YEAR, INV_WEEK, INV_MONTH, PAYTHISAMOUNT, TOTALAMOUNTEXCLVAT, REPORTPARAM_ID, DELIVERYZIPCODE, PARENTINVOICEHEADER_ID, INVOICEHEADER_ID, MSCODE, CODE, DESCRIPTION, BILLEDQTY, PRICE, AMOUNT)
as select ih.invoicedate,
cr.code currencycode, ih.deltocity, ih.city billtocity,
  dcu.customernumber deltocustomernumber, dcu.name deltocustomername,
  bcu.customernumber billtocustomernumber, bcu.name billtocustomername,
  (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.deltocity = ih.deltocity
       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.deltocity = ih.deltocity
       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.deltocity = ih.deltocity
       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.deltocity = ih.deltocity
       and ih1.invoicebusinessunit_id = ih.invoicebusinessunit_id) bc_totalinvoiceamountexclvat,
  YEAR(ih.invoicedate) inv_year, ih.invoiceweek inv_week, --GETISOWEEK(ih.invoicedate) inv_week,
  MONTH(ih.invoicedate) inv_month,
  ih.paythisamount, ih.totalamountexclvat,
  rp.reportparam_id
  , (select a.zipcode from address a where dcu.visitaddress_id=a.address_id) DeliveryZipCode --todo 4675
  , ih.parentinvoiceheader_id, ih.invoiceheader_id --todo 22165
  , ms.code mscode
, il.code, il.description, il.billedqty, il.price, il.amount
from invoiceheader ih
                   left outer join invoiceline il on il.invoiceheader_id = ih.invoiceheader_id and il.invoicelinetype_id = 2--only WASH
, customer dcu, customer bcu, currency cr, status st,
  marketsegment ms, salesarea sa, reportparam rp
where ih.deltocustomer_link_id = dcu.customer_id
  and ih.billtocustomer_link_id = bcu.customer_id
  and dcu.currency_id = cr.currency_id
  and dcu.marketsegment_id = ms.marketsegment_id
  and dcu.salesarea_id = sa.salesarea_id
  and ih.status_id = st.status_id
  and st.code = '2'
  AND ih.documenttype = 1 --invoice
  and ih.invoicedate between rp.date_value1 and rp.date_value2
  and ih.invoicebusinessunit_id = rp.number_value1
  and sa.code between rp.string_value1 and rp.string_value2
  --and ms.code between rp.string_value3 and rp.string_value4 --commented with todo 22140
  and ih.billtocustomernumber between rp.number_value2 and rp.number_value4

/
create or replace view V_REVENUEPERCUSTOMER_SMG
 (INVOICEDATE, CURRENCYCODE, DELTOCITY, BILLTOCITY, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, DC_TOTALAMOUNT, DC_TOTALINVOICEAMOUNTEXCLVAT, BC_TOTALAMOUNT, BC_TOTALINVOICEAMOUNTEXCLVAT, INV_YEAR, INV_WEEK, INV_MONTH, PAYTHISAMOUNT, TOTALAMOUNTEXCLVAT, REPORTPARAM_ID, DELIVERYZIPCODE, PARENTINVOICEHEADER_ID, INVOICEHEADER_ID, MSCODE)
as select ih.invoicedate,
  coalesce(pcu.code, cr.code) currencycode, ih.deltocity, ih.city billtocity,
  dcu.customernumber deltocustomernumber, dcu.name deltocustomername,
  bcu.customernumber billtocustomernumber, bcu.name billtocustomername,
  (select sum(coalesce(ihc1.paythisamount, ih1.paythisamount)) from invoiceheader ih1
     left outer join invoiceheadercurrency ihc1 on ihc1.invoiceheader_id = ih1.invoiceheader_id and ihc1.invoicecurrencytype = 2 --Plant Currency
     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.deltocity = ih.deltocity
       and ih1.invoicebusinessunit_id = ih.invoicebusinessunit_id) dc_totalamount,
  (select sum(coalesce(ihc1.totalamountexclvat, ih1.totalamountexclvat)) from invoiceheader ih1
     left outer join invoiceheadercurrency ihc1 on ihc1.invoiceheader_id = ih1.invoiceheader_id and ihc1.invoicecurrencytype = 2 --Plant Currency
     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.deltocity = ih.deltocity
       and ih1.invoicebusinessunit_id = ih.invoicebusinessunit_id) dc_totalinvoiceamountexclvat,
  (select sum(coalesce(ihc1.paythisamount, ih1.paythisamount)) from invoiceheader ih1
     left outer join invoiceheadercurrency ihc1 on ihc1.invoiceheader_id = ih1.invoiceheader_id and ihc1.invoicecurrencytype = 2 --Plant Currency
     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.deltocity = ih.deltocity
       and ih1.invoicebusinessunit_id = ih.invoicebusinessunit_id) bc_totalamount,
  (select sum(coalesce(ihc1.totalamountexclvat, ih1.totalamountexclvat)) from invoiceheader ih1
     left outer join invoiceheadercurrency ihc1 on ihc1.invoiceheader_id = ih1.invoiceheader_id and ihc1.invoicecurrencytype = 2 --Plant Currency
     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.deltocity = ih.deltocity
       and ih1.invoicebusinessunit_id = ih.invoicebusinessunit_id) bc_totalinvoiceamountexclvat,
  ih.invoiceyear inv_year, ih.invoiceweek inv_week,
	MONTH(ih.invoicedate) inv_month,
  coalesce(ihc.paythisamount, ih.paythisamount) paythisamount, coalesce(ihc.totalamountexclvat, ih.totalamountexclvat) totalamountexclvat,
  rp.reportparam_id
  , (select a.zipcode from address a where dcu.visitaddress_id=a.address_id) DeliveryZipCode --todo 4675
  , ih.parentinvoiceheader_id, ih.invoiceheader_id --todo 22165
  , ms.code mscode
from invoiceheader ih
  left outer join invoiceheadercurrency ihc
       inner join currency pcu on pcu.currency_id = ihc.currency_id
  on ihc.invoiceheader_id = ih.invoiceheader_id and ihc.invoicecurrencytype = 2 --Plant Currency
, customer dcu, customer bcu, currency cr, status st, marketsegment ms, salesarea sa, reportparam rp
where ih.deltocustomer_link_id = dcu.customer_id
  and ih.billtocustomer_link_id = bcu.customer_id
  and dcu.currency_id = cr.currency_id
  and dcu.marketsegment_id = ms.marketsegment_id
  and dcu.salesarea_id = sa.salesarea_id
  and ih.status_id = st.status_id
  and st.code = '2'
  AND ih.documenttype = 1 --invoice
  and ih.invoicedate between rp.date_value1 and rp.date_value2
  and ih.invoicebusinessunit_id = rp.number_value1
  and sa.code between rp.string_value1 and rp.string_value2
  --and ms.code between rp.string_value3 and rp.string_value4 --commented with todo 22140
  and ih.billtocustomernumber between rp.number_value2 and rp.number_value4

/
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_ROUTECONTAINERS
 (COUNTCONTAINER, STOP_ID, ROUTE_ID)
as select
  count(distinct pnc.container_id) countContainer
, pn.stop_id, pn.route_id
from
  packingnote pn, packingnotecontainer pnc
where
    pn.packingnote_id = pnc.packingnote_id
and pnc.container_id is not null
group by
 pn.stop_id, pn.route_id

/
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 c.routenumber, c.description routedescription, a.routelistprinted, a.soilticketsprinted, a.soilcountstatus,
a.settlementstatus, a.packingstatus, a.originaldrivingdate, a.drivingdate, d.daynumber packingdaynumber, a.overageamount,
a.voucheramount, a.totalcashcollected, a.totalcoddelayed, a.totalcodpaythisamnt, a.totalcodundelivered,a.totalcodplusadj,
a.totalcodminusadj, a.totalcodprebilled, a.totalchargeplusadj, a.totalchargecollections, a.totalchargepaythisamnt,
a.totalchargeundelivered, a.totalchargeminusadj, a.totalchargeprebilled, a.returntime, a.returndate, a.starttime,
a.loadingdock, a.packingdeadline, a.truckcode, a.drivernumber, b.code plantcode, b.name plantname, a.routecontrol_id,
s.street plantstreet, s.zipcode plantzipcode, s.city plantcity, s.street2 plantstreet2, e.code depotcode,
l.code Language_Code,
(select ddd.description from day_desc ddd where ddd.day_id = GETABSDAYNUMBER(a.drivingdate) and ddd.language_id = l.language_id) Day_Description,
--(select dd.description from day_desc dd where d.day_id=dd.day_id  and dd.language_id = l.language_id) Day_Description,
(select emp.name from employee emp where emp.plant_id = a.plant_id and emp.employeenumber = a.drivernumber) Employee_Name
from routecontrol a LEFT OUTER JOIN day d ON (a.packingday_id = d.day_id),
     plant b, route c left outer join depot e on c.depot_id = e.depot_id, address s, languages l
where a.plant_id = b.plant_id
and a.route_id = c.route_id
and b.address_id = s.address_id
/*and c.depot_id is null
union all
select c.routenumber, c.description routedescription, a.routelistprinted, a.soilticketsprinted, a.soilcountstatus,
a.settlementstatus, a.packingstatus, a.originaldrivingdate, a.drivingdate, d.daynumber packingdaynumber, a.overageamount,
a.voucheramount, a.totalcashcollected, a.totalcoddelayed, a.totalcodpaythisamnt, a.totalcodundelivered,a.totalcodplusadj,
a.totalcodminusadj, a.totalcodprebilled, a.totalchargeplusadj, a.totalchargecollections, a.totalchargepaythisamnt,
a.totalchargeundelivered, a.totalchargeminusadj, a.totalchargeprebilled, a.returntime, a.returndate, a.starttime,
a.loadingdock, a.packingdeadline, a.truckcode, a.drivernumber, b.code plantcode, b.name plantname, a.routecontrol_id,
s.street plantstreet, s.zipcode plantzipcode, s.city plantcity, s.street2 plantstreet2, e.code depotcode,
l.code Language_Code,
(select ddd.description from day_desc ddd where ddd.day_id = GETABSDAYNUMBER(a.drivingdate) and ddd.language_id = l.language_id) Day_Description,
--(select dd.description from day_desc dd where d.day_id=dd.day_id  and dd.language_id = l.language_id) Day_Description,
(select emp.name from employee emp where emp.plant_id = a.plant_id and emp.employeenumber = a.drivernumber) Employee_Name
from routecontrol a
LEFT OUTER JOIN day d ON (a.packingday_id = d.day_id),
plant b, route c, address s,
languages l, depot e
where a.plant_id = b.plant_id
and a.route_id = c.route_id
and b.address_id = s.address_id
and c.depot_id = e.depot_id
and c.plant_id = e.plant_id*/

/
create or replace view V_ROUTECONTROL_AUJ
 (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, DAY_NR)
as Select c.routenumber, c.description routedescription, a.routelistprinted, a.soilticketsprinted, a.soilcountstatus,
a.settlementstatus, a.packingstatus, a.originaldrivingdate, a.drivingdate, d.daynumber packingdaynumber, a.overageamount,
a.voucheramount, a.totalcashcollected, a.totalcoddelayed, a.totalcodpaythisamnt, a.totalcodundelivered,a.totalcodplusadj,
a.totalcodminusadj, a.totalcodprebilled, a.totalchargeplusadj, a.totalchargecollections, a.totalchargepaythisamnt,
a.totalchargeundelivered, a.totalchargeminusadj, a.totalchargeprebilled, a.returntime, a.returndate, a.starttime,
a.loadingdock, a.packingdeadline, a.truckcode, a.drivernumber, b.code plantcode, b.name plantname, a.routecontrol_id,
s.street plantstreet, s.zipcode plantzipcode, s.city plantcity, s.street2 plantstreet2, e.code depotcode,
l.code Language_Code,
(select ddd.description from day_desc ddd where ddd.day_id = GETABSDAYNUMBER(a.drivingdate) and ddd.language_id = l.language_id) Day_Description,
(select emp.name from employee emp where emp.plant_id = a.plant_id and emp.employeenumber = a.drivernumber) Employee_Name,
(select da.daynumber from day da where da.day_id = GETABSDAYNUMBER(a.drivingdate) ) Day_Nr
from routecontrol a
           LEFT OUTER JOIN day d ON (a.packingday_id = d.day_id),
     plant b, route c
		       left outer join depot e on c.depot_id = e.depot_id,
		 address s, languages l
where a.plant_id = b.plant_id
and a.route_id = c.route_id
and b.address_id = s.address_id

/
create or replace view V_ROUTECOUNTBAGSTOTAL_LLG
 (LINETYPE, NOOFPACKINGNOTES, ROUTECONTROL_ID)
as select 1 linetype, count(pn.notenumber) noofpackingnotes, pn.routecontrol_id
from
  packingnote pn
where pn.status_id = (select s.status_id from status s where s.statustype = 'PN' and s.code = 30)
and exists (select 1 from packingnoteline pnl where pnl.packingnote_id = pn.packingnote_id and pnl.deliveredamount <> 0)
group by pn.routecontrol_id
union
select 2 linetype, count(pn.notenumber) noofpackingnotes, pn.routecontrol_id
from
  packingnote pn
where pn.status_id not in (select s.status_id from status s where s.statustype = 'PN' and s.code in (40,60))
and exists (select 1 from packingnoteline pnl where pnl.packingnote_id = pn.packingnote_id and pnl.deliveredamount <> 0)
group by pn.routecontrol_id

/
create or replace view V_ROUTECOUNTBAGS_LLG
 (LINETYPE, NOOFPACKINGNOTES, STOP_ID, ROUTE_ID)
as select 1 linetype, count(pn.notenumber) noofpackingnotes, pn.stop_id, pn.route_id
from
  packingnote pn
where pn.status_id = (select s.status_id from status s where s.statustype = 'PN' and s.code = 30)
and exists (select 1 from packingnoteline pnl where pnl.packingnote_id = pn.packingnote_id and pnl.deliveredamount <> 0)
group by pn.stop_id, pn.route_id
union
select 2 linetype, count(pn.notenumber) noofpackingnotes, pn.stop_id, pn.route_id
from
  packingnote pn
where pn.status_id not in (select s.status_id from status s where s.statustype = 'PN' and s.code in (40,60))
and exists (select 1 from packingnoteline pnl where pnl.packingnote_id = pn.packingnote_id and pnl.deliveredamount <> 0)
group by pn.stop_id, pn.route_id

/
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
    GETCURRENTDATETIME() 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 <= GetCurrentDate()
and rst.dateinactive > GetCurrentDate()

/
create or replace view V_ROUTEFOLLOWUP
 (REASONCODE_ID, PROOFOFVISITHISTORY_ID, CONTACT_ID, ROUTECONTROL_ID, ROUTENUMBER, STOPNUMBER, DRIVINGDATE, ROUTEDESCRIPTION, CUSTOMERNUMBER, NAME, STOP_ID, DEPARTURETIME, REASONCODE, REASONDESC, CONTACTPERSONNUMBER, CONTACTPERSONNAME, CONTACTPERSONPHONE, DEPARTMENTNUMBER, DEPARTMENTDESC, DISTRIBUTIONPOINTNUMBER, DISTRIBDESC, VISITDATE, VISITTIME, CONTACTCATEGORYCODE, PRIORITY, STATUS, CONTACTNOTES, REPORTPARAM_ID, LANGUAGECODE)
as select 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,
       (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 re.code from reasoncode re where st.reasoncode_id = re.reasoncode_id) ReasonCode,
       (select red.description from reasoncode_desc red where st.reasoncode_id = red.reasoncode_id and red.language_id = lan.language_id) ReasonDesc,
       cp.contactpersonnumber, cp.name ContactPersonName, cp.phone ContactPersonPhone,
       dep.departmentnumber, dep.description DepartmentDesc,
       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(pvh.visitdatetime, 'HH:MI AM')
         else to_char(pvh.visitdatetime, 'HH24:MI')
       end  from dual)  visittime,
       (select cc.code from contactcategory cc where ct.contactcategory_id = cc.contactcategory_id) ContactCategoryCode,
       ct.priority, ct.status, ct.contactnotes,
       rp.reportparam_id,
       lan.code LanguageCode
from routecontrol rc, route r, stop st
     left outer join proofofvisithistory pvh
          left outer join distributionpoint dp
               left outer join department dep on dp.department_id=dep.department_id
          on pvh.distributionpoint_link_id = dp.distributionpoint_id
     on pvh.stop_id = st.stop_id and pvh.scanned = 'N'
     left outer join contact ct on ct.stop_id = st.stop_id
     left outer join customer cu on cu.customer_id = st.customer_link_id
     left outer join routestop rs
          left outer join contactperson cp on rs.contactperson_id = cp.contactperson_id
     on rs.routestop_id = st.routestop_id
     , reportparam rp, languages lan
where st.status in (0, 3, 4) and st.departuretime is not null and rc.pocketpcstatus = 2
      and st.routecontrol_id = rc.routecontrol_id and rc.route_id = r.route_id
      and rp.number_value = rc.routecontrol_id

/
create or replace view V_ROUTELISTBNL
 (DAYDESC, DRIVINGDATE, ROUTENUMBER, STOPNUMBER, CONTAINERNO, ROUTELISTINSTRUCTIONS, CUSTOMERNUMBER, CUSTOMERNAME, LOCKERMANAGEMENT, DEPARTMENTNUMBER, DEPARTMENTDESC, LEGACYDEPARTMENTCODE, PLANTDEPCODE, CONTACTPERSONNAME, CONTACTPERSONNUMBER, CONTACTPERSONPHONE, STREET, CITY, NEWLEV, REPORTPARAM_ID)
as select GETDAYDESCRIPTION(rc.drivingdate) daydesc, rc.drivingdate, ru.routenumber, st.stopnumber, rs.containerno,
 -- case when st.routestop_id is null then st.routelistinstructions else rs.ROUTELISTINSTRUCTIONS end routelistinstructions,
 st.routelistinstructions,
  cu.customernumber, cu.name customername, coalesce(( select clm.showlockeronroutelist
  from customerlockermanagement clm
  where clm.customer_id = cu.customer_id ) , 'N') lockermanagement,
  d.departmentnumber, d.description departmentdesc, d.legacydepartmentcode,
  case when d.plantdepartment_id is null then pd2.code else pd.code
   end plantdepcode,
  case when st.contactperson_id is null then cp2.name  else cp.name
    end contactpersonname,
  case when st.contactperson_id is null then cp2.contactpersonnumber else cp.contactpersonnumber
    end contactpersonnumber,
  case when st.contactperson_id is null then cp2.phone else cp.phone
    end contactpersonphone,
  case when ad2.street is null then ad.street else ad2.street
     end street,
  case when ad2.street is null then ad.city else ad2.city
    end city,
  case when not exists (select ds.businessunit_id from deliveryscan ds
    where ds.fromstock = 'Y' and ds.packingnote_id = pn.packingnote_id) then 'N' else 'Y' end newlev,
  rp.reportparam_id
from route ru, routecontrol rc,
  stop st
  left outer join contactperson cp on st.contactperson_id = cp.contactperson_id,
  routestop rs,
  customer cu
    left outer join plantdepartment pd2 on cu.plantdepartment_id = pd2.plantdepartment_id,
  address ad,
  packingnote pn, distributionpoint dip,
  department d
    left outer join plantdepartment pd on d.plantdepartment_id = pd.plantdepartment_id
    left outer join contactperson cp2 on d.contactperson_id = cp2.contactperson_id,
  deliverypoint dp, address ad2, reportparam rp
where ru.route_id = rc.route_id
  and rc.routecontrol_id = st.routecontrol_id
  and st.routestop_id = rs.routestop_id
  and cu.customer_id = st.customer_link_id
  and st.stop_id = pn.stop_id
  and pn.distributionpoint_id = dip.distributionpoint_id
  and dip.deliverypoint_id = st.deliverypoint_id
  and dip.department_id = d.department_id
  and cu.visitaddress_id = ad.address_id
  and st.deliverypoint_id = dp.deliverypoint_id
  and dp.deliveryaddress_id = ad2.address_id
  and rp.NUMBER_VALUE = rc.ROUTECONTROL_ID
union all
-- with del note and depatment via customer
select GETDAYDESCRIPTION(rc.drivingdate) daydesc, rc.drivingdate, ru.routenumber, st.stopnumber, rs.containerno,
  ---case when st.routestop_id is null then st.routelistinstructions else rs.ROUTELISTINSTRUCTIONS end routelistinstructions,
  st.routelistinstructions,
  cu.customernumber, cu.name customername, coalesce(( select clm.showlockeronroutelist
  from customerlockermanagement clm
  where clm.customer_id = cu.customer_id ) , 'N') lockermanagement,
  d.departmentnumber, d.description departmentdesc, d.legacydepartmentcode,
  case when d.plantdepartment_id is null then pd2.code else pd.code
    end plantdepcode,
  case when st.contactperson_id is null then cp2.name else cp.name
    end contactpersonname,
  case when st.contactperson_id is null then cp2.contactpersonnumber else cp.contactpersonnumber
    end contactpersonnumber,
  case when st.contactperson_id is null then cp2.phone else cp.phone
    end contactpersonphone,
  ad.street,
  ad.city,
  case when not exists (select ds.businessunit_id from deliveryscan ds
    where ds.fromstock = 'Y' and ds.packingnote_id = pn.packingnote_id) then 'N' else 'Y' end newlev,
  rp.reportparam_id
from route ru, routecontrol rc,
  stop st
  left outer join contactperson cp on st.contactperson_id = cp.contactperson_id,
  routestop rs,
  customer cu
    left outer join plantdepartment pd2 on cu.plantdepartment_id = pd2.plantdepartment_id,
  address ad,
  packingnote pn, distributionpoint dip,
  department d
    left outer join plantdepartment pd on d.plantdepartment_id = pd.plantdepartment_id
    left outer join contactperson cp2 on d.contactperson_id = cp2.contactperson_id,
  reportparam rp
where ru.route_id = rc.route_id
  and rc.routecontrol_id = st.routecontrol_id
  and st.routestop_id = rs.routestop_id
  and cu.customer_id = st.customer_link_id
  and st.stop_id = pn.stop_id
  and pn.distributionpoint_id = dip.distributionpoint_id
  and st.deliverypoint_id is null
  and dip.department_id = d.department_id
  and d.customer_id = rs.customer_id
  and cu.visitaddress_id = ad.address_id
  and rp.NUMBER_VALUE = rc.ROUTECONTROL_ID
union all
-- without del note
select GETDAYDESCRIPTION(rc.drivingdate) daydesc, rc.drivingdate, ru.routenumber, st.stopnumber, rs.containerno,
  ---case when st.routestop_id is null then st.routelistinstructions else rs.ROUTELISTINSTRUCTIONS end routelistinstructions,
  st.routelistinstructions,
  cu.customernumber, cu.name customername, coalesce(( select clm.showlockeronroutelist
  from customerlockermanagement clm
  where clm.customer_id = cu.customer_id ) , 'N') lockermanagement,
  null departmentnumber, null departmentdesc, null legacydepartmentcode,
  pd.code plantdepcode,
  cp.name contactpersonname,
  cp.contactpersonnumber contactpersonnumber,
  cp.phone contactpersonphone,
  ad.street,
  ad.city,
  'N' newlev,
  rp.reportparam_id
from route ru, routecontrol rc,
  stop st
  left outer join contactperson cp on st.contactperson_id = cp.contactperson_id,
  routestop rs,
  customer cu
    left outer join plantdepartment pd on cu.plantdepartment_id = pd.plantdepartment_id,
  address ad, reportparam rp
where ru.route_id = rc.route_id
  and rc.routecontrol_id = st.routecontrol_id
  and st.routestop_id = rs.routestop_id
  and cu.customer_id = st.customer_link_id
  --and not exists (select p.stop_id from packingnote p where p.stop_id = st.stop_id)
  and cu.visitaddress_id = ad.address_id
  and rp.NUMBER_VALUE = rc.ROUTECONTROL_ID

/
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, PUTUP, STRAIGHTEVENEXCHANGE, STATUSCODE, STRAIGHTEVENRETURN)
as select pn.notenumber, pn.deliverypoint_id, pn.stop_id, pn.route_id, c.delnoteforbulkputupitems,
  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, PACKINGNOTELINEPERDELSCHEME H
      where PNL2.PACKINGNOTELINE_ID = H.PACKINGNOTELINE_ID
        AND PNL2.PACKINGNOTE_ID = PN.PACKINGNOTE_ID) > 0 THEN 1 ELSE 0 END STRAIGHTEVENEXCHANGE,
  st.code statuscode, pn.straightevenreturn
from
  packingnote pn,
  stop sp, customer c, routecontrol rc, route r, status st
where pn.stop_id = sp.stop_id
  and sp.customer_link_id = c.customer_id
  and sp.routecontrol_id = rc.routecontrol_id
  and rc.route_id = r.route_id
  and 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_ROUTELISTPACKINGNOTE_ECL
 (NOTENUMBER, DELIVERYPOINT_ID, STOP_ID, ROUTE_ID, DELNOTEFORBULKPUTUPITEMS, PUTUP, STRAIGHTEVENEXCHANGE, STATUSCODE, STRAIGHTEVENRETURN)
as select cn.consignmentnotenumber notenumber, cn.deliverypoint_link_id deliverypoint_id, sp.stop_id, cn.route_id, c.delnoteforbulkputupitems,
  0 PUTUP,
  1 STRAIGHTEVENEXCHANGE,
  '' statuscode, '' straightevenreturn
from
  consignmentnote cn,
  stop sp, customer c, routecontrol rc, route r
where cn.route_id = rc.route_id
  and cn.deliverydate = rc.originaldrivingdate
  and sp.routecontrol_id = rc.routecontrol_id
  and sp.customer_link_id = c.customer_id
  and rc.route_id = r.route_id
  and cn.stopnumber=sp.stopnumber
  and cn.customer_link_id=c.customer_id
  and cn.status<>1
union all
select pn.notenumber, pn.deliverypoint_id, pn.stop_id, pn.route_id, c.delnoteforbulkputupitems,
  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, PACKINGNOTELINEPERDELSCHEME H
      where PNL2.PACKINGNOTELINE_ID = H.PACKINGNOTELINE_ID
        AND PNL2.PACKINGNOTE_ID = PN.PACKINGNOTE_ID) > 0 THEN 1 ELSE 0 END STRAIGHTEVENEXCHANGE, '' statuscode,
 pn.straightevenreturn
from
  packingnote pn,
  stop sp, customer c, routecontrol rc, route r
where pn.stop_id = sp.stop_id
  and sp.customer_link_id = c.customer_id
  and sp.routecontrol_id = rc.routecontrol_id
  and rc.route_id = r.route_id
  and pn.status_id<>(select s.status_id from status s where s.statustype='PN' and s.factorydescription='Cancelled')
  and not exists (select 1 from consignmentnote cn where cn.route_id = rc.route_id and cn.deliverydate = rc.originaldrivingdate
  and sp.routecontrol_id = rc.routecontrol_id
  and sp.customer_link_id = c.customer_id
  and c.customer_id=cn.customer_link_id
  and rc.route_id = r.route_id
  and cn.stopnumber=sp.stopnumber and cn.status<>1)

/
create or replace view V_ROUTELISTRECEIPTS
 (INVOICENUMBER, PREBILLAMOUNT, CUSTOMERNUMBER, CURRENCYCODE, INVOICEAMOUNTDECIMALS, STOP_ID, ROUTECONTROL_ID, CUSTOMER_ID, CLIENT_NAME, INVOICEBUSINESSUNIT_ID, ROUTE_ID, DELPOINTID, PLANT_ID)
as select i.invoicenumber, i.prebillamount, c.customernumber, r.code currencycode, r.invoiceamountdecimals
       , i.stop_id, i.routecontrol_id, c.customer_id, cl.name Client_Name, i.invoicebusinessunit_id, i.route_id
, coalesce ((select dp.deliverypoint_id from departmentroom dr, distributionpoint dp where cl.departmentroom_id = dr.departmentroom_id and dr.distributionpoint_id = dp.distributionpoint_id), cl.deliverypoint_link_id) delpointID
, ibu.plant_id
from invoiceheader i, customer c , currency r, invoiceheaderclient ihc, client_link cl, businessunit ibu
where i.deltocustomer_link_id = c.customer_id
and c.currency_id = r.currency_id
and ihc.invoiceheader_id = i.invoiceheader_id
and ihc.client_link_id = cl.client_link_id
and i.invoicebusinessunit_id = ibu.businessunit_id
and i.documenttype = 3
and ihc.clientinvoicetype = 1
and ihc.paiddate is null
and i.originalcollectiontype = 1

/
create or replace view V_ROUTELISTSTOPPN_SMG
 (CODE, ACTIVITY_ID, STOP_ID, CUSTOMER_ID, STOPNOTENO)
as select  distinct vnt.code,vnt.activity_id, vnt.stop_id, vnt.customer_id,f_getactivitystop(vnt.activity_id,vnt.stop_id)stopnoteno
from (
select  a.code, a.activity_id,  pn.stop_id,sp.customer_link_id customer_id
from packingnote pn,packingnoteline pl, product p, productgroup pg, activity a,  stop sp
where pn.packingnote_id=pl.packingnote_id
      and pl.product_id=p.product_id
      and p.productgroup_id=pg.productgroup_id
      and pg.activity_id=a.activity_id
      and pn.stop_id = sp.stop_id
      and sp.routecontrol_id = pn.routecontrol_id
      and pn.status_id = ( select st.status_id from status st where st.statustype='PN' and st.code='30')
union
  select  a.code,a.activity_id,pn.stop_id, sp.customer_link_id customer_id
from packingnote pn,packingnotecontainer pnc, weighingcategory wg, activity a,  stop sp
where pn.packingnote_id=pnc.packingnote_id
     and pnc.weighingcategory_id=wg.weighingcategory_id
     and wg.activity_id=a.activity_id
     and pn.stop_id = sp.stop_id
     and sp.routecontrol_id = pn.routecontrol_id
     and pn.status_id = ( select st.status_id from status st where st.statustype='PN' and st.code='30')) vnt

/
create or replace view V_ROUTELIST_AMM
 (INVOICENUMBER, INVOICEDATE, PLANTCOUNTRYID, LANGUAGECODE, INVOICEHEADER_ID, PRODUCTCODE, PRODUCT_ID, SIZEDEFINITION_ID, FINISHINGMETHOD_ID, QTYDELIVERED, QTYDELIVERED_PNL, BILLINGMETHOD, INVENTORYQTY, PRICE, BILLEDQTY, AMOUNT, MINIMUMPERCENTAGE, MINIMUMQUANTITY, SOILQUANTITY, ROUTENUMBER, DRIVINGYEAR, DRIVINGWEEK, SHOWSTOP, DELIVERYSCHEMECODE, DELIVERYFREQUENCY, DELIVERYDAYS, NEXTDELIVERYDATE, CUSTOMER_ID, DATEINACTIVE, CUSTOMERNUMBER, CUSTOMERNAME, DELIVERYADDRESS1, DELIVERYADDRESS2
, DELIVERYCITY, DELIVERYSTATE, DELIVERYZIPCODE, CUSTOMERCOUNTRYID, COUNTRYCODE, CUSTOMERPHONE, SRCMETHOD, SRC, TYPEOFMERCHADISE, PRODUCTDESCRIPTION, SIZECODE, FINISHINGMETHODCODE, REPORTPARAM_ID, DEL_POINT_START_TIME, DEL_POINT_END_TIME, BREAKSTARTTIME, BREAKENDTIME, ROUTE_START_TIME, STOP_TRAVELMINUTES, STOP_SERVICEMINUTES, DELIVERYSCHEMESTARTDATE, QTYEXPECTED, ENDCONTRACT, DETAIL, MOVEDROUTENUMBER, MOVEDROUTEDESCRIPTION, STATUS, COUNTRY, SHOWLOCKERONROUTELIST
, PUTUPTYPE_PRODUCT, PUTUPTYPE_PLPC, STRAIGHTEVENEXCHANGE, DELNOTEFORBULKPUTUPITEMS, NOTENUMBER, STOP_DELIVERYPOINT_ID, PN_DELIVERYPOINT_ID, CITY, STATE, ZIPCODE, HOUSENUMBER, HOUSENUMBEREXT, C_DELIVERYADDRESS1, C_DELIVERYADDRESS2, C_CITY, C_STATE, C_ZIPCODE, C_HOUSENUMBER, C_HOUSENUMBEREXT, MOBILEPHONE, DEPARTMENTNUMBER, DISTRIBUTIONPOINTNUMBER, DELIVERYPOINTCODE, DEPARTMENTDESC, DISTRIBUTIONPOINTDESC, DELIVERYPOINTDESC, ROUTECONTROL_ID, STOP_ID, ROUTE_ID
, DRIVINGDATE, STOPTYPE, STOP_DELIVERYPOINT, ROUTESTOP_ID, STOPNUMBER, STOPSTATUS, PLANTCODE, ROUTEDESCRIPTION, ROUTELISTINSTRUCTIONS, DEPOTCODE, DEPOTDESCRIPTION, LOADINGDOCK, STARTTIME, DRIVERNAME, DRIVERNUMBER, TRUCKCODE, TRUCKDESCRIPTION, CONTACTPERSONNAME, CONTACTPERSONPHONE, CONTACTPERSONMOBILEPHONE)
as select ih.invoicenumber, ih.invoicedate, pt.country_id plantcountryid,
       (select lg.code from languages lg where lg.language_id = pt.language_id) languagecode,
       il.invoiceheader_id, il.code productcode, ilp.product_link_id product_id,
       ilp.sizedefinition_link_id sizedefinition_id, ilp.finishingmethod_id,
       max(ilp.deliveredqty) qtydelivered, max(ilp.deliveredqty) qtydelivered_pnl,
       max(ilp.billingmethod) billingmethod, max(ilp.inventoryqty) inventoryqty, max(il.price) price,
       max(il.billedqty) billedqty, sum(il.amount) amount,
       max(ilp.minimumpercentage) minimumpercentage, max(ilp.minimumquantity) minimumquantity,
       max(ilp.soilquantity) soilquantity, ih.routenumber,
       --to_char(rc.drivingdate, 'IYYY') drivingyear, getisoweek(rc.drivingdate) drivingweek,
       getYearofWeek(rc.drivingdate) drivingyear, getisoweek(rc.drivingdate) drivingweek,
       f_show_routestop(sp.stop_id, rs.routestop_id, r.plant_id)  showstop,
       --to see if this is the problem
       nvl(min(ilp.deliveryschemecode),
            (select min(dsp.code)
              from   deliveryschemesperstop dsps, deliveryscheme dsp
              where  dsps.routestop_id = rs.routestop_id
              and    dsps.customer_id = sp.customer_link_id
              and    dsps.deliveryscheme_id = dsp.deliveryscheme_id)) deliveryschemecode,
       (select ds.frequency
         from   deliveryscheme ds
         where  ds.code = nvl(ilp.deliveryschemecode,
                              (select min(dsp.code)
                                from   deliveryschemesperstop dsps, deliveryscheme dsp
                                where  dsps.routestop_id = rs.routestop_id
                                and    dsps.customer_id = sp.customer_link_id
                                and    dsps.deliveryscheme_id = dsp.deliveryscheme_id))) deliveryfrequency,
       nvl((select to_char(pddm.day_id)
            from   productdeliveryday pddm
            where  pddm.productlistpercustomer_id = l.productlistpercustomer_id
            and    pddm.day_id = 1), '-') ||
        nvl((select to_char(pddm.day_id)
            from   productdeliveryday pddm
            where  pddm.productlistpercustomer_id = l.productlistpercustomer_id
            and    pddm.day_id = 2), '-') ||
        nvl((select to_char(pddm.day_id)
            from   productdeliveryday pddm
            where  pddm.productlistpercustomer_id = l.productlistpercustomer_id
            and    pddm.day_id = 3), '-') ||
        nvl((select to_char(pddm.day_id)
            from   productdeliveryday pddm
            where  pddm.productlistpercustomer_id = l.productlistpercustomer_id
            and    pddm.day_id = 4), '-') ||
        nvl((select to_char(pddm.day_id)
            from   productdeliveryday pddm
            where  pddm.productlistpercustomer_id = l.productlistpercustomer_id
            and    pddm.day_id = 5), '-') ||
        nvl((select to_char(pddm.day_id)
            from   productdeliveryday pddm
            where  pddm.productlistpercustomer_id = l.productlistpercustomer_id
            and    pddm.day_id = 6), '-') ||
        nvl((select to_char(pddm.day_id)
            from   productdeliveryday pddm
            where  pddm.productlistpercustomer_id = l.productlistpercustomer_id
            and    pddm.day_id = 7), '-') deliverydays,
       (select min(rc.drivingdate)
         from   routecontrol rc2, stop sp
         where  rc2.drivingdate > rc.drivingdate
         and    rc2.routecontrol_id = sp.routecontrol_id
         and    sp.customer_link_id = ih.deltocustomer_link_id) nextdeliverydate,
       ih.deltocustomer_link_id customer_id, c.dateinactive, c.customernumber, c.name customername,
       da.street deliveryaddress1, da.street2 deliveryaddress2, da.city deliverycity,
       da.state deliverystate, da.zipcode deliveryzipcode, c.country_id customercountryid,
       (select ct.code from country ct where ct.country_id = c.country_id) countrycode,
       c.phoneno customerphone, l.srcmethod,
       case
         when l.srcmethod = 1 then
          max(l.srcpercentagesoilcount)
         when l.srcmethod = 2 then
          max(l.srcpercentageinventory)
         when l.srcmethod = 3 then
          max(l.srcquantity)
         else
          0
       end src,
       (select p.typeofmerchandise from product p where p.product_id = ilp.product_link_id) typeofmerchadise,
       (select pd.description
         from   product_desc pd
         where  pd.product_id = ilp.product_link_id
         and    pd.language_id = pt.language_id) productdescription,
       (select s.code from sizedefinition s where s.sizedefinition_id = ilp.sizedefinition_link_id) sizecode,
       (select f.code from finishingmethod f where f.finishingmethod_id = ilp.finishingmethod_id) finishingmethodcode,
       rp.reportparam_id, null del_point_start_time, null del_point_end_time, null breakstarttime,
       null breakendtime, null route_start_time, null stop_travelminutes, null stop_serviceminutes,
       null deliveryschemestartdate, null qtyexpected, null endcontract, null detail,
       null movedroutenumber, null movedroutedescription, null status, null country,
       null showlockeronroutelist, null putuptype_product, null putuptype_plpc,
       null straightevenexchange, null delnoteforbulkputupitems, null notenumber,
       null stop_deliverypoint_id, null pn_deliverypoint_id, null city, null state, null zipcode,
       null housenumber, null housenumberext, null c_deliveryaddress1, null c_deliveryaddress2,
       null c_city, null c_state, null c_zipcode, null c_housenumber, null c_housenumberext,
       null mobilephone, null departmentnumber, null distributionpointnumber, null deliverypointcode,
       null departmentdesc, null distributionpointdesc, null deliverypointdesc, rc.routecontrol_id,
       sp.stop_id, rc.route_id, rc.drivingdate, sp.stoptype, sp.deliverypoint_id stop_deliverypoint,
       sp.routestop_id, rs.stopnumber, sp.status stopstatus,
       (select rpt.code from plant rpt where rpt.plant_id = r.plant_id) plantcode,
       r.description routedescription, (dbms_lob.substr( sp.routelistinstructions)) routelistinstructions,
       (select dp.code from depot dp where dp.depot_id = r.depot_id) depotcode,
       (select dp.description from depot dp where dp.depot_id = r.depot_id) depotdescription,
       r.loadingdock, r.starttime,
       (select ed.name from employee ed where ed.employee_id = r.driver_id) drivername,
       (select ed.employeenumber from employee ed where ed.employee_id = r.driver_id) drivernumber,
       (select t.code from truck t where t.truck_id = r.truck_id) truckcode,
       (select t.description from truck t where t.truck_id = r.truck_id) truckdescription,
       (select cp.name from contactperson cp where sp.contactperson_id = cp.contactperson_id) contactpersonname,
       (select cp.phone from contactperson cp where sp.contactperson_id = cp.contactperson_id) contactpersonphone,
       (select cp.mobilephone from contactperson cp where sp.contactperson_id = cp.contactperson_id) contactpersonmobilephone
from   reportparam rp, invoiceheader ih, invoiceline il, invoicelineproduct ilp, plant pt,
       businessunit bu, customer c, address da, routecontrol rc, route r, stop sp, routestop rs,
       productlistpercustomer l
where  ih.invoiceheader_id = il.invoiceheader_id
and    ih.invoicebusinessunit_id = bu.businessunit_id
and    bu.plant_id = pt.plant_id
and    ih.routecontrol_id = rc.routecontrol_id
and    ih.routenumber = r.routenumber
and    ih.stopnumber = rs.stopnumber
and    ih.stop_id = sp.stop_id
and    ih.route_id = rc.route_id
and    ih.deltocustomer_link_id = c.customer_id
and    c.visitaddress_id = da.address_id
and    ih.deltocustomer_link_id = l.customer_id
and    rs.route_id = r.route_id
and    rc.routecontrol_id = sp.routecontrol_id
and    rc.route_id = r.route_id
and    il.invoiceline_id = ilp.invoiceline_id
and    il.invoicelinetype_id in (1, 2, 5)
and    sp.routestop_id = rs.routestop_id
and    l.productlistpercustomer_id =
       (select max(lx.productlistpercustomer_id)
         from   productlistpercustomer lx
         where  lx.customer_id = ih.deltocustomer_link_id
         and    lx.product_id = ilp.product_link_id
         and    ((lx.sizedefinition_id =
               (select s.sizedefinition_id from sizedefinition s where s.code = '*')) or
               lx.sizedefinition_id = ilp.sizedefinition_link_id)
         and    lx.finishingmethod_id = ilp.finishingmethod_id
         and    ih.invoicedate between lx.dateactive and lx.dateinactive)
and    ih.documenttype = 1
and    ih.status_id <> 3
and    rp.number_value = ih.routecontrol_id
group  by ih.invoicenumber, ih.invoicedate, pt.country_id, pt.language_id, il.invoiceheader_id,
          il.code, ilp.product_link_id, ilp.sizedefinition_link_id, ilp.finishingmethod_id,
          ilp.deliveryschemecode, ih.routenumber, to_char(rc.drivingdate, 'IYYY'),
          getisoweek(rc.drivingdate), rs.routestop_id, sp.customer_link_id,
          l.productlistpercustomer_id, ih.deltocustomer_link_id, c.dateinactive, c.customernumber,
          c.name, da.street, da.street2, da.city, da.state, da.zipcode, c.country_id, c.country_id,
          c.phoneno, l.srcmethod, ilp.product_link_id, rp.reportparam_id, rc.routecontrol_id,
          sp.stop_id, rc.route_id, rc.drivingdate, sp.stoptype, sp.deliverypoint_id, sp.routestop_id,
          rs.stopnumber, sp.status, r.plant_id, r.description, (dbms_lob.substr( sp.routelistinstructions)) , r.depot_id,
          r.loadingdock, r.starttime, r.driver_id, r.truck_id, sp.contactperson_id

/
create or replace view V_ROUTELIST_BAGTAGS_LLG
 (PACKINGNOTENUMBER, BAGTAGNUMBER, ROUTECONTROL_ID, STOP_ID)
as select pn.notenumber packingnotenumber,
bt.primaryid bagtagnumber,
pn.routecontrol_id,
pn.stop_id
from packingnote pn, bagtag bt, status s
where pn.packingnote_id = bt.packingnote_id
and pn.status_id = s.status_id
and s.statustype = 'PN'
and s.code not in (40,60)
and exists (select 1 from packingnoteline pnl where pnl.packingnote_id = pn.packingnote_id and pnl.deliveredamount <> 0)

/
create or replace view V_ROUTELIST_CN_LLG
 (CONSIGNMENTNOTENUMBER, CUSTOMER_LINK_ID, DELIVERYDATE, STOPNUMBER, ROUTE_ID, DRIVINGDATE, ROUTECONTROL_ID, STOP_ID)
as select cn.consignmentnotenumber,
cn.customer_link_id,
cn.deliverydate,
cn.stopnumber,
cn.route_id,
rc.drivingdate,
rc.routecontrol_id,
s.stop_id
from consignmentnote cn,
routecontrol rc,
stop s
where cn.route_id = rc.route_id
and cn.deliverydate = rc.originaldrivingdate
and s.routecontrol_id = rc.routecontrol_id
and s.customer_link_id = cn.customer_link_id

/
create or replace view V_ROUTELIST_SMG
 (LINETYPE, ROUTESTOP_ID, CUSTOMER_ID, SHOWSTOP, ROUTECONTROL_ID, STOP_DELIVERYPOINT_ID, PLANTCODE, ROUTENUMBER, ROUTEDESCRIPTION, DRIVINGDATE, DEPOTDESCRIPTION, LOADINGDOCK, STARTTIME, DRIVERNAME, TRUCKCODE, TRUCKDESCRIPTION, STOPNUMBER, CUSTOMERNUMBER, CUSTOMERNAME, CUSTNR, DELIVERYADDRESS1, DELIVERYADDRESS2, CITY, STATE, ZIPCODE, C_DELIVERYADDRESS1, C_DELIVERYADDRESS2, C_CITY, C_STATE, C_ZIPCODE, 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, ROUTE_START_TIME, STOP_TRAVELMINUTES, STOP_SERVICEMINUTES, DATEINACTIVE, DEL_POINT_START_TIMECH, DEL_POINT_END_TIMECH, BREAKSTARTTIMECH, BREAKENDTIMECH, ROUTE_START_TIMECH24, STARTTIMECH, SHOWONROUTELIST, CONTACTNOTES, CONTACTSTATUS, PLANT_ID, PLANTEMAIL, COMMETHOD, COUNTCONTAINERS, COUNTCONTSTOP
)
as SELECT 1 linetype,d.routestop_id, 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,
  S.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, A.DRIVINGDATE,
  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,insertspace_after_x_characters(to_char(P.CUSTOMERNUMBER),3) custnr,
  T.STREET DELIVERYADDRESS1, T.STREET2 DELIVERYADDRESS2, T.CITY, T.STATE, T.ZIPCODE,
  '' C_DELIVERYADDRESS1, '' C_DELIVERYADDRESS2, '' C_CITY, '' C_STATE, '' C_ZIPCODE,
  d.routelistinstructions,
  Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE, z.mobilephone, 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, ( select vr.routenumber from routecontrol vc join route vr on vr.route_id = vc.route_id  where vc.routecontrol_id = v.routecontrol_id) movedroutenumber,
  ( select vr.description from routecontrol vc join route vr on vr.route_id = vc.route_id  where vc.routecontrol_id = v.routecontrol_id) 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
  , n.breakstarttime breakstarttime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
  , p.dateinactive
  , (SELECT to_char(HH.STARTTIME,'fmhhfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIMECH
  , (SELECT to_char(HH.ENDTIME,'fmhhfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIMECH
  , to_char(n.breakstarttime,'fmHH:MI:AM') breakstarttimeCH, to_char(n.breakendtime,'fmHH:MI:AM') breakendtimeCH
  , to_char(B.STARTTIME,'fmhh24fm:MI') ROUTE_START_TIMECH24
  , to_char(A.STARTTIME,'fmhhfm:MI:AM') STARTTIMECH
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, a.plant_id
 ,cast((select GetSubstringOnLength(pl.email,0,40) from plant pl where pl.plant_id=a.plant_id)as varchar2(40)) plantemail
,(select cmd.description from  communicationmethod_desc cmd where cmd.communicationmethod_id=p.communicationmethod_id and cmd.language_id=LANGUAGES.LANGUAGE_ID) commethod
,(select  nvl(count(distinct pnc.container_id),0) countContainer from   packingnote pn, packingnotecontainer pnc
   where pn.packingnote_id = pnc.packingnote_id and pnc.container_id is not null and pn.routecontrol_id=a.routecontrol_id and pn.status_id=7)countContainers
,(select  nvl(count(distinct pnc.container_id),0) countContainer from   packingnote pn, packingnotecontainer pnc
   where pn.packingnote_id = pnc.packingnote_id and pnc.container_id is not null and pn.routecontrol_id=a.routecontrol_id and pn.status_id=7 and pn.stop_id=d.stop_id)countContStop
 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 stop 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)
    left outer join contact cont ON (cont.contact_id = coalesce(f_getcontactonroutelist(p.customer_id), -1)),
  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
  N.CUSTOMER_ID=P.CUSTOMER_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 --TNE ORDER 500713
  and rp.NUMBER_VALUE = a.ROUTECONTROL_ID
UNION ALL          -- 2 --
SELECT 2 linetype,
  d.routestop_id,  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,
   S.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, A.DRIVINGDATE,
   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,insertspace_after_x_characters(to_char(P.CUSTOMERNUMBER),3) custnr,
  T.STREET DELIVERYADDRESS1, T.STREET2 DELIVERYADDRESS2, T.CITY, T.STATE, T.ZIPCODE,
  '' C_DELIVERYADDRESS1, '' C_DELIVERYADDRESS2, '' C_CITY, '' C_STATE, '' C_ZIPCODE,
  d.routelistinstructions,
  Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE, z.mobilephone,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, ( select vr.routenumber from routecontrol vc join route vr on vr.route_id = vc.route_id  where vc.routecontrol_id = v.routecontrol_id) movedroutenumber,
  ( select vr.description from routecontrol vc join route vr on vr.route_id = vc.route_id  where vc.routecontrol_id = v.routecontrol_id) 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 breakstarttime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES STOP_TRAVELMINUTES, E.SERVICEMINUTES STOP_SERVICEMINUTES
  , p.dateinactive
  , (SELECT to_char(HH.STARTTIME,'fmHHfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_START_TIMECH
  , (SELECT to_char(HH.ENDTIME,'fmHHfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = N.DELIVERYPOINT_ID AND HH.DAY_ID = B.DRIVINGDAY_ID) DEL_POINT_END_TIMECH
  , to_char(n.breakstarttime,'fmHHfm:MI:AM') breakstarttimeCH, to_char(n.breakendtime,'fmHH:MI:AM') breakendtimeCH
  , to_char(B.STARTTIME,'fmHH24fm:MI') ROUTE_START_TIMECH24
  , to_char(A.STARTTIME,'fmHHfm:MI:AM') STARTTIMECH
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, a.plant_id
 ,cast((select GetSubstringOnLength(pl.email,0,40) from plant pl where pl.plant_id=a.plant_id)as varchar2(40)) plantemail
 ,(select cmd.description from  communicationmethod_desc cmd where cmd.communicationmethod_id=p.communicationmethod_id and cmd.language_id=LANGUAGES.LANGUAGE_ID) commethod
 ,(select  nvl(count(distinct pnc.container_id),0) countContainer from   packingnote pn, packingnotecontainer pnc
   where pn.packingnote_id = pnc.packingnote_id and pnc.container_id is not null and pn.routecontrol_id=a.routecontrol_id and pn.status_id=7)countContainers
   ,(select  nvl(count(distinct pnc.container_id),0) countContainer from   packingnote pn, packingnotecontainer pnc
   where pn.packingnote_id = pnc.packingnote_id and pnc.container_id is not null and pn.routecontrol_id=a.routecontrol_id and pn.status_id=7 and pn.stop_id=d.stop_id)countContStop
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 stop 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)
    left outer join contact cont ON (cont.contact_id = coalesce(f_getcontactonroutelist(p.customer_id), -1)),
  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
  N.CUSTOMER_ID=P.CUSTOMER_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 linetype,
  d.routestop_id,  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,
  S.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, A.DRIVINGDATE,
  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,insertspace_after_x_characters(to_char(P.CUSTOMERNUMBER),3) custnr,
  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,
  d.routelistinstructions,
  Z.NAME CONTACTPERSONNAME, Z.PHONE CONTACTPERSONPHONE,z.mobilephone, 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, ( select vr.routenumber from routecontrol vc join route vr on vr.route_id = vc.route_id  where vc.routecontrol_id = v.routecontrol_id) movedroutenumber,
  ( select vr.description from routecontrol vc join route vr on vr.route_id = vc.route_id  where vc.routecontrol_id = v.routecontrol_id) 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 breakstarttime
  , B.STARTTIME ROUTE_START_TIME, E.TRAVELMINUTES ROUTESTOP_TRAVELMINUTES, E.SERVICEMINUTES ROUTESTOP_SERVICEMINUTES
  , p.dateinactive
  , (SELECT to_char(HH.STARTTIME,'fmHHfm:MI:AM') FROM deliverypointopeninghour HH
            WHERE HH.DELIVERYPOINT_ID = dp.DELIVERYPOINT_ID AND HH.DAY_ID = B.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 = B.DRIVINGDAY_ID) DEL_POINT_END_TIMECH
  , to_char(dp.breakstarttime,'fmHHfm:MI:AM') breakstarttimeCH, to_char(dp.breakendtime,'fmHH:MI:AM') breakendtimeCH
  , to_char(B.STARTTIME,'fmHH24fm:MI') ROUTE_START_TIMECH24
  , to_char(A.STARTTIME,'fmHHfm:MI:AM') STARTTIMECH
  , cont.showonroutelist, cont.contactnotes, cont.status contactstatus, a.plant_id
 ,cast((select GetSubstringOnLength(pl.email,0,40) from plant pl where pl.plant_id=a.plant_id)as varchar2(40)) plantemail
 ,(select cmd.description from  communicationmethod_desc cmd where cmd.communicationmethod_id=p.communicationmethod_id and cmd.language_id=LANGUAGES.LANGUAGE_ID) commethod
 ,(select  nvl(count(distinct pnc.container_id),0) countContainer from   packingnote pn, packingnotecontainer pnc
   where pn.packingnote_id = pnc.packingnote_id and pnc.container_id is not null and pn.routecontrol_id=a.routecontrol_id and pn.status_id=7)countContainers
   ,(select  nvl(count(distinct pnc.container_id),0) countContainer from   packingnote pn, packingnotecontainer pnc
   where pn.packingnote_id = pnc.packingnote_id and pnc.container_id is not null and pn.routecontrol_id=a.routecontrol_id and pn.status_id=7 and pn.stop_id=d.stop_id)countContStop
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 stop 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)
    left outer join contact cont ON (cont.contact_id = coalesce(f_getcontactonroutelist(p.customer_id), -1)),
  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_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, PRODUCTDESCRIPTION, PUTUPREPORTROUTESTOP, SIZECODE, FINISHINGMETHODCODE, TOBEDELIVEREDAMOUNT, SIZEDESCRIPTION, DISTRIBUTIONPOINTNUMBER, REMARKONPACKINGNOTE, PACKREMARKENDDATE, LANGUAGECODE, DEPARTMENTNUMBER, PACKDEP_CODE, PACKDEP_DESC, REMARKFORPACKINGINSTRUCTIONS
, REPLACEMENTQTY, REPLACEMENTLOSSQTY)
as SELECT A.ROUTECONTROL_ID,
  D.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, X.DESCRIPTION DEPOTDESCRIPTION, --Y.NAME DRIVERNAME,
  (SELECT EMP.NAME FROM EMPLOYEE EMP WHERE EMP.EMPLOYEENUMBER = A.DRIVERNUMBER AND EMP.PLANT_ID = A.PLANT_ID) DRIVERNAME,
  A.DRIVINGDATE, A.LOADINGDOCK, A.PACKINGDEADLINE STARTTIME, Z.CODE TRUCKCODE, Z.DESCRIPTION TRUCKDESCRIPTION,
  E.STOPNUMBER, K.CUSTOMERNUMBER, K.SEARCHNAME, K.LEGALNAME, K.NAME CUSTOMERNAME,
  J.CODE PRODUCTCODE,
  (SELECT DESCRIPTION FROM PRODUCT_DESC W WHERE J.PRODUCT_ID = W.PRODUCT_ID AND W.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
  B.PUTUPREPORTROUTESTOP,
  H.CODE SIZECODE, I.CODE FINISHINGMETHODCODE, G.TOBEDELIVEREDAMOUNT,
  (SELECT DESCRIPTION FROM SIZEDEFINITION_DESC SW WHERE H.SIZEDEFINITION_ID = SW.SIZEDEFINITION_ID AND SW.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDESCRIPTION,
  L.DISTRIBUTIONPOINTNUMBER, L.REMARKONPACKINGNOTE, L.PACKREMARKENDDATE,
  LANGUAGES.CODE LANGUAGECODE, DEP.DEPARTMENTNUMBER
  , PL.CODE PACKDEP_CODE, PL.DESCRIPTION PACKDEP_DESC--501742
  , G.REMARKFORPACKINGINSTRUCTIONS
	, G.REPLACEMENTQTY
  , G.REPLACEMENTLOSSQTY
FROM ROUTECONTROL A
     LEFT OUTER JOIN TRUCK Z ON (Z.CODE = A.TRUCKCODE AND Z.PLANT_ID = A.PLANT_ID),
  ROUTE B
     LEFT OUTER JOIN DEPOT X ON (X.DEPOT_ID = B.DEPOT_ID)
    --LEFT OUTER JOIN EMPLOYEE Y ON (Y.EMPLOYEE_ID = B.DRIVER_ID)
    --LEFT OUTER JOIN TRUCK Z ON (Z.TRUCK_ID = B.TRUCK_ID)
    , PLANT D, STOP E, PACKINGNOTE F, PACKINGNOTELINE G, SIZEDEFINITION H, FINISHINGMETHOD I, PRODUCT J,
  CUSTOMER K, LANGUAGES, DISTRIBUTIONPOINT L, DEPARTMENT DEP
  , PLANTDEPARTMENT PL, STATUS ST
WHERE A.ROUTE_ID = B.ROUTE_ID AND
  A.PLANT_ID = D.PLANT_ID AND
  A.ROUTECONTROL_ID = E.ROUTECONTROL_ID AND
  E.STOP_ID = F.STOP_ID AND
  F.PACKINGNOTE_ID = G.PACKINGNOTE_ID AND
  G.SIZEDEFINITION_ID = H.SIZEDEFINITION_ID AND
  G.FINISHINGMETHOD_ID = I.FINISHINGMETHOD_ID AND
  G.PRODUCT_ID = J.PRODUCT_ID AND
  E.CUSTOMER_LINK_ID = K.CUSTOMER_ID AND
  F.DISTRIBUTIONPOINT_ID = L.DISTRIBUTIONPOINT_ID AND
  (E.STATUS = 0 OR E.STATUS = 3)--TNE ORDER500713
  AND L.DEPARTMENT_ID = DEP.DEPARTMENT_ID -- TNE TODO4042
  AND PL.PLANTDEPARTMENT_ID=F.PLANTDEPARTMENT_ID
  AND F.STATUS_ID = ST.STATUS_ID
  AND ST.CODE <> '40'

/
create or replace view V_ROUTESTOPPUTUPLIST_AMM
 (ROUTECONTROL_ID, PLANTCODE, ROUTENUMBER, ROUTEDESCRIPTION, DEPOTDESCRIPTION, DRIVERNAME, DRIVINGDATE, LOADINGDOCK, STARTTIME, TRUCKCODE, TRUCKDESCRIPTION, STOPNUMBER, CUSTOMERNUMBER, SEARCHNAME, LEGALNAME, CUSTOMERNAME, PRODUCTCODE, PRODUCTDESCRIPTION, PUTUPREPORTROUTESTOP, SIZECODE, FINISHINGMETHODCODE, TOBEDELIVEREDAMOUNT, SIZEDESCRIPTION, DISTRIBUTIONPOINTNUMBER, REMARKONPACKINGNOTE, PACKREMARKENDDATE, LANGUAGECODE, DEPARTMENTNUMBER, PACKDEP_CODE, PACKDEP_DESC, REMARKFORPACKINGINSTRUCTIONS
)
as SELECT A.ROUTECONTROL_ID,
  D.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, X.DESCRIPTION DEPOTDESCRIPTION, --Y.NAME DRIVERNAME,
  (SELECT EMP.NAME FROM EMPLOYEE EMP WHERE EMP.EMPLOYEENUMBER = A.DRIVERNUMBER AND EMP.PLANT_ID = A.PLANT_ID) DRIVERNAME,
  A.DRIVINGDATE, A.LOADINGDOCK, A.PACKINGDEADLINE STARTTIME, Z.CODE TRUCKCODE, Z.DESCRIPTION TRUCKDESCRIPTION,
  E.STOPNUMBER, K.CUSTOMERNUMBER, K.SEARCHNAME, K.LEGALNAME, K.NAME CUSTOMERNAME,
  J.CODE PRODUCTCODE,
  (SELECT DESCRIPTION FROM PRODUCT_DESC W WHERE J.PRODUCT_ID = W.PRODUCT_ID AND W.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
  B.PUTUPREPORTROUTESTOP,
  H.CODE SIZECODE, I.CODE FINISHINGMETHODCODE, G.TOBEDELIVEREDAMOUNT,
  (SELECT DESCRIPTION FROM SIZEDEFINITION_DESC SW WHERE H.SIZEDEFINITION_ID = SW.SIZEDEFINITION_ID AND SW.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDESCRIPTION,
  L.DISTRIBUTIONPOINTNUMBER, L.REMARKONPACKINGNOTE, L.PACKREMARKENDDATE,
  LANGUAGES.CODE LANGUAGECODE, DEP.DEPARTMENTNUMBER
  , PL.CODE PACKDEP_CODE, PL.DESCRIPTION PACKDEP_DESC--501742
  , G.REMARKFORPACKINGINSTRUCTIONS
FROM ROUTECONTROL A
     LEFT OUTER JOIN TRUCK Z ON (Z.CODE = A.TRUCKCODE AND Z.PLANT_ID = A.PLANT_ID),
  ROUTE B
     LEFT OUTER JOIN DEPOT X ON (X.DEPOT_ID = B.DEPOT_ID)
    --LEFT OUTER JOIN EMPLOYEE Y ON (Y.EMPLOYEE_ID = B.DRIVER_ID)
    --LEFT OUTER JOIN TRUCK Z ON (Z.TRUCK_ID = B.TRUCK_ID)
    , PLANT D, STOP E, PACKINGNOTE F, PACKINGNOTELINE G, SIZEDEFINITION H, FINISHINGMETHOD I, PRODUCT J,
  CUSTOMER K, LANGUAGES, DISTRIBUTIONPOINT L, DEPARTMENT DEP
  , PLANTDEPARTMENT PL, STATUS ST
WHERE A.ROUTE_ID = B.ROUTE_ID AND
  A.PLANT_ID = D.PLANT_ID AND
  A.ROUTECONTROL_ID = E.ROUTECONTROL_ID AND
  E.STOP_ID = F.STOP_ID AND
  F.PACKINGNOTE_ID = G.PACKINGNOTE_ID AND
  G.SIZEDEFINITION_ID = H.SIZEDEFINITION_ID AND
  G.FINISHINGMETHOD_ID = I.FINISHINGMETHOD_ID AND
  G.PRODUCT_ID = J.PRODUCT_ID AND
  E.CUSTOMER_LINK_ID = K.CUSTOMER_ID AND
  F.DISTRIBUTIONPOINT_ID = L.DISTRIBUTIONPOINT_ID  --  AND (E.STATUS = 0 OR E.STATUS = 3)--TNE ORDER500713
  AND L.DEPARTMENT_ID = DEP.DEPARTMENT_ID -- TNE TODO4042
  AND PL.PLANTDEPARTMENT_ID=F.PLANTDEPARTMENT_ID
  AND F.STATUS_ID = ST.STATUS_ID
  AND ST.CODE <> '40'

/
create or replace view V_ROUTESTOPPUTUPLIST_BNL
 (ROUTECONTROL_ID, PLANTCODE, ROUTENUMBER, ROUTEDESCRIPTION, DEPOTDESCRIPTION, DRIVERNAME, DRIVINGDATE, LOADINGDOCK, STARTTIME, TRUCKCODE, TRUCKDESCRIPTION, STOPNUMBER, CUSTOMERNUMBER, SEARCHNAME, LEGALNAME, CUSTOMERNAME, PRODUCTCODE, ROUTELISTINSTRUCTIONS, PRODUCTDESCRIPTION, PUTUPREPORTROUTESTOP, SIZECODE, FINISHINGMETHODCODE, TOBEDELIVEREDAMOUNT, SIZEDESCRIPTION, DISTRIBUTIONPOINTNUMBER, REMARKONPACKINGNOTE, PACKREMARKENDDATE, LANGUAGECODE, DEPARTMENTNUMBER, PACKDEP_CODE
, PACKDEP_DESC, PRODGROUPCODE, STREET, HOUSENUMBER, ZIPCODE, CITY)
as SELECT A.ROUTECONTROL_ID,
  D.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, X.DESCRIPTION DEPOTDESCRIPTION, --Y.NAME DRIVERNAME,
  (select EMP.NAME from EMPLOYEE EMP where EMP.Employeenumber = A.Drivernumber and EMP.Plant_Id = A.Plant_Id) DRIVERNAME,
  A.DRIVINGDATE, A.LOADINGDOCK, A.PACKINGDEADLINE STARTTIME, Z.CODE TRUCKCODE, Z.DESCRIPTION TRUCKDESCRIPTION,
  E.STOPNUMBER, K.CUSTOMERNUMBER, K.SEARCHNAME, K.LEGALNAME, K.Name Customername,
  J.CODE PRODUCTCODE, E.ROUTELISTINSTRUCTIONS,
  (SELECT description FROM PRODUCT_DESC W WHERE J.PRODUCT_ID = W.PRODUCT_ID AND W.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
  B.PUTUPREPORTROUTESTOP,
  H.CODE SIZECODE, I.CODE FINISHINGMETHODCODE, G.TOBEDELIVEREDAMOUNT,
  (SELECT description FROM SIZEDEFINITION_DESC SW WHERE H.SIZEDEFINITION_ID = SW.SIZEDEFINITION_ID AND SW.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDESCRIPTION,
  L.DISTRIBUTIONPOINTNUMBER, L.REMARKONPACKINGNOTE, L.PACKREMARKENDDATE,
  LANGUAGES.CODE LANGUAGECODE, dep.departmentnumber
  , PL.Code PackDep_code, PL.Description PackDep_desc--501742
  , (select pg.code from productgroup pg where j.productgroup_id = pg.productgroup_id ) ProdGroupCode
  , coalesce((select ad.street from deliverypoint dp, address ad where dp.deliverypoint_id = e.deliverypoint_id and ad.address_id = dp.deliveryaddress_id),
             (select adr.street from address adr where adr.address_id = k.visitaddress_id)) Street
  , coalesce((select ad.housenumber from deliverypoint dp, address ad where dp.deliverypoint_id = e.deliverypoint_id and ad.address_id = dp.deliveryaddress_id),
             (select adr.housenumber from address adr where adr.address_id = k.visitaddress_id)) Housenumber
  , coalesce((select ad.zipcode from deliverypoint dp, address ad where dp.deliverypoint_id = e.deliverypoint_id and ad.address_id = dp.deliveryaddress_id),
             (select adr.zipcode from address adr where adr.address_id = k.visitaddress_id)) ZipCode
  , coalesce((select ad.city from deliverypoint dp, address ad where dp.deliverypoint_id = e.deliverypoint_id and ad.address_id = dp.deliveryaddress_id),
             (select adr.city from address adr where adr.address_id = k.visitaddress_id)) City
FROM ROUTECONTROL A
     left outer join TRUCK Z ON (Z.Code = A.Truckcode and z.plant_id = A.Plant_Id),
  ROUTE B
     left outer join DEPOT X ON (X.DEPOT_ID = B.DEPOT_ID)
    , PLANT D, STOP E, PACKINGNOTE F, PACKINGNOTELINE G, SIZEDEFINITION H, FINISHINGMETHOD I, PRODUCT J,
  CUSTOMER K, LANGUAGES, DISTRIBUTIONPOINT L, department dep
  , PLANTDEPARTMENT PL, status st
WHERE A.ROUTE_ID = B.ROUTE_ID AND
  A.PLANT_ID = D.PLANT_ID AND
  A.ROUTECONTROL_ID = E.ROUTECONTROL_ID AND
  E.STOP_ID = F.STOP_ID AND
  F.PACKINGNOTE_ID = G.PACKINGNOTE_ID AND
  G.SIZEDEFINITION_ID = H.SIZEDEFINITION_ID AND
  G.FINISHINGMETHOD_ID = I.FINISHINGMETHOD_ID AND
  G.PRODUCT_ID = J.PRODUCT_ID AND
  E.CUSTOMER_LINK_ID = K.CUSTOMER_ID AND
  F.DISTRIBUTIONPOINT_ID = L.DISTRIBUTIONPOINT_ID and
  (e.status = 0 or e.status = 3)--TNE order500713
  and l.department_id = dep.department_id -- TNE todo4042
 and PL.PLANTDEPARTMENT_ID=f.plantdepartment_id
 and f.status_id = st.status_id
 and st.code <> '40'

/
create or replace view V_ROUTESTOPPUTUPLIST_DFD
 (ROUTECONTROL_ID, PLANTCODE, ROUTENUMBER, ROUTEDESCRIPTION, DEPOTDESCRIPTION, DRIVERNAME, DRIVINGDATE, LOADINGDOCK, STARTTIME, TRUCKCODE, TRUCKDESCRIPTION, STOPNUMBER, CUSTOMERNUMBER, SEARCHNAME, LEGALNAME, CUSTOMERNAME, PRODUCTCODE, PRODUCTDESCRIPTION, PUTUPREPORTROUTESTOP, SIZECODE, FINISHINGMETHODCODE, TOBEDELIVEREDAMOUNT, SIZEDESCRIPTION, DISTRIBUTIONPOINTNUMBER, REMARKONPACKINGNOTE, PACKREMARKENDDATE, LANGUAGECODE, DEPARTMENTNUMBER, PACKDEP_CODE, PACKDEP_DESC, REMARKFORPACKINGINSTRUCTIONS
, LOCATIONCPL)
as SELECT A.ROUTECONTROL_ID,
  D.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, X.DESCRIPTION DEPOTDESCRIPTION, --Y.NAME DRIVERNAME,
  (SELECT EMP.NAME FROM EMPLOYEE EMP WHERE EMP.EMPLOYEENUMBER = A.DRIVERNUMBER AND EMP.PLANT_ID = A.PLANT_ID) DRIVERNAME,
  A.DRIVINGDATE, A.LOADINGDOCK, A.PACKINGDEADLINE STARTTIME, Z.CODE TRUCKCODE, Z.DESCRIPTION TRUCKDESCRIPTION,
  E.STOPNUMBER, K.CUSTOMERNUMBER, K.SEARCHNAME, K.LEGALNAME, K.NAME CUSTOMERNAME,
  J.CODE PRODUCTCODE,
  (SELECT DESCRIPTION FROM PRODUCT_DESC W WHERE J.PRODUCT_ID = W.PRODUCT_ID AND W.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
  B.PUTUPREPORTROUTESTOP,
  H.CODE SIZECODE, I.CODE FINISHINGMETHODCODE, G.TOBEDELIVEREDAMOUNT,
  (SELECT DESCRIPTION FROM SIZEDEFINITION_DESC SW WHERE H.SIZEDEFINITION_ID = SW.SIZEDEFINITION_ID AND SW.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDESCRIPTION,
  L.DISTRIBUTIONPOINTNUMBER, L.REMARKONPACKINGNOTE, L.PACKREMARKENDDATE,
  LANGUAGES.CODE LANGUAGECODE, DEP.DEPARTMENTNUMBER
  , PL.CODE PACKDEP_CODE, PL.DESCRIPTION PACKDEP_DESC--501742
  , G.REMARKFORPACKINGINSTRUCTIONS
  , (select min(sdl.location) from standarddelivery sd, standarddeliveryline sdl,productlistperdistribpoint plpd
                              where sd.standarddelivery_id=sdl.standarddelivery_id
                              and f.distributionpoint_id=sd.distributionpoint_id
                              and sdl.productlistperdistribpoint_id=plpd.productlistperdistribpoint_id
                              and plpd.product_id=g.product_id
                              and plpd.sizedefinition_id=h.sizedefinition_id
                              and plpd.finishingmethod_id=i.finishingmethod_id
                              and sdl.dateactive<=a.drivingdate and sdl.dateinactive>=a.drivingdate) LocationCPL
FROM ROUTECONTROL A
     LEFT OUTER JOIN TRUCK Z ON (Z.CODE = A.TRUCKCODE AND Z.PLANT_ID = A.PLANT_ID),
  ROUTE B
     LEFT OUTER JOIN DEPOT X ON (X.DEPOT_ID = B.DEPOT_ID)
    --LEFT OUTER JOIN EMPLOYEE Y ON (Y.EMPLOYEE_ID = B.DRIVER_ID)
    --LEFT OUTER JOIN TRUCK Z ON (Z.TRUCK_ID = B.TRUCK_ID)
    , PLANT D, STOP E, PACKINGNOTE F, PACKINGNOTELINE G, SIZEDEFINITION H, FINISHINGMETHOD I, PRODUCT J,
  CUSTOMER K, LANGUAGES, DISTRIBUTIONPOINT L, DEPARTMENT DEP
  , PLANTDEPARTMENT PL, STATUS ST
WHERE A.ROUTE_ID = B.ROUTE_ID AND
  A.PLANT_ID = D.PLANT_ID AND
  A.ROUTECONTROL_ID = E.ROUTECONTROL_ID AND
  E.STOP_ID = F.STOP_ID AND
  F.PACKINGNOTE_ID = G.PACKINGNOTE_ID AND
  G.SIZEDEFINITION_ID = H.SIZEDEFINITION_ID AND
  G.FINISHINGMETHOD_ID = I.FINISHINGMETHOD_ID AND
  G.PRODUCT_ID = J.PRODUCT_ID AND
  E.CUSTOMER_LINK_ID = K.CUSTOMER_ID AND
  F.DISTRIBUTIONPOINT_ID = L.DISTRIBUTIONPOINT_ID AND
  (E.STATUS = 0 OR E.STATUS = 3)--TNE ORDER500713
  AND L.DEPARTMENT_ID = DEP.DEPARTMENT_ID -- TNE TODO4042
  AND PL.PLANTDEPARTMENT_ID=F.PLANTDEPARTMENT_ID
  AND F.STATUS_ID = ST.STATUS_ID
  AND ST.CODE <> '40'

/
create or replace view V_ROUTESTOPPUTUPLIST_ECL
 (ROUTECONTROL_ID, PLANTCODE, ROUTENUMBER, ROUTEDESCRIPTION, DEPOTDESCRIPTION, DRIVERNAME, DRIVINGDATE, LOADINGDOCK, STARTTIME, TRUCKCODE, TRUCKDESCRIPTION, STOPNUMBER, CUSTOMERNUMBER, SEARCHNAME, LEGALNAME, CUSTOMERNAME, PRODUCTCODE, PRODUCTDESCRIPTION, PUTUPREPORTROUTESTOP, DISTRIBUTIONPOINTNUMBER, REMARKONPACKINGNOTE, PACKREMARKENDDATE, LANGUAGECODE, DEPARTMENTNUMBER, PLANTDEP_CODE, PACKDEP_DESC, REMARKFORPACKINGINSTRUCTIONS, REPLACEMENTQTY, REPLACEMENTLOSSQTY, NOTENUMBER
, CONSIGNMENTNOTENUMBERS, LOADSEQUENCENR, DELIVEREDAMOUNT, THEORETICALWEIGHT, TAREWEIGHT, CAGE, BAG)
as SELECT RC.ROUTECONTROL_ID,
  P.CODE PLANTCODE, R.ROUTENUMBER, R.DESCRIPTION ROUTEDESCRIPTION, X.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, Z.CODE TRUCKCODE, Z.DESCRIPTION TRUCKDESCRIPTION,
  S.STOPNUMBER, C.CUSTOMERNUMBER, C.SEARCHNAME, C.LEGALNAME, C.NAME CUSTOMERNAME,
  PR.CODE PRODUCTCODE,
  (SELECT DESCRIPTION FROM PRODUCT_DESC PD WHERE PR.PRODUCT_ID = PD.PRODUCT_ID AND PD.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
  R.PUTUPREPORTROUTESTOP,
 DP.DISTRIBUTIONPOINTNUMBER, DP.REMARKONPACKINGNOTE, DP.PACKREMARKENDDATE,
  LANGUAGES.CODE LANGUAGECODE, DEP.DEPARTMENTNUMBER
  , PL.CODE PLANTDEP_CODE, PL.DESCRIPTION PACKDEP_DESC
  , PNL.REMARKFORPACKINGINSTRUCTIONS
	, PNL.REPLACEMENTQTY
  , PNL.REPLACEMENTLOSSQTY
  , pn.notenumber
  , (SELECT  listagg(cn.consignmentnotenumber,', ') within group (order by cn.consignmentnotenumber)
    from consignmentnote cn, customer c
    where c.customer_id = cn.customer_link_id
    and cn.deliverydate = rc.drivingdate
    and cn.route_id = r.route_id
    and cn.stopnumber = s.stopnumber
    group by c.customernumber) consignmentnotenumbers,
  (SELECT  listagg(pn2.loadsequencenr,', ') within group (order by pn2.loadsequencenr)
    from packingnote pn2
    where pn2.plantdepartment_id = pl.plantdepartment_id
    and pn2.distributionpoint_id = dp.distributionpoint_id
    and pn2.status_id = ST.STATUS_ID
    and S.STOP_ID = PN2.STOP_ID
    and pn2.origin <>3
    and pn.straightevenreturn='N'
    AND ST.CODE <> '40'
    group by pl.plantdepartment_id) loadsequencenr,
     PNL.DELIVEREDAMOUNT,
     pr.theoreticalweight,
     (select sum(pnc.tareweight) from packingnotecontainer pnc, packingnote pn3
     where pn3.packingnote_id = pnc.packingnote_id
     and  pn3.plantdepartment_id = pl.plantdepartment_id
    and pn3.distributionpoint_id = dp.distributionpoint_id
    and pn3.status_id = ST.STATUS_ID
    and pn3.origin <>3
    and pn3.straightevenreturn='N'
    and S.STOP_ID = PN3.STOP_ID
    AND ST.CODE <> '40') tareweight,
    (select sum(pn.numberofcolli) from packingnote pn4, transportarticle_desc tad
    where pn4.transportarticle_id = tad.transportarticle_id
    and pn4.plantdepartment_id = pl.plantdepartment_id
    and pn4.distributionpoint_id = dp.distributionpoint_id
    and pn4.status_id = ST.STATUS_ID
    and S.STOP_ID = PN4.STOP_ID
    and pn4.origin <>3
    and pn4.straightevenreturn='N'
    AND ST.CODE <> '40'
    and tad.language_id = LANGUAGES.LANGUAGE_ID
    and lower(tad.description) like '%cage%') cage,
    (select sum(pn.numberofcolli) from packingnote pn4, transportarticle_desc tad
    where pn4.transportarticle_id = tad.transportarticle_id
    and pn4.plantdepartment_id = pl.plantdepartment_id
    and pn4.distributionpoint_id = dp.distributionpoint_id
    and pn4.status_id = ST.STATUS_ID
    and S.STOP_ID = PN4.STOP_ID
    AND ST.CODE <> '40'
    and pn4.origin <>3
    and pn4.straightevenreturn='N'
    and tad.language_id = LANGUAGES.LANGUAGE_ID
    and lower(tad.description) like '%bag%') bag
FROM ROUTECONTROL RC
LEFT OUTER JOIN TRUCK Z ON (Z.CODE = RC.TRUCKCODE AND Z.PLANT_ID = RC.PLANT_ID),
ROUTE R
LEFT OUTER JOIN DEPOT X ON (X.DEPOT_ID =  R.DEPOT_ID),
PLANT P, STOP S, PACKINGNOTE PN, PACKINGNOTELINE PNL,  PRODUCT PR,
CUSTOMER C, LANGUAGES, DISTRIBUTIONPOINT DP, DEPARTMENT DEP, PLANTDEPARTMENT PL, STATUS ST
WHERE RC.ROUTE_ID =  R.ROUTE_ID AND
  RC.PLANT_ID = P.PLANT_ID AND
  RC.ROUTECONTROL_ID = S.ROUTECONTROL_ID AND
  S.STOP_ID = PN.STOP_ID AND
  PN.PACKINGNOTE_ID = PNL.PACKINGNOTE_ID AND
  PNL.PRODUCT_ID = PR.PRODUCT_ID AND
  S.CUSTOMER_LINK_ID = C.CUSTOMER_ID AND
  PN.DISTRIBUTIONPOINT_ID = DP.DISTRIBUTIONPOINT_ID AND
  (S.STATUS = 0 OR S.STATUS = 3)
  AND DP.DEPARTMENT_ID = DEP.DEPARTMENT_ID
  AND PL.PLANTDEPARTMENT_ID=PN.PLANTDEPARTMENT_ID
  AND PN.STATUS_ID = ST.STATUS_ID
  AND ST.CODE <> '40'
  and pn.origin <> 3
  and pn.straightevenreturn='N'
  and c.bulkpacking='N'

/
create or replace view V_ROUTESTOPPUTUPLIST_LST
 (ROUTECONTROL_ID, PLANTCODE, ROUTENUMBER, ROUTEDESCRIPTION, DEPOTDESCRIPTION, DRIVERNAME, DRIVINGDATE, LOADINGDOCK, STARTTIME, TRUCKCODE, TRUCKDESCRIPTION, STOPNUMBER, CUSTOMERNUMBER, SEARCHNAME, LEGALNAME, CUSTOMERNAME, PRODUCTCODE, PRODUCTDESCRIPTION, PUTUPREPORTROUTESTOP, SIZECODE, FINISHINGMETHODCODE, TOBEDELIVEREDAMOUNT, SIZEDESCRIPTION, DISTRIBUTIONPOINTNUMBER, REMARKONPACKINGNOTE, PACKREMARKENDDATE, LANGUAGECODE, DEPARTMENTNUMBER, PACKDEP_CODE, PACKDEP_DESC, DELIVERYSCHEMECODE
)
as SELECT A.ROUTECONTROL_ID,
  D.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, X.DESCRIPTION DEPOTDESCRIPTION,
  (select EMP.NAME from EMPLOYEE EMP where EMP.Employeenumber = A.Drivernumber and EMP.Plant_Id = A.Plant_Id) DRIVERNAME,
  A.DRIVINGDATE, A.LOADINGDOCK, A.PACKINGDEADLINE STARTTIME, Z.CODE TRUCKCODE, Z.DESCRIPTION TRUCKDESCRIPTION,
  E.STOPNUMBER, K.CUSTOMERNUMBER, K.SEARCHNAME, K.LEGALNAME, K.Name Customername,
  J.CODE PRODUCTCODE,
  (SELECT description FROM PRODUCT_DESC W WHERE J.PRODUCT_ID = W.PRODUCT_ID AND W.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
  B.PUTUPREPORTROUTESTOP,
  H.CODE SIZECODE, I.CODE FINISHINGMETHODCODE,
  --G.TOBEDELIVEREDAMOUNT,
--  PNLDS.TOBEDELIVEREDQTY TOBEDELIVEREDAMOUNT,
  case
    when PNLDS.TOBEDELIVEREDQTY is null then G.TOBEDELIVEREDAMOUNT
    else PNLDS.TOBEDELIVEREDQTY
  end TOBEDELIVEREDAMOUNT,
  (SELECT description FROM SIZEDEFINITION_DESC SW WHERE H.SIZEDEFINITION_ID = SW.SIZEDEFINITION_ID AND SW.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDESCRIPTION,
  L.DISTRIBUTIONPOINTNUMBER, L.REMARKONPACKINGNOTE, L.PACKREMARKENDDATE,
  LANGUAGES.CODE LANGUAGECODE, dep.departmentnumber,
  PL.Code PackDep_code, PL.Description PackDep_desc,
  DS.code DELIVERYSCHEMECODE
FROM ROUTECONTROL A
     left outer join TRUCK Z ON (Z.Code = A.Truckcode and z.plant_id = A.Plant_Id),
  ROUTE B
     left outer join DEPOT X ON (X.DEPOT_ID = B.DEPOT_ID),
  PACKINGNOTELINEPERDELSCHEME PNLDS, DELIVERYSCHEME DS,
  PLANT D, STOP E, PACKINGNOTE F, PACKINGNOTELINE G, SIZEDEFINITION H, FINISHINGMETHOD I, PRODUCT J,
  CUSTOMER K, LANGUAGES, DISTRIBUTIONPOINT L, department dep,
  PLANTDEPARTMENT PL, status st
WHERE A.ROUTE_ID = B.ROUTE_ID AND
  A.PLANT_ID = D.PLANT_ID AND
  A.ROUTECONTROL_ID = E.ROUTECONTROL_ID AND
  E.STOP_ID = F.STOP_ID AND
  F.PACKINGNOTE_ID = G.PACKINGNOTE_ID AND
  G.SIZEDEFINITION_ID = H.SIZEDEFINITION_ID AND
  G.FINISHINGMETHOD_ID = I.FINISHINGMETHOD_ID AND
  G.PRODUCT_ID = J.PRODUCT_ID AND
  E.CUSTOMER_LINK_ID = K.CUSTOMER_ID AND
  F.DISTRIBUTIONPOINT_ID = L.DISTRIBUTIONPOINT_ID and
  (e.status = 0 or e.status = 3) and
  l.department_id = dep.department_id and
  PL.PLANTDEPARTMENT_ID=f.plantdepartment_id and
  PNLDS.PACKINGNOTELINE_ID = G.PACKINGNOTELINE_ID AND
  DS.DELIVERYSCHEME_ID = PNLDS.DELIVERYSCHEME_ID
  and f.status_id = st.status_id and
  st.code <> '40'
UNION ALL -- Non-straight even exchange items
SELECT A.ROUTECONTROL_ID,
  D.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, X.DESCRIPTION DEPOTDESCRIPTION,
  (select EMP.NAME from EMPLOYEE EMP where EMP.Employeenumber = A.Drivernumber and EMP.Plant_Id = A.Plant_Id) DRIVERNAME,
  A.DRIVINGDATE, A.LOADINGDOCK, A.PACKINGDEADLINE STARTTIME, Z.CODE TRUCKCODE, Z.DESCRIPTION TRUCKDESCRIPTION,
  E.STOPNUMBER, K.CUSTOMERNUMBER, K.SEARCHNAME, K.LEGALNAME, K.Name Customername,
  J.CODE PRODUCTCODE,
  (SELECT description FROM PRODUCT_DESC W WHERE J.PRODUCT_ID = W.PRODUCT_ID AND W.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
  B.PUTUPREPORTROUTESTOP,
  H.CODE SIZECODE, I.CODE FINISHINGMETHODCODE,
  --G.TOBEDELIVEREDAMOUNT,
  --PNLDSN.TOBEDELIVEREDQTY TOBEDELIVEREDAMOUNT,
  case
    when PNLDSN.TOBEDELIVEREDQTY is null then G.TOBEDELIVEREDAMOUNT
    else PNLDSN.TOBEDELIVEREDQTY
  end TOBEDELIVEREDAMOUNT,
  (SELECT description FROM SIZEDEFINITION_DESC SW WHERE H.SIZEDEFINITION_ID = SW.SIZEDEFINITION_ID AND SW.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDESCRIPTION,
  L.DISTRIBUTIONPOINTNUMBER, L.REMARKONPACKINGNOTE, L.PACKREMARKENDDATE,
  LANGUAGES.CODE LANGUAGECODE, dep.departmentnumber,
  PL.Code PackDep_code, PL.Description PackDep_desc,
  -- 20070405 RVI, BEGIN
  (CASE WHEN PNLDSN.packingnoteline_id IS NULL THEN
           F_GETDELIVERYSCHEME(F.distributionpoint_id, F.deliverydate, G.product_id, G.sizedefinition_id, G.finishingmethod_id)
        ELSE DS.code
   END) DELIVERYSCHEMECODE
FROM ROUTECONTROL A
     left outer join TRUCK Z ON (Z.Code = A.Truckcode and z.plant_id = A.Plant_Id),
  ROUTE B
     left outer join DEPOT X ON (X.DEPOT_ID = B.DEPOT_ID),
  PLANT D, STOP E, PACKINGNOTE F,
  PACKINGNOTELINE G
    left outer join (PNLINEPERDELSCHEMENONSEE PNLDSN
      left outer join DELIVERYSCHEME DS ON PNLDSN.DELIVERYSCHEME_ID = DS.DELIVERYSCHEME_ID)
        ON G.PACKINGNOTELINE_ID = PNLDSN.PACKINGNOTELINE_ID,
  SIZEDEFINITION H, FINISHINGMETHOD I, PRODUCT J,
  CUSTOMER K, LANGUAGES, DISTRIBUTIONPOINT L, department dep, PLANTDEPARTMENT PL, status st
WHERE A.ROUTE_ID = B.ROUTE_ID AND
  A.PLANT_ID = D.PLANT_ID AND
  A.ROUTECONTROL_ID = E.ROUTECONTROL_ID AND
  E.STOP_ID = F.STOP_ID AND
  F.PACKINGNOTE_ID = G.PACKINGNOTE_ID AND
  G.SIZEDEFINITION_ID = H.SIZEDEFINITION_ID AND
  G.FINISHINGMETHOD_ID = I.FINISHINGMETHOD_ID AND
  G.PRODUCT_ID = J.PRODUCT_ID AND
  E.CUSTOMER_LINK_ID = K.CUSTOMER_ID AND
  F.DISTRIBUTIONPOINT_ID = L.DISTRIBUTIONPOINT_ID and
  (e.status = 0 or e.status = 3)
  AND l.department_id = dep.department_id
  and PL.PLANTDEPARTMENT_ID=f.plantdepartment_id
  AND NOT EXISTS (SELECT 1
                  FROM PACKINGNOTELINEPERDELSCHEME PNLDS
                  WHERE PNLDS.PACKINGNOTELINE_ID = G.PACKINGNOTELINE_ID)
  and f.status_id = st.status_id
  and st.code <> '40'

/
create or replace view V_ROUTESTOPPUTUPLIST_POS
 (ROUTECONTROL_ID, PLANTCODE, ROUTENUMBER, ROUTEDESCRIPTION, DEPOTDESCRIPTION, DRIVERNAME, DRIVINGDATE, LOADINGDOCK, STARTTIME, TRUCKCODE, TRUCKDESCRIPTION, STOPNUMBER, CUSTOMERNUMBER, SEARCHNAME, LEGALNAME, CUSTOMERNAME, PRODUCTCODE, PRODUCTDESCRIPTION, PUTUPREPORTROUTESTOP, SIZECODE, FINISHINGMETHODCODE, TOBEDELIVEREDAMOUNT, SIZEDESCRIPTION, DISTRIBUTIONPOINTNUMBER, REMARKONPACKINGNOTE, PACKREMARKENDDATE, LANGUAGECODE, DEPARTMENTNUMBER, PACKDEP_CODE, PACKDEP_DESC, PLPCCUSTOMDESC
, ROUTEDAYNUMBER)
as SELECT A.ROUTECONTROL_ID,
  D.CODE PLANTCODE, B.ROUTENUMBER, B.DESCRIPTION ROUTEDESCRIPTION, X.DESCRIPTION DEPOTDESCRIPTION, --Y.NAME DRIVERNAME,
  (select EMP.NAME from EMPLOYEE EMP where EMP.Employeenumber = A.Drivernumber and EMP.Plant_Id = A.Plant_Id) DRIVERNAME,
  A.DRIVINGDATE, A.LOADINGDOCK, A.PACKINGDEADLINE STARTTIME, Z.CODE TRUCKCODE, Z.DESCRIPTION TRUCKDESCRIPTION,
  E.STOPNUMBER, K.CUSTOMERNUMBER, K.SEARCHNAME, K.LEGALNAME, K.Name Customername,
  J.CODE PRODUCTCODE,
  (SELECT description FROM PRODUCT_DESC W WHERE J.PRODUCT_ID = W.PRODUCT_ID AND W.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
  B.PUTUPREPORTROUTESTOP,
  H.CODE SIZECODE, I.CODE FINISHINGMETHODCODE, G.TOBEDELIVEREDAMOUNT,
  (SELECT description FROM SIZEDEFINITION_DESC SW WHERE H.SIZEDEFINITION_ID = SW.SIZEDEFINITION_ID AND SW.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) SIZEDESCRIPTION,
  L.DISTRIBUTIONPOINTNUMBER, L.REMARKONPACKINGNOTE, L.PACKREMARKENDDATE,
  LANGUAGES.CODE LANGUAGECODE, dep.departmentnumber
  , PL.Code PackDep_code, PL.Description PackDep_desc--501742
, (select Plpc.Customdescription from Productlistpercustomer Plpc where plpc.customer_id = k.customer_id and plpc.product_id = g.product_id and plpc.sizedefinition_id = g.sizedefinition_id and plpc.finishingmethod_id = g.finishingmethod_id and plpc.dateactive <= a.drivingdate and plpc.dateinactive > a.drivingdate ) PlpcCustomDesc
, (select dy.daynumber from day Dy where b.drivingday_id = dy.day_id) RouteDayNumber
FROM ROUTECONTROL A
     left outer join TRUCK Z ON (Z.Code = A.Truckcode and z.plant_id = A.Plant_Id),
  ROUTE B
     left outer join DEPOT X ON (X.DEPOT_ID = B.DEPOT_ID)
    --left outer join EMPLOYEE Y ON (Y.EMPLOYEE_ID = B.DRIVER_ID)
    --left outer join TRUCK Z ON (Z.TRUCK_ID = B.TRUCK_ID)
    , PLANT D, STOP E, PACKINGNOTE F, PACKINGNOTELINE G
    , SIZEDEFINITION H, FINISHINGMETHOD I, PRODUCT J
    --left outer join Productgroup PG
         left outer join Packingdepartmentdefinition Pdd
              left outer join PLANTDEPARTMENT PL on pdd.plantdepartment_id = pl.plantdepartment_id
         on Pdd.Productgroup_Id = j.productgroup_id
    --on J.Productgroup_Id = PG.Productgroup_Id
  , CUSTOMER K, LANGUAGES, DISTRIBUTIONPOINT L, department dep
  --, PLANTDEPARTMENT PL
  , businessunit ProcBu, status st
WHERE A.ROUTE_ID = B.ROUTE_ID AND
  A.PLANT_ID = D.PLANT_ID AND
  A.ROUTECONTROL_ID = E.ROUTECONTROL_ID AND
  E.STOP_ID = F.STOP_ID AND
  F.PACKINGNOTE_ID = G.PACKINGNOTE_ID AND
  G.SIZEDEFINITION_ID = H.SIZEDEFINITION_ID AND
  G.FINISHINGMETHOD_ID = I.FINISHINGMETHOD_ID AND
  G.PRODUCT_ID = J.PRODUCT_ID AND
  E.CUSTOMER_LINK_ID = K.CUSTOMER_ID AND
  F.DISTRIBUTIONPOINT_ID = L.DISTRIBUTIONPOINT_ID and
  (e.status = 0 or e.status = 3)--TNE order500713
  and l.department_id = dep.department_id -- TNE todo4042
 --and PL.PLANTDEPARTMENT_ID=f.plantdepartment_id
 and ProcBu.Businessunit_Id = F.Processbusinessunit_Id
 and coalesce(pl.plant_id, ProcBu.Plant_Id) = ProcBu.Plant_Id
 and f.status_id = st.status_id
 and st.code <> '40'

/
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 >= GETCURRENTDATE()
   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 <= GETCURRENTDATE()
   and rst.dateinactive>= GETCURRENTDATE()
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 >= GETCURRENTDATE()
   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 <= GETCURRENTDATE()
   and rst.dateinactive>= GETCURRENTDATE()

/
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 >= GETCURRENTDATE()
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 <= GetCurrentDate()
and rst.dateinactive > GetCurrentDate()

/
create or replace view V_ROUTE_DELIVERY_CUSTOMER_URZ
 (PLANTCODE, PLANTNAME, BUSINESSUNITCODE, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMER_ID, DEPOTCODE, STREET, STREET2, CITY, DAYNUMBER, ZIPCODE, DELIVERYSCHEMECODE, ROUTENUMBER, DAYCODE, 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 CONCATENATEWITHBLANK(addressDlv.Street, addressDlv.Street2)
            when ' ' 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, route.routenumber
, (select day_desc.code from day_desc where day_desc.day_id = day.day_id
  and day_desc.language_id = languages.language_id) DayCode
, rst.stopnumber, deliverypoint.code deliverypointCode, emp.name Driver
--, buusg.usergroup_id UsergroupID, 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  --- observation: useful line are 'doubled' by UsergroupID
  customer cu
           --left outer join customercluster on customercluster.cluster_id = cu.cluster_id
--, businessunit bu
, plant, deliveryschemesperstop dskt
--, businessunitsperusergroup buusg
, 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
, 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 >= GETCURRENTDATE() --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 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 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')
    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)))

/
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 >= GETCURRENTDATE()
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 >= GETCURRENTDATE()
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_ROWCOUNT
 (COUNTER)
as select rownum counter
from user_tables

/
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, 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)
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, --cast(
wk.remark --as varchar2(60)) remark
, wkCredit.Workordernumber CreditWorkordernumber
, prdlk.code productCode, szlk.code sizecode, fm.code finishingcode, qg.code qualitygradeCode, qg.priority
, ( 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
, ( 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,
(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 = languages.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 = languages.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 = languages.language_id) DeliveryTermDescr,
(select e.employeenumber from employee e, systemuser su where e.employee_id = su.employee_id and su.systemuser_id = wk.approvaluser_id) EmployeeNumber,
(select e.name from employee e, systemuser su where e.employee_id = su.employee_id and su.systemuser_id = wk.approvaluser_id) 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
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_link prdlk, sizedefinition_link szlk, finishingmethod fm, qualitygrade qg
, address, languages
, businessunit bu
, 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 = prdlk.product_link_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
and bu.businessunit_id = wk.businessunit_id
and languages.language_id = cu.language_id

/
create or replace view V_SALESCREDITNOTETRADE_ELI
 (CUSTOMERNUMBER, CUSTOMERNAME, STREET, ZIPCODE, CITY, WORKORDER_ID, ORIGIN, WORKORDERNUMBER, REFERENCENUMBER, ORDERDATE, NEEDEDDATE, ENTRYDATE, EXPECTEDDATE, ROUTENUMBER, ROUTE_DESC, DAY_DESC, REMARK, CREDITWORKORDERNUMBER, PRODUCTCODE, SIZECODE, FINISHINGCODE, QUALITYGRADECODE, PRIORITY, PRODUCTDESC, QTYSALES, QUANTITYTOBECREDITED, INSTRUCTIONS, LANGUAGECODE, PRINT_BARCODE, 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_STREET2, 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, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTWEBSITE, PLANTEMAIL, CONTRACT_PONUMBERS, SERVICEEMP_NR, SERVICEEMP_NAME, DEBTORSTREET, DEBTORSTREET2, DEBTORZIPCODE, DEBTORCITY, DEBTORVATNUMBER, DELTOVATNUMBER
, VATNUMBER, LNDRY_BANK_IBANNO, LNDRY_BANK_LNDRYBANKACCOUNT, PAYMENTTERMS)
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, wk.entrydate, wkli.expecteddate
, 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, --cast(
wk.remark --as varchar2(60)) remark
, wkCredit.Workordernumber CreditWorkordernumber
, prdlk.code productCode, szlk.code sizecode, fm.code finishingcode, qg.code qualitygradeCode, qg.priority
, ( 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
, ( 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
, 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.street2 deliverypoint_street2, 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,
cu_debtor.customernumber DebtorNumber,
cu_debtor.name 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 = languages.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 = languages.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 = languages.language_id) DeliveryTermDescr,
(select e.employeenumber from employee e, systemuser su where e.employee_id = su.employee_id and su.systemuser_id = wk.approvaluser_id) EmployeeNumber,
(select e.name from employee e, systemuser su where e.employee_id = su.employee_id and su.systemuser_id = wk.approvaluser_id) 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,
       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
, (select LISTAGG(contractspercustomer.purchaseorder, ', ') within group (order by contractspercustomer.purchaseorder)
 from contractspercustomer Where contractspercustomer.customer_id = cu.Customer_Id) Contract_POnumbers,
(select se.employeenumber from employee se where se.employee_id = cu.serviceemployee_id) ServiceEmp_NR,
(select se.name from employee se where se.employee_id = cu.serviceemployee_id) ServiceEmp_Name,
debad.street Debtorstreet, debad.street2 Debtorstreet2, debad.zipcode Debtorzipcode, debad.city Debtorcity,
cu_debtor.vatnumber Debtorvatnumber, cu.vatnumber Deltovatnumber, bu.vatnumber,
( select lbank.ibanno from bankinstitution Lbank where Lbank.bankinstitution_id = bu.defaultbankinstitution_id) lndry_bank_ibanno,
( select lbank.laundrybankaccount from bankinstitution Lbank where Lbank.bankinstitution_id = bu.defaultbankinstitution_id) lndry_bank_lndrybankaccount
, (select ptd.description from paymentterms_desc ptd, customerbillinginfo cbi where cbi.customer_id = cu.customer_id
         and cbi.paymentterms_id = ptd.paymentterms_id and ptd.language_id = p.language_id ) PaymentTerms
from
  workorder wk
  inner join workorderline wkli on wk.workorder_id = wkli.workorder_id
 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=coalesce(wk.salesemployee1_id, wkli.salesemployee1_id)
 left outer join employee sales2_emp on sales2_emp.employee_id=coalesce(wk.salesemployee2_id, wkli.salesemployee2_id)
 left outer join woreferencenumber worefnr on wk.woreferencenumber_id = worefnr.woreferencenumber_id
 left outer join customer cu_debtor
      inner join address debad on debad.address_id = cu_debtor.invoiceaddress_id
 on cu_debtor.customer_id = wk.debtor_id
, customer cu
, product_link prdlk, sizedefinition_link szlk, finishingmethod fm, qualitygrade qg
, address, languages, businessunit bu, plant p, address x
, 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 wkli.product_link_id = prdlk.product_link_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
and bu.businessunit_id = wk.businessunit_id
and bu.plant_id = p.plant_id
and p.address_id = x.address_id
and languages.language_id = cu.language_id

/
create or replace view V_SALESCREDITNOTETRADE_NAF
 (CUSTOMERNUMBER, CUSTOMERNAME, LEGALNAME, EXTRANAME1, EXTRANAME2, STREET, STREET2, ZIPCODE, CITY, COUNTRY_CODE, COUNTRY_DESC, WORKORDER_ID, ORIGIN, WORKORDERNUMBER, REFERENCENUMBER, ORDERDATE, NEEDEDDATE, ROUTENUMBER, ROUTE_DESC, DAY_DESC, REMARK, CREDITWORKORDERNUMBER, PRODUCTCODE, SIZECODE, FINISHINGCODE, QUALITYGRADECODE, PRIORITY, PRODUCTDESC, PRODUCTLONGDESC, COLORDESC, QTYSALES, QUANTITYTOBECREDITED, INSTRUCTIONS, LANGUAGECODE, PRINT_BARCODE, 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, DEBTORLEGALNAME, DEBTOREXTRANAME1, DEBTOREXTRANAME2, DEBTORSTREET, DEBTORSTREET2, DEBTORZIPCODE, DEBTORCITY, DEBTORCOUNTRY_CODE, DEBTORCOUNTRY_DESC, CONTACTPERSONNUMBER, CONTACTPERSON, COMMMETHODCODE, COMMMETHODDESCR, SHIPMENTTYPECODE, SHIPMENTTYPEDESCR, DELIVERYTERMCODE, DELIVERYTERMDESCR, APPROVALEMPLOYEENUMBER, APPROVALEMPLOYEENAME, RESPEMPLOYEENUMBER, RESPEMPLOYEENAME, APPROVALTIMESTAMP, OFFER
, BLOCKEDFORINVOICING, BLOCKED, ALLOWPARTIALINVOICING, WODISCOUNTPERCENTAGE, EXTERNALREMARK, THEORETICALWEIGHT, TRANSPORTCOSTS, SALESORDERLINESTOTALAMOUNT, SALESORDERLINESTOTALNETAMOUNT, SALESORDERLINESEMBLTOTALAMT, SALESORDERLINESEMBTOTNETAMT, SALESORDERLINESTOTALDISCOUNT, SALESORDERLINESEMBTOTDISC, DELIVERYTERMUNITPRICE, VATAMOUNT, SALESORDERTOTALNETAMOUNT, SALESORDERTOTALGROSSAMOUNT, SALESORDERGODAMOUNT, MODIF_DESC1, MODIF_DESC2, MODIF_DESC3
, CURRENCY_CODE, PAYMENTTERMDESCR, SYSTEMUSERUSERNAME, SYSTEMUSERFULLNAME, TAXRATE, SIZE_SEQUENCENR, WORKORDERLINE_ID)
as select /*v_salescreditnotetrade_naf version 2.0*/
  cu.customernumber, cu.name customerName, cu.legalname, cu.extraname1, cu.extraname2
, vis.street, vis.street2, vis.zipcode, vis.city
, co.code country_code, co.description country_desc
, 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
, prdlk.code productCode, szlk.code sizecode, fm.code finishingcode, qg.code qualitygradeCode, qg.priority
, (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 product_link_desc.longdescription from product_link_desc where product_link_desc.product_link_id = prdlk.product_link_id
  and product_link_desc.language_id = languages.language_id) productLongDesc
, (select cd.description from color_desc cd, product pr where cd.color_id = pr.color_id
  and pr.product_id = prdlk.product_link_id and cd.language_id = languages.language_id) colorDesc
, (wkli.quantityordered - wkli.quantitycancelled) QtySales
, wkli.quantitytobecredited, --cast(
wkli.instructions --as varchar2(60)) 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
, 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,
deb.customernumber DebtorNumber, deb.name DebtorName, deb.legalname Debtorlegalname, cu.extraname1 Debtorextraname1, cu.extraname2 Debtorextraname2,
inv.street Debtorstreet, inv.street2 Debtorstreet2, inv.zipcode Debtorzipcode, inv.city Debtorcity
, dco.code Debtorcountry_code, dco.description Debtorcountry_desc,
(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 = languages.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 = languages.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 = languages.language_id) DeliveryTermDescr,
(select e.employeenumber from employee e, systemuser au where e.employee_id = au.employee_id and au.systemuser_id = wk.approvaluser_id) approvalEmployeeNumber,
(select e.name from employee e, systemuser au where e.employee_id = au.employee_id and au.systemuser_id = wk.approvaluser_id) approvalEmployeeName,
(select e.employeenumber from employee e where e.employee_id = wk.resplaundryemployee_id) RespEmployeeNumber,
(select e.name from employee e where e.employee_id = wk.resplaundryemployee_id) RespEmployeeName,
wk.approvaltimestamp, wk.offer, wk.blockedforinvoicing, wk.blocked, wk.allowpartialinvoicing,
wk.discountpercentage WODiscountPercentage, --cast(
wk.externalremark --as varchar2(60)) externalremark
, wk.TheoreticalWeight,
coalesce(pack_trade.GetSalesOrderTransportCosts(wk.workorder_id, bu.plant_id), wk.TransportCosts) TransportCosts,
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,
pack_trade.GetDeliveryTermUnitPrice(wk.workorder_id, wk.theoreticalweight, sysdate) DeliveryTermUnitPrice,
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,
(select md.description from workorderlinemodification wlm, modification_desc md where wlm.workorderline_id = wkli.workorderline_id
 and wlm.modification_id = md.modification_id and md.language_id = languages.language_id and wlm.sequencenumber = 1) Modif_desc1,
(select md.description from workorderlinemodification wlm, modification_desc md where wlm.workorderline_id = wkli.workorderline_id
 and wlm.modification_id = md.modification_id and md.language_id = languages.language_id and wlm.sequencenumber = 2) Modif_desc2,
(select md.description from workorderlinemodification wlm, modification_desc md where wlm.workorderline_id = wkli.workorderline_id
 and wlm.modification_id = md.modification_id and md.language_id = languages.language_id and wlm.sequencenumber = 3) Modif_desc3,
(select curr.code from currency curr where cu.currency_id = curr.currency_id) currency_code,
(select ptdesc.description from paymentterms_desc ptdesc, customerbillinginfo cbi where ptdesc.paymentterms_id = cbi.paymentterms_id
 and ptdesc.language_id = languages.language_id and cbi.customer_id = cu.customer_id) paymentTermDescr,
 su.username systemuserusername, su.fullname systemuserfullname,
(select (case when (tg.startdatetaxrate <=
                    decode(wk.completiondate, to_date('31-12-2099', 'dd-mm-yyyy'), trunc(sysdate), wk.completiondate)) then
                   tg.taxrate
                  else
                   tg.oldtaxrate
                end)
         from   taxgroup tg
         where  tg.country_id = cu.country_id
         and    tg.code = '2') taxrate,
 coalesce((select ps.sequencenumber from productsize ps where ps.product_id = prdlk.product_link_id and ps.sizedefinition_id = szlk.sizedefinition_link_id), 0) size_sequencenr
 , (select min(wol.workorderline_id) from workorderline wol where wol.workorder_id = wk.workorder_id and wol.product_link_id = wkli.product_link_id) workorderline_id
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, customer deb, country co, country dco, workorderline wkli
, product_link prdlk, sizedefinition_link szlk, finishingmethod fm, qualitygrade qg
, address vis, address inv, languages, businessunit bu
, 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 = prdlk.product_link_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=vis.address_id
and wk.distributionpoint_link_id=disp.distributionpoint_id
and disp.deliverypoint_id=dp.deliverypoint_id
and bu.businessunit_id = wk.businessunit_id
and deb.customer_id = wk.debtor_id
and deb.invoiceaddress_id = inv.address_id
and cu.country_id = co.country_id
and deb.country_id = dco.country_id
and cu.language_id = languages.language_id

/
create or replace view V_SALESCREDITNOTE_CBD
 (CUSTOMERNUMBER, CUSTOMERNAME, STREET, STREET2, ZIPCODE, CITY, WORKORDER_ID, ORIGIN, WORKORDERNUMBER, REFERENCENUMBER, ORDERDATE, NEEDEDDATE, CREATIONTIMESTAMP, COMPLETIONDATE, ENTRYDATE, EXPECTEDCOMPLETEDATE, 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, DELIVERYPOINTCODE, DELIVERYPOINTDESCRIPTION, DELIVERYPOINT_STREET, DELIVERYPOINT_ZIPCODE, DELIVERYPOINT_CITY
, DAY_ID, STARTTIME, ENDTIME, BREAKSTARTTIME, BREAKENDTIME, WOREFERENCENUMBER_ID, WOREFERENCENR, WOREFNR_DESC, BUDESCRIPTION, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTPHONENO, PLANTFAXNO, REGUNIT)
as select
  cu.customernumber, cu.name customerName, adr.street
  , adr.street2
  , adr.zipcode
  , adr.city
, wk.workorder_id, wk.origin -- 6: sales, 7: credit
, wk.workordernumber, wk.referencenumber, wk.requestdate orderDate, wk.neededdate
, wk.creationtimestamp, wk.completiondate, wk.entrydate, wk.expectedcompletedate
, 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
, prdlk.code productCode, szlk.code sizecode, fm.code finishingcode, qg.code qualitygradeCode, qg.priority
, ( 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
, ( wkli.quantityordered - wkli.quantitycancelled ) QtySales
, wkli.quantitytobecredited
, wkli.instructions
, languages.code languageCode
, cast((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') as varchar2(1)) 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 deliverypointcode, dp.description deliverypointdescription
, 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, bu.description budescription,
plant.code plantcode, plant.name plantname, plant.website plantwebsite, plant.email plantemail,
plantaddress.street plantstreet, plantaddress.zipcode plantzipcode,
plantaddress.city plantcity, plantaddress.state plantstate, plant.phoneno plantphoneno, plant.faxno plantfaxno,
(select rg.code from registrationunit rg, product
         where product.product_id = prdlk.product_id and rg.registrationunit_id = product.registrationunit_id) regunit
from workorder wk
 left outer join workorder wkCredit on wkCredit.Workorder_Id = wk.creditworkorder_id
 left outer join route r on r.route_id = wk.route_id
 left outer join systemuser su  on su.systemuser_id = wk.creationuser_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 worefnr.woreferencenumber_id = wk.woreferencenumber_id
, customer cu
      left outer join employee emp on cu.serviceemployee_id = emp.employee_id
, workorderline wkli
, product_link prdlk, sizedefinition_link szlk, finishingmethod fm, qualitygrade qg
, address, languages
, distributionpoint disp, deliverypoint dp, address  adr
, businessunit bu, plant, address plantaddress
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 = prdlk.product_link_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
and dp.deliveryaddress_id = adr.address_id
and wk.businessunit_id = bu.businessunit_id
and bu.plant_id = plant.plant_id
and plant.address_id = plantaddress.address_id

/
create or replace view V_SALESCREDITNOTE_HOW
 (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
, prdlk.code productCode, szlk.code sizecode, fm.code finishingcode, qg.code qualitygradeCode, qg.priority
, ( 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
, ( 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
, delp.code, delp.description
, a.street deliverypoint_street, a.zipcode deliverypoint_zipcode, a.city deliverypoint_city
, getabsdaynumber(wk.neededdate) day_id,
( select dpoh.starttime from deliverypointopeninghour dpoh  where delp.deliverypoint_id=dpoh.deliverypoint_id
   and dpoh.day_id = getabsdaynumber(wk.neededdate))starttime,
( select dpoh.endtime from deliverypointopeninghour dpoh  where delp.deliverypoint_id=dpoh.deliverypoint_id
   and dpoh.day_id = getabsdaynumber(wk.neededdate))endtime,
delp.breakstarttime, delp.breakendtime,
-1 --wk.
woreferencenumber_id,--worefnr.referencenumber
-1 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
    left outer join distributionpoint distrp on distrp.distributionpoint_id=wk.distributionpoint_link_id --todo HOW07.01.09
    left outer join deliverypoint delp on delp.deliverypoint_id=distrp.deliverypoint_id --todo HOW07.01.09
    left outer join address a on a.address_id=delp.deliveryaddress_id --todo HOW07.01.09
, customer cu, workorderline wkli
, product_link prdlk, sizedefinition_link szlk, finishingmethod fm, qualitygrade qg
, address, languages
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 = prdlk.product_link_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 --changed by HOW 16.05.2012
and cu.mailaddress_id=address.address_id

/
create or replace view V_SALESCREDITNOTE_SMG
 (CUSTOMERNUMBER, CUSTNR, CUSTOMERNAME, WORKORDER_ID, ORIGIN, WORKORDERNUMBER, REFERENCENUMBER, ORDERDATE, NEEDEDDATE, ROUTENUMBER, ROUTE_DESC, DAY_DESC, REMARK, CREDITWORKORDERNUMBER, PRODUCTGROUPCODE, PRODUCTCODE, SIZECODE, FINISHINGCODE, QUALITYGRADECODE, PRIORITY, PRODUCTDESC, QTYSALES, QTYFILLED, QUANTITYTOBECREDITED, QUANTITYRETURNED, INSTRUCTIONS, LANGUAGECODE, BUDESCRIPTION, PRINT_BARCODE, EMPLOYEENUMBER1, EMPLOYEENAME1, EMPLOYEENUMBER2, EMPLOYEENAME2, SALESPRICE, DISCOUNTPERCENTAGE
, CODE, DESCRIPTION, DELIVERYPOINT_STREET, DELIVERYPOINT_ZIPCODE, DELIVERYPOINT_CITY, DAY_ID, WOREFERENCENUMBER_ID, WOREFERENCENR, WOREFNR_DESC, PLANT_CODE, PLANT_NAME, PLANT_PHONENO, PLANT_FAXNO, PLANT_EMAIL, PLANT_WEBSITE, PLANT_STREET, PLANT_STREET2, PLANT_ZIPCODE, PLANT_CITY, PLANT_STATE, PLANT_COUNTY, STOPNUMBER, DELPOINTCODE, DELPOINTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, CONSPOINTDESC, DEPARTMENTNUMBER, DEPARTMENTDESC, COSTCENTERDESCRIPTION, COSTCENTERCODE
, PONUMBER)
as select
  cu.customernumber,cast(insertspace_after_x_characters(to_char(CU.CUSTOMERNUMBER),3) as varchar2(20)) custnr,
   cu.name customerName, 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,prdlk.productgroupcode
, prdlk.code productCode, szlk.code sizecode, fm.code finishingcode, qg.code qualitygradeCode, qg.priority
, ( 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
, ( wkli.quantityordered - wkli.quantitycancelled ) QtySales
, wkli.quantityfilled qtyfilled
, wkli.quantitytobecredited, wkli.quantityreturned quantityreturned
, wkli.instructions
, languages.code languageCode
, bu.description budescription
, (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
, 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,
wk.woreferencenumber_id,
worefnr.referencenumber woreferencenr,
worefnr.description worefnr_desc
, plant.code plant_code, plant.name plant_name, plant.phoneno plant_phoneno, plant.faxno plant_faxno
, GetSubstringOnLength(plant.email,0,40) plant_email, plant.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,
wk.stopnumber,
dp.code delpointcode, dp.description delpointdescription,
disp.distributionpointnumber, disp.description conspointdesc,
(select  dep.departmentnumber from department dep where dep.department_id=disp.department_id) departmentnumber,
(select  dep.description from department dep where dep.department_id=disp.department_id) departmentdesc,
coc.description costcenterdescription, coc.code costcentercode, coc.ponumber
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 woreferencenumber worefnr on wk.woreferencenumber_id = worefnr.woreferencenumber_id
, customer cu, workorderline wkli
, product_link prdlk, 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
,businessunit bu, plant, address paddr, costcenter coc
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 = prdlk.product_link_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
and wk.businessunit_id = bu.businessunit_id
and bu.plant_id = plant.plant_id
and plant.address_id = paddr.address_id
and coc.costcenter_id=disp.costcenter_id

/
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, GETCURRENTDATE())) / 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_SCANNINGSPERCUSTOMER
 (CUSTOMER_ID, CUSTOMERNUMBER, DEBTORNUMBER, MASTERACCOUNT, MASTERACCOUNTNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESC, CITY, PHONENO, FAXNO, PRODUCTCODE, PRODUCTDESCRIPTION, TRANSACTIONTYPE, SCANDATE, SCANDATETRUNC, LANGUAGECODE, BUSINESSUNIT_ID, DEFAULTBUSINESSUNIT_ID, BU_CODE, PRIMARYID, WEARERNUMBER, WEARERNAME, PHONELEN)
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,
 (select bus.code from businessunit bus where bus.businessunit_id=scan.businessunit_id) bu_code
       , case when length(scan.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(scan.primaryid)
              else scan.primaryid
         end primaryid
       , we.wearernumber, we.wearername,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
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, businessunit bu
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 bu.businessunit_id = cu.defaultbusinessunit_id

/
create or replace view V_SCANNINGSPERCUSTOMERTOTAL
 (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
from customer cu, customer deb, customer macc, address, product prd, stay, transactiontype, languages, scan
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
group by  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_TOTAL
 (CUSTOMER_ID, CUSTOMERNUMBER, DEBTORNUMBER, MASTERACCOUNT, MASTERACCOUNTNUMBER, CUSTOMERNAME, PHONELEN, DEPARTMENTNUMBER, DEPARTMENTDESC, CITY, PHONENO, FAXNO, PRODUCTCODE, PRODUCTDESCRIPTION, TRANSACTIONTYPE, SCANDATE, SCANDATETRUNC, LANGUAGECODE, BUSINESSUNIT_ID, DEFAULTBUSINESSUNIT_ID, BU_CODE, COUNTID)
as select cu.customer_id, cu.customernumber,
       deb.customernumber debtornumber,
       cu.masteraccount,
       macc.customernumber masteraccountnumber,
       cu.name customername,
       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   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,
       (select bus.code from businessunit bus where bus.businessunit_id=scan.businessunit_id) bu_code,
       count(scan.primaryid) CountID
from customer cu, customer deb, customer macc, address, product prd, stay, transactiontype, languages, scan
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
group by  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_SCANS
 (CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, TRANSACTIONTYPE_ID, TRANSACTIONTYPEDESC, WORKSTATIONCODE, WORKSTATIONDESC, USERNAME, FULLNAME, SCANTIMESTAMP, SCANDATE, SCANTIME_NUMBER, PRIMARYID, BUSINESSUNITCODE, BUSINESSUNIT_ID, PLANTDEPARTMENTCODE, PLANTDEPARTMENTDESC, LANGUAGECODE, REASON_CODE, ROUTENUMBER, QUALITYTESTTYPE_CODE, QUALITYTESTTYPE_DESC, TREATMENTTYPE_CODE, TREATMENTTYPE_DESC, SCANTIME_CHAR, REPORTPARAM_ID, NUMBER_VALUE5, NUMBER_VALUE6)
as select --+ INDEX (scan XSPEEDSCAN)
culk.customer_id, culk.customernumber, culk.name CustomerName, 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
, coalesce(wst.code, ' ') workstationCode, wst.description workstationDesc
, sy.username, sy.fullname
, scan.scantimestamp, trunc(scan.scantimestamp) ScanDate
, GETTIMEASNUMERIC(scan.scantimestamp) ScanTime_Number
, scan.primaryid, bu.code businessunitCode, bu.businessunit_id
, pd.code plantdepartmentcode, pd.description plantdepartmentdesc
, languages.code languageCode
, (select rc.code from reasoncode rc where scan.reasoncode_id = rc.reasoncode_id) reason_code
, (select r.routenumber from route r where scan.route_id = r.route_id) routenumber
, (select qtt.code from qualitytesttype qtt where scan.qualitytesttype_id = qtt.qualitytesttype_id) qualitytesttype_code
, (select qttd.description from qualitytesttype_desc qttd where scan.qualitytesttype_id = qttd.qualitytesttype_id and qttd.language_id = languages.language_id) qualitytesttype_desc
, (select tt.code from treatmenttype tt, treatmentscan ts where ts.scan_id = scan.scan_id and ts.treatmenttype_id = tt.treatmenttype_id) treatmenttype_code
, (select ttd.description from treatmenttype_desc ttd, treatmentscan ts where ts.scan_id = scan.scan_id and ts.treatmenttype_id = ttd.treatmenttype_id and ttd.language_id = languages.language_id) treatmenttype_desc
, to_char(scan.scantimestamp,'HH24:MI:SS') ScanTime_Char
, rp.reportparam_id, rp.number_value5, rp.number_value6
from
  scan left outer join (workstation wst
         inner join plantdepartment pd on wst.plantdepartment_id = pd.plantdepartment_id)
       on scan.scanstation = wst.code
       left outer join customer culk on culk.customer_id = scan.customer_link_id
, businessunit bu, SYSTEMUSER sy , languages, reportparam rp,transactiontype
where scan.businessunit_id = bu.businessunit_id
and scan.systemuser_id = sy.systemuser_id
and coalesce(culk.customernumber, 0) >= rp.number_value1 and coalesce(culk.customernumber, 999999999999) <= rp.number_value2
and nvl(sy.username,' ') >= nvl(rp.string_value3,' ') and nvl(sy.username,' ') <= nvl(rp.string_value4,'ZZZZZZZZZZZZZZZZZZZZZ' )
--and coalesce(wst.code, ' ') >= rp.string_value5 and coalesce(wst.code, ' ') <= rp.string_value6
and (coalesce(wst.code, ' ') >= coalesce(rp.string_value5, ' ') )
and (coalesce(wst.code, ' ') <= coalesce(rp.string_value6, 'ZZZZZZZZZZZZ') )
and (
    nvl(rp.string_value8,'-') = '-' --NOT BNL
    or --is BNL and filter on Plant Dept
    (nvl(rp.string_value8,' ') <> '-' and coalesce(pd.code, ' ') >= rp.string_value7 and coalesce(pd.code, ' ') <= rp.string_value8)
    )
    and scan.transactiontype_id = transactiontype.transactiontype_id
and transactiontype.transactiontype_id between rp.number_value3 and rp.number_value4
and trunc(scan.scantimestamp) >= TRUNC(rp.date_value1) and trunc(scan.scantimestamp) < TRUNC(rp.date_value2)
and languages.code = rp.string_value
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)
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
 (ROUTENUMBER, BATCHNUMBER, DAYNUMBER, DESCRIPTION, CODE, GARMENTSOILSCANNED, DEPOTDESC, SORTBATCHDESC)
as SELECT
 A.ROUTENUMBER,
 S.BATCHNUMBER,
 D.DAYNUMBER,
 A.DESCRIPTION,
 DEPOT.CODE,
 COUNT(1) GARMENTSOILSCANNED,
 DEPOT.DESCRIPTION depotDesc,
 S.DESCRIPTION sortBatchDesc
  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 = 30)
   AND UIR.PLANNEDOUTROUTE_ID = A.ROUTE_ID
  GROUP BY A.ROUTENUMBER,
          S.BATCHNUMBER,
          D.DAYNUMBER,
          A.DESCRIPTION,
          DEPOT.CODE,
          DEPOT.DESCRIPTION,
          S.DESCRIPTION
/
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 = 30)
   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, WEARERFIRSTNAME, WEARERLASTNAME, PRIMARYID, PRODUCTCODE, SIZECODE, PRODUCTDESC, SIZEDESC, YEAR, WEEK, DAYNO, DAYCODE, SCANTIMESTAMP, SCANDATE, TRANSACTIONTYPE_ID, TRANSACTIONTYPEDESC, FACTORYDESCRIPTION, LANGUAGECODE, REASON_CODE, PNNOTENUMBER, REPORTPARAM_ID, BUSINESSUNIT_ID, NUMBER_VALUE9, NUMBER_VALUE)
as select--+ INDEX(scan XSPEEDSCAN) INDEX(dilk XPKDISTRIBUTIONPOINT_LINK) INDEX(prdlk XPKPRODUCT_LINK)
  cu.customernumber,  cu.name customerName, cu.customer_id, delk.departmentnumber, delk.description departmentDesc
, w.wearernumber, w.fullname wearername, w.firstname wearerfirstname, w.searchname wearerlastname
, case when length(scan.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(scan.primaryid)
              else scan.primaryid
  end primaryid
, prdlk.code ProductCode, szlk.code SizeCode
, (select product_desc.description from product_desc where product_desc.product_id = prdlk.product_id
  and product_desc.language_id = languages.language_id ) ProductDesc
, (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = szlk.sizedefinition_link_id
  and sdd.language_id = languages.language_id ) SizeDesc
, 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
, trunc(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
, rc.code reason_code
, case when transactiontype.transactiontype_id = 2 then
       coalesce((select pn.notenumber from deliveryscan ds, packingnote pn, uniqueitem ui
         where ds.uniqueitem_link_id = scan.uniqueitem_link_id
               and ds.uniqueitem_link_id = ui.uniqueitem_id
               and ds.scantimestamp = ui.lastoutscandate
               and pn.packingnote_id = ds.packingnote_id), -1)
  else null
  end pnnotenumber
, rp.reportparam_id
, scan.businessunit_id, rp.number_value9,rp.number_value
from
  scan left outer join reasoncode rc on scan.reasoncode_id = rc.reasoncode_id, customer cu, distributionpoint_link dilk, department_link delk, weareremployment we join wearer w on w.wearer_id=we.wearer_id
, product_link prdlk, sizedefinition_link szlk, transactiontype
, languages, reportparam rp
, businessunit bu
WHERE scan.customer_link_id = cu.customer_id and
    scan.weareremployment_link_id = we.weareremployment_id
         and we.distributionpoint_id = dilk.distributionpoint_link_id
             and dilk.department_link_id = delk.department_link_id
                 and delk.customer_link_id = cu.customer_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 cu.customernumber >= rp.number_value1 and cu.customernumber <= rp.number_value2
and delk.departmentnumber >= rp.number_value3 and delk.departmentnumber <= rp.number_value4
and w.wearernumber >= rp.number_value5 and w.wearernumber <= rp.number_value6
and transactiontype.transactiontype_id >= rp.number_value7 and transactiontype.transactiontype_id <= rp.number_value8
and languages.code = rp.string_value
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(scan.scantimestamp) >= rp.date_value1 and trunc(scan.scantimestamp) <= rp.date_value2
and decode(rp.number_value,0 ,rp.number_value9,scan.businessunit_id)=scan.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 ))
    )
and bu.businessunit_id = cu.defaultbusinessunit_id

/
create or replace view V_SCANSPERWEARER_AUJ
 (CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMER_ID, DEPARTMENTNUMBER, DEPARTMENTDESC, WEARERNUMBER, WEARERNAME, PRIMARYID, PRODUCTCODE, SIZECODE, PRODUCTDESC, YEAR, WEEK, DAYNO, DAYCODE, SCANTIMESTAMP, SCANDATE, TRANSACTIONTYPE_ID, TRANSACTIONTYPEDESC, FACTORYDESCRIPTION, LANGUAGECODE, REASON_CODE, MAXINVENTORY, CHANGESPERWEEK)
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 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
, GETDATEONLY(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 wi1.maxinventory+wi1.maxfreeofcharge from wearerinventory wi1
  where wi1.weareremployment_id = wylk.weareremployment_link_id
  and wi1.product_id = prdlk.product_link_id and wi1.sizedefinition_id = szlk.sizedefinition_link_id) maxinventory
, (select wi2.changesperweek from wearerinventory wi2 where wi2.weareremployment_id = wylk.weareremployment_link_id
  and wi2.product_id = prdlk.product_link_id and wi2.sizedefinition_id = szlk.sizedefinition_link_id) changesperweek
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_SCANSPERWEARER_DRE
 (CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMER_ID, DEPARTMENTNUMBER, DEPARTMENTDESC, WEARERNUMBER, WEARERNAME, PRIMARYID, PRODUCTCODE, SIZECODE, PRODUCTDESC, YEAR, WEEK, DAYNO, DAYCODE, SCANTIMESTAMP, SCANDATE, TRANSACTIONTYPE_ID, TRANSACTIONTYPEDESC, FACTORYDESCRIPTION, LANGUAGECODE, REASON_CODE, REPORTPARAM_ID, BUSINESSUNIT_ID, NUMBER_VALUE9, NUMBER_VALUE, QUALITYGRADEDESC)
as select--+ INDEX(scan XSPEEDSCAN) INDEX(dilk XPKDISTRIBUTIONPOINT_LINK) INDEX(prdlk XPKPRODUCT_LINK)
  cu.customernumber, cu.name customerName, cu.customer_id, delk.departmentnumber, delk.description departmentDesc
, wylk.wearernumber, wylk.wearername, scan.primaryid
, prdlk.code ProductCode, szlk.code SizeCode
, (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
, trunc(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 rcd.description from reasoncode_desc rcd where rcd.reasoncode_id = rc.reasoncode_id and rcd.language_id = languages.language_id) reason_code
, rp.reportparam_id
, scan.businessunit_id, rp.number_value9, rp.number_value
, (select qgd.description from qualitygrade_desc qgd where qgd.qualitygrade_id = scan.qualitygrade_id and qgd.language_id = languages.language_id) qualitygradedesc
from
  scan left outer join reasoncode rc on scan.reasoncode_id = rc.reasoncode_id
, customer cu, distributionpoint_link dilk, department_link delk, weareremployment_link wylk
, product_link prdlk, sizedefinition_link szlk, transactiontype
, languages, reportparam rp
WHERE scan.customer_link_id = cu.customer_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 = cu.customer_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 not in (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 510, 511, 512, 540, 541, 542, 543, 545, 640)
/*    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 cu.customernumber >= rp.number_value1 and cu.customernumber <= rp.number_value2
and delk.departmentnumber >= rp.number_value3 and delk.departmentnumber <= rp.number_value4
and wylk.wearernumber >= rp.number_value5 and wylk.wearernumber <= rp.number_value6
and transactiontype.transactiontype_id >= rp.number_value7 and transactiontype.transactiontype_id <= rp.number_value8
and languages.code = rp.string_value
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(scan.scantimestamp) >= rp.date_value1 and trunc(scan.scantimestamp) <= rp.date_value2
and decode(rp.number_value,0 ,rp.number_value9,scan.businessunit_id)=scan.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_SCANSPERWEARER_WBA
 (CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMER_ID, DEPARTMENTNUMBER, DEPARTMENTDESC, WEARERNUMBER, WEARERNAME, PRIMARYID, PRODUCTCODE, SIZECODE, PRODUCTDESC, YEAR, WEEK, DAYNO, DAYCODE, SCANTIMESTAMP, SCANDATE, TRANSACTIONTYPE_ID, TRANSACTIONTYPEDESC, FACTORYDESCRIPTION, LANGUAGECODE, REASON_CODE, REPORTPARAM_ID)
as select culk.customernumber
,      culk.name customerName
,      culk.customer_id
,      delk.departmentnumber
,      delk.description departmentDesc
,      wylk.wearernumber
,      wylk.wearername
,      s.primaryid
,      prdlk.code ProductCode
,      szlk.code SizeCode
,      ( select product_desc.description
         from   product_desc
         where  product_desc.product_id = prdlk.product_id
            and product_desc.language_id = languages.language_id ) ProductDesc
,      s.year
,      s.week
,      s.dayno
,      ( select day_desc.code
         from   day_desc
         where  day_desc.day_id = s.dayno
            and day_desc.language_id = languages.language_id ) dayCode
,      to_char(s.scantimestamp, 'HH24.MI.SS') scantimestamp
,      trunc(s.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  s.reasoncode_id = rc.reasoncode_id ) reason_code
,      rp.reportparam_id
from   scan s
,      customer_link culk
,      distributionpoint_link dilk
,      department_link delk
,      weareremployment_link wylk
,      product_link prdlk
,      sizedefinition_link szlk
,      transactiontype
,      languages
,      reportparam rp
where  s.weareremployment_link_id = wylk.weareremployment_link_id
   and s.customer_link_id = culk.customer_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 s.product_link_id = prdlk.product_link_id
   and s.sizedefinition_link_id = szlk.sizedefinition_link_id
   and s.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 ( ( culk.customer_id = rp.number_value9 )
         or
         (s.businessunit_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_SCANSWITHFLAGS_NIX
 (FLAGCODE, FLAGDESC, WORKSTATIONCODE, WORKSTATIONDESC, TRANSACTIONTYPE_ID, TRANSACTIONTYPEDESC, SCANTIMESTAMP, SCANDATE, PRIMARYID, CUSTOMERNUMBER, CUSTOMERNAME, FLAGRESPONSE, LANGUAGECODE, ROUTENUMBER, SCANTIME_NUMBER, SCANTIME_CHAR)
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
, wst.code workstationCode, wst.description 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, GETDATEONLY(scan.scantimestamp) ScanDate, scan.primaryid
, culk.customernumber, culk.name CustomerName
, scanflag.flagresponse
, languages.code languageCode
, coalesce((select ro.routenumber from route ro where scan.route_id = ro.route_id),
            (select max(rou.routenumber) from route rou, routestop rs where scan.customer_link_id = rs.customer_id and rs.route_id = rou.route_id)) RouteNumber
, GETTIMEASNUMERIC(scan.scantimestamp) ScanTime_Number
, to_char(scan.scantimestamp,'fmHHfm:MI:SS:AM') ScanTime_Char
from scanflag, flag
, scan
       left outer join customer_link culk on culk.customer_link_id= scan.customer_link_id
       left outer join workstation wst on scan.scanstation = wst.code
, 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)
as select 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
from   scan s
join   businessunit bu
on     bu.businessunit_id = s.businessunit_id
join   systemuser sy
on     sy.systemuser_id = s.systemuser_id
left   outer join(workstation wst
inner  join plantdepartment pd
on     wst.plantdepartment_id = pd.plantdepartment_id) on s.scanstation = wst.code
left   outer join customer culk
on     culk.customer_id = s.customer_link_id, languages l
group by l.language_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_SCANS_TOTAL_SNG
 (SCANDATE, BUSINESSUNIT_ID, CUSTOMER_ID, CUSTOMERBU_ID, SCANTIMESTAMP, 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)
as select trunc(s.scantimestamp) scandate, s.businessunit_id, s.customer_link_id customer_id, coalesce(culk.defaultbusinessunit_id,s.businessunit_id) CustomerBU_ID,
       s.scantimestamp, 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
from   scan s
join   businessunit bu
on     bu.businessunit_id = s.businessunit_id
join   systemuser sy
on     sy.systemuser_id = s.systemuser_id
left   outer join(workstation wst
inner  join plantdepartment pd
on     wst.plantdepartment_id = pd.plantdepartment_id) on s.scanstation = wst.code
left   outer join customer culk
on     culk.customer_id = s.customer_link_id, languages l
group by l.language_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, s.scantimestamp

/
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  rp.reportparam_id,sl.shipmentlist_id,sl.shipmentlistnumber,sll.shipmentlistline_id, sl.completiondate,
bu.code bucode, bu.description budescr,
pladdr.street bustreet, pladdr.zipcode buzipcode, pladdr.city bucity, co.description bucountry,
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,
 coalesce((select max(a.transportunitnumber) from shipmentlistline a where a.shipmentlist_id=sl.shipmentlist_id),0)notrunit,
coalesce((select sum(b.quantityshipped) from shipmentlistline b where b.shipmentlist_id=sl.shipmentlist_id),0)noitems,
(select count(distinct(wo.workorder_id)) from workorder wo, workorderline wol, shipmentlistline sla
       where wol.workorderline_id=sla.workorderline_id and wol.workorder_id=wo.workorder_id and sla.shipmentlist_id=sl.shipmentlist_id) noWO,
sll.transportunitnumber, wo.workordernumber, p.code prodcode,
( select pdesc.description from product_desc pdesc
where pdesc.product_id=p.product_id and pdesc.language_id=lan.language_id) prod_desc, sz.code szcode,
w.wearernumber, w.fullname, ui.primaryid,
pol.purchaseprice polprice,
cu.code currencycode,
cu.decimals decimals, lan.code languagecode
from shipmentlist sl, shipmentlistline sll,workorderline wol
        left outer join workorderlinepurchordline wolpol
          on wol.workorderline_id=wolpol.workorderline_id
         , workorder wo
left outer join  weareremployment we on wo.weareremployment_link_id=we.weareremployment_id
left outer join  wearer w on we.wearer_id=w.wearer_id
 , product p, sizedefinition sz, issuehistory ih , uniqueitem ui, businessunit bu, plant pl,
 address pladdr, country co,stockroom st, address staddress,  languages lan,
 reportparam  rp, purchaseorderheader poh, purchaseorderline pol, currency cu
 where sl.shipmentlist_id=sll.shipmentlist_id
 and sl.supplyingstockroom_id=st.stockroom_id
 and sl.shiptobusinessunit_id=bu.businessunit_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
 and sll.workorderline_id=wol.workorderline_id
 and wol.workorder_id=wo.workorder_id
 and wol.product_link_id=p.product_id
 and wol.sizedefinition_link_id=sz.sizedefinition_id
 and nvl(wol.purchaseorderline_id, wolpol.purchaseorderline_id)=pol.purchaseorderline_id
 and pol.purchaseorderheader_id=poh.purchaseorderheader_id
 and poh.currency_id=cu.currency_id
 and ih.workorder_id=wo.workorder_id
 and ih.shipmentlistline_id=sll.shipmentlistline_id
 and ih.uniqueitem_link_id=ui.uniqueitem_id
 and ih.product_link_id=p.product_id
 and ih.sizedefinition_link_id=sz.sizedefinition_id
 and rp.number_value=sl.shipmentlist_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, 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
, 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_SHORTAGES_LTS
 (BUSINESSUNITCODE, BUSINESSUNITDESC, CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESC, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESC, PRODUCTGROUPCODE, PRODUCTCODE, SIZEDEFINITIONCODE, FINISHINGMETHODCODE, PRODUCTDESC, 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
, 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
, 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
, 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_SHORTSFROMSTOCKTAKE_LLG
 (BUCODE, COUNTDATE, CUSTOMERNUMBER, CUSTOMERNAME, PRODUCTCODE, PRODUCTDESC, SIZECODE, PGCODE, LANGUAGECODE, DIFFERENCECPL)
as select
(select bu.code from businessunit bu,customer c, distributionpoint dp, department d
        where cic.distributionpoint_id = dp.distributionpoint_id
        and dp.department_id = d.department_id
        and d.customer_id = c.customer_id and bu.businessunit_id = c.defaultbusinessunit_id) bucode,
cic.countdate,
(select c.customernumber from customer c, distributionpoint dp, department d
        where cic.distributionpoint_id = dp.distributionpoint_id
        and dp.department_id = d.department_id
        and d.customer_id = c.customer_id) customernumber,
(select c.name from customer c, distributionpoint dp, department d
        where cic.distributionpoint_id = dp.distributionpoint_id
        and dp.department_id = d.department_id
        and d.customer_id = c.customer_id) customername,
(select p.code from product p where p.product_id = cic.product_id) productcode,
(select pd.description from product_desc pd where pd.product_id = cic.product_id and pd.language_id = l.language_id) productdesc,
(select sd.code from sizedefinition sd where sd.sizedefinition_id = cic.sizedefinition_id) sizecode,
(select pg.code from productgroup pg, product p where p.product_id = cic.product_id and pg.productgroup_id = p.productgroup_id) pgcode,
l.code languagecode,cic.adjustmentcpl differencecpl
from customerinventorycount cic,
languages l
where cic.adjustmentcpl < 0

/
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,  to_date(a.salesdate) assigndate,
  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,
 sum(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,
  languages.code languagecode
from garmentsaleshistory a, workorder wo,workorderline wol, product p, sizedefinition_link s, qualitygrade qg, languages
where a.workorderline_id=wol.workorderline_id
and wol.workorder_id=wo.workorder_id
  and a.product_link_id = p.product_id
  and a.sizedefinition_link_id = s.sizedefinition_link_id
  and a.qualitygrade_id=qg.qualitygrade_id
  group by wo.workorder_id,  to_date(a.salesdate), p.code,a.product_link_id,s.code,
  s.sizedefinition_link_id,qg.qualitygrade_id,qg.code,languages.code,languages.language_id

/
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 GETCURRENTDATE() 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_SOILTICKETHEADER
 (SOILTICKETNUMBER, SOILTICKETCOPIES, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERSTREET, CUSTOMERZIPCODE, CUSTOMERCITY, CUSTOMERSTREET2, CUSTOMERSTATE, CUSTOMERMARKINGGARMENT, ROUTECONTROL_ID, ROUTENUMBER, ROUTESTOPNUMBER, DEPOTCODE, PROCESSBUSINESSUNITCODE, PLANTCODE, INVOICENUMBER, INVOICEDATE, IMPORTDATE, COUNTDATE, EMPLOYEENUMBER, EMPLOYEENAME, SYSTEMUSER_ID, TIMESTAMP, SOILTICKET_ID)
as select a.soilticketnumber,t.soiltickets soilticketcopies,
c.customernumber, c.name customername,
s.street customerstreet, s.zipcode customerzipcode, s.city customercity,
s.street2 customerstreet2,s.state customerstate, c.customermarkinggarment,
r.routecontrol_id,
d.routenumber, a.routestopnumber,f.code depotcode,
b.code processbusinessunitcode,
p.code plantcode,
a.invoicenumber, a.invoicedate, a.importdate, a.countdate,
e.employeenumber, e.name employeename,
a.systemuser_id, a.timestamp, a.soilticket_id
from  businessunit b, customer c, routecontrol r, routestop t,
 soilticket a
 LEFT OUTER JOIN employee e ON(a.employee_id = e.employee_id),
 route d
 LEFT OUTER JOIN depot f ON (d.depot_id = f.depot_id), PLANT P, address s
where a.customer_id = c.customer_id
and c.visitaddress_id = s.address_id
and a.routecontrol_id = r.routecontrol_id
and r.route_id = d.route_id
and t.route_id = d.route_id
and t.customer_id = a.customer_id
and a.processbusinessunit_id = b.businessunit_id
and b.plant_id = p.plant_id

/
create or replace view V_SOILTICKETHEADER_POS
 (SOILTICKETNUMBER, SOILTICKETCOPIES, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERSTREET, CUSTOMERZIPCODE, CUSTOMERCITY, CUSTOMERSTREET2, CUSTOMERSTATE, CUSTOMERMARKINGGARMENT, ROUTECONTROL_ID, ROUTENUMBER, ROUTESTOPNUMBER, DEPOTCODE, PROCESSBUSINESSUNITCODE, PLANTCODE, INVOICENUMBER, INVOICEDATE, IMPORTDATE, COUNTDATE, EMPLOYEENUMBER, EMPLOYEENAME, SYSTEMUSER_ID, TIMESTAMP, SOILTICKET_ID, STOPNUMBER, DRIVINGDATE, LANGUAGE_CODE, DAY_DESC)
as select a.soilticketnumber,t.soiltickets soilticketcopies,
c.customernumber, c.name customername,
s.street customerstreet, s.zipcode customerzipcode, s.city customercity,
s.street2 customerstreet2,s.state customerstate, c.customermarkinggarment,
r.routecontrol_id,
d.routenumber, a.routestopnumber,f.code depotcode,
b.code processbusinessunitcode,
p.code plantcode,
a.invoicenumber, a.invoicedate, a.importdate, a.countdate,
e.employeenumber, e.name employeename,
a.systemuser_id, a.timestamp, a.soilticket_id
, (SELECT st.stopnumber FROM STOP st WHERE st.stop_id = a.stop_id) Stopnumber
, r.drivingdate, lan.code Language_code,
(SELECT dd.description FROM DAY_DESC dd WHERE dd.day_id = GETABSDAYNUMBER(r.drivingdate) AND dd.language_id = lan.language_id) Day_desc
from  businessunit b, customer c, routecontrol r, routestop t,
 soilticket a
 LEFT OUTER JOIN employee e ON(a.employee_id = e.employee_id),
 route d
 LEFT OUTER JOIN depot f ON (d.depot_id = f.depot_id), PLANT P, address s
 , languages lan
where a.customer_id = c.customer_id
and c.visitaddress_id = s.address_id
and a.routecontrol_id = r.routecontrol_id
and r.route_id = d.route_id
and t.route_id = d.route_id
and t.customer_id = a.customer_id
and a.processbusinessunit_id = b.businessunit_id
and b.plant_id = p.plant_id

/
create or replace view V_SOILTICKETLINE
 (SOILTICKETNUMBER, PRODUCTCODE, PRODUCTDESCRIPTION, FINISHINGMETHODCODE, SIZEDEFINITIONCODE, COUNTLIGHTFRAME, COUNTKEYPAD, COUNTCONVERTED, COUNTABUSED, SOILWEIGHT, INVOICELINENUMBER, INVENTORY, DELAYEDEVENEXCHANGE, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE)
as select b.soilticketnumber, p.code productcode,
(SELECT description  FROM PRODUCT_DESC X WHERE X.PRODUCT_ID = A.PRODUCT_ID AND X.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) productdescription,
 f.code finishingmethodcode,
s.code sizedefinitioncode, a.countlightframe, a.countkeypad, a.countconverted, a.countabused,
a.soilweight, a.invoicelinenumber, a.inventory, a.delayedevenexchange, a.systemuser_id, a.timestamp, LANGUAGES.CODE LANGUAGECODE
from soilticketline a, soilticket b, product p, finishingmethod f, sizedefinition s, LANGUAGES
where a.soilticket_id = b.soilticket_id
and a.product_id = p.product_id
and a.finishingmethod_id = f.finishingmethod_id
and a.sizedefinition_id = s.sizedefinition_id

/
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 GETCURRENTDATE() 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 GETCURRENTDATE() 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_SPECIALCHARGE
 (SPECIALCHARGECODE, SPECIALCHARGEDESCRIPTION, STARTDATE, FREQUENCY, INCLUDININVOICEMINIMUM, NEWPERCENTAGE, OLDPERCENTAGE, NEWAMOUNT, OLDAMOUNT, FIXEDAMOUNT, TURNOVERGROUPCODE, TURNOVERGROUPDESCRIPTION, SPECIALCHARGE_ID, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE)
as select specialcharge.code,
 (SELECT description FROM SPECIALCHARGE_DESC a WHERE a.specialcharge_id = specialcharge.specialcharge_id
  AND a.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) specialchargedescription,
 specialcharge.startdate, specialcharge.frequency, --specialcharge.autoaddtonewcustomer,
 specialcharge.includininvoiceminimum, specialcharge.newpercentage, specialcharge.oldpercentage,
 specialcharge.newamount, specialcharge.oldamount, specialcharge.fixedamount,
 turnovergroup.code,
 (SELECT description FROM turnovergroup_DESC b WHERE b.turnovergroup_id = specialcharge.turnovergroup_id
  AND b.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) turnovergroupdescription,
 specialcharge.specialcharge_id, specialcharge.SYSTEMUSER_ID,
 specialcharge.TIMESTAMP, languages.code
from languages, specialcharge
 left outer join turnovergroup on (turnovergroup.turnovergroup_id = specialcharge.turnovergroup_id)

/
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_SQITEMSINCIRCULATION_BDM
 (CUSTOMER_LINK_ID, WEEK, PRODUCT_LINK_ID, COSTCENTER_ID, YEAR, SIZEDEFINITION_LINK_ID, CODE, TOTALCIRCINV, CHANGESPERWEEK, MAXINV, PRODUCTCODE, SIZECODE)
as select sqi.customer_link_id, sq.week, sqi.product_link_id, dp.costcenter_id, sq.year,
 sqi.sizedefinition_link_id,p.code, sqi.totalcircinv, sqi.changesperweek, sqi.maxinv, p.code productcode,
 (select sd.code from sizedefinition sd where sd.sizedefinition_id=sqi.sizedefinition_link_id) sizecode
from statusquoheader sq
join sqitemincirculation sqi on sqi.statusquoheader_id=sq.statusquoheader_id
join distributionpoint dp on sqi.distributionpoint_link_id=dp.distributionpoint_id
join product p on sqi.product_link_id=p.product_id
and exists (select 1 from packingnote pn join packingnoteline pnl
on pn.packingnote_id=pnl.packingnote_id
join distributionpoint dp on pn.distributionpoint_id=dp.distributionpoint_id
join department dep on dp.department_id=dep.department_id
join customer c on c.customer_id=dep.customer_id
where year(pn.deliverydate)= sq.year
and getisoweek(pn.deliverydate)=sq.week
and c.customer_id=sqi.customer_link_id
and pnl.product_id=sqi.product_link_id
and sqi.sizedefinition_link_id=pnl.sizedefinition_id
and sqi.finishingmethod_id=pnl.finishingmethod_id
)

/
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_SQSTOCKQUANTITY_AUS
 (YEARWEEK, YEAR, WEEK, PRODUCTGROUPCODE, PRODUCTGROUP_DESC, PRODUCTCODE, PRODUCT_DESC, STOCKROOMCODE, STOCKROOMNAME, CUSTOMEROWNED, CUSTOMERNUMBER, CUSTOMERNAME, STOCKUNIQUE, SIZEDEFINITIONCODE, SIZEDEFINITION_DESC, QTYONSTOCK, QTYUNIQUEWITHMODIF, QTYNEW, QTYUSED, QTYNEWRESERVED, QTYUSEDRESERVED, QTYORDERED, STATUSQUOHEADER_ID, SQSTOCKQUANTITY_ID, STATUSQUODATE, PRICEAVGPP, LEDGERACCOUNT, 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,
  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, b.sqstockquantity_id,
  a.statusquodate,
  F_GetAvgPPAtDatePerSkProdSize(a.statusquodate, b.product_link_id, b.sizedefinition_link_id, b.stockroom_id, b.customerowned, b.customer_link_id) priceavgpp,
  (select la.exportcode
          from ledgeraccntsperproduct lpp,
               ledgeraccnttype        lat,
               ledgeraccounts         la
         where lpp.product_id = (case
                                  when d.typeofmerchandise = 1 then
                                   (select pm.product_id
                                      from product pm
                                     where pm.code = 'ZZ1')
                                  when d.typeofmerchandise = 2 then
                                   (select pm.product_id
                                      from product pm
                                     where pm.code = 'ZZ2')
                                  when d.typeofmerchandise = 3 then
                                   (select pm.product_id
                                      from product pm
                                     where pm.code = 'ZZ3')
                                end)
           and lat.code = 'SHLFST'
           and lat.ledgeraccnttype_id = lpp.ledgeraccnttype_id
           and lpp.ledgeraccounts_id = la.ledgeraccounts_id) ||'.'||
           (select substr(tg.code, -4)
                           from   turnovergroup tg
                           where  tg.turnovergroup_id = d.rentturnovergroup_id) ledgeraccount,
  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, 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 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, CUSTOMERLANGUAGECODE, DEPARTMENTNUMBER, DESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESC, DELIVERYPOINTCODE, DELIVERYPOINTDESC, PRODUCTCODE, PRODUCTGROUPCODE, PRODUCTDESC, SIZECODE, FINISHINGMETHODCODE, DELIVERYSCHEMECODE, SEASONCODE, SEASONDESC, DAYNUMBER, AMOUNT, STOCK_DAYNUMBER, STOCK_AMOUNT, 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)
as SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, W.CODE CUSTOMERLANGUAGECODE, DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION,
  DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION distributionpointdesc,
  DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESC, PRODUCT.CODE productcode,
  Z.CODE productgroupcode,
  (select a.DESCRIPTION from PRODUCT_DESC a where a.product_id = PRODUCTLISTPERDISTRIBPOINT.PRODUCT_ID and a.language_id = LG.language_id) productdesc,
  SIZEDEFINITION.CODE sizecode,
  FINISHINGMETHOD.CODE finishingmethodcode,
  Y.CODE deliveryschemecode,
  X.code SEASONCODE,
  (select st.DESCRIPTION from SEASONTYPE_DESC ST where X.SEASONTYPE_ID=ST.SEASONTYPE_ID and ST.language_id = LG.language_id) SEASONDESC,
  D1.DAYNUMBER, STANDARDDELIVERYAMOUNT.AMOUNT, NS_AMOUNT.STOCK_DAYNUMBER,
  NS_AMOUNT.STOCK_AMOUNT,
  PRODUCTLISTPERDISTRIBPOINT.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,
  GETDATEONLY(STANDARDDELIVERYLINE.DATEACTIVE) DATEACTIVE, GETDATEONLY(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
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 STANDARDDELIVERYAMOUNT
               inner join DAY D1 on STANDARDDELIVERYAMOUNT.DAY_ID = D1.DAY_ID
         on STANDARDDELIVERYLINE.STANDARDDELIVERYLINE_ID = STANDARDDELIVERYAMOUNT.STANDARDDELIVERYLINE_ID
         inner join PRODUCTLISTPERDISTRIBPOINT
             left outer 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 (PRODUCTLISTPERDISTRIBPOINT.PRODUCTLISTPERDISTRIBPOINT_ID = NS_AMOUNT.PRODUCTLISTPERDISTRIBPOINT_ID)
             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 PRODUCTLISTPERDISTRIBPOINT.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
             inner join PRODUCT
                   left outer join PRODUCTGROUP Z ON PRODUCT.PRODUCTGROUP_ID = Z.PRODUCTGROUP_ID
             on PRODUCTLISTPERDISTRIBPOINT.PRODUCT_ID = PRODUCT.PRODUCT_ID
             inner join SIZEDEFINITION on PRODUCTLISTPERDISTRIBPOINT.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
             inner join FINISHINGMETHOD on PRODUCTLISTPERDISTRIBPOINT.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
          ON STANDARDDELIVERYLINE.PRODUCTLISTPERDISTRIBPOINT_ID = PRODUCTLISTPERDISTRIBPOINT.PRODUCTLISTPERDISTRIBPOINT_ID
  on STANDARDDELIVERY.STANDARDDELIVERY_ID = STANDARDDELIVERYLINE.STANDARDDELIVERY_ID,
  LANGUAGES LG, reportparam rp, businessunit bu
WHERE DEPARTMENT.ACTIVE = 'Y'
  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) --StandardDelivery.rpt

/
create or replace view V_STANDARDDELIVERYANDSTOCK_ECL
 (CUSTOMERNUMBER, NAME, CUSTOMERLANGUAGECODE, DEPARTMENTNUMBER, DESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESC, DELIVERYPOINTCODE, DELIVERYPOINTDESC, PRODUCTCODE, PRODUCTGROUPCODE, PRODUCTDESC, SIZECODE, FINISHINGMETHODCODE, DELIVERYSCHEMECODE, SEASONCODE, SEASONDESC, DAYNUMBER, AMOUNT, STOCK_DAYNUMBER, STOCK_AMOUNT, 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, FORECASTAMOUNT, STOCKCOUNT, ORDERDAY, ORDERDATE, DISTRIBUTIONPOINT_ID, PRODUCT_ID, CURRENTDAY)
as SELECT CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME, W.CODE CUSTOMERLANGUAGECODE, DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION,
  DISTRIBUTIONPOINT.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT.DESCRIPTION distributionpointdesc,
  DELIVERYPOINT.CODE DELIVERYPOINTCODE, DELIVERYPOINT.DESCRIPTION DELIVERYPOINTDESC, PRODUCT.CODE productcode,
  Z.CODE productgroupcode,
  (select a.DESCRIPTION from PRODUCT_DESC a where a.product_id = PRODUCTLISTPERDISTRIBPOINT.PRODUCT_ID and a.language_id = LG.language_id) productdesc,
  SIZEDEFINITION.CODE sizecode,
  FINISHINGMETHOD.CODE finishingmethodcode,
  Y.CODE deliveryschemecode,
  X.code SEASONCODE,
  (select st.DESCRIPTION from SEASONTYPE_DESC ST where X.SEASONTYPE_ID=ST.SEASONTYPE_ID and ST.language_id = LG.language_id) SEASONDESC,
  D1.DAYNUMBER, STANDARDDELIVERYAMOUNT.AMOUNT, NS_AMOUNT.STOCK_DAYNUMBER,
  NS_AMOUNT.STOCK_AMOUNT,
  PRODUCTLISTPERDISTRIBPOINT.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,
  GETDATEONLY(STANDARDDELIVERYLINE.DATEACTIVE) DATEACTIVE, GETDATEONLY(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,
  coalesce(f_forecastamount(STANDARDDELIVERYAMOUNT.day_id, STANDARDDELIVERY.distributionpoint_id, PRODUCTLISTPERDISTRIBPOINT.product_id,
                                  PRODUCTLISTPERDISTRIBPOINT.sizedefinition_id, PRODUCTLISTPERDISTRIBPOINT.finishingmethod_id),0) forecastamount,
  (select sum(iol.quantity)
 from internetorder io join distributionpoint dp on io.distributionpoint_link_id=dp.distributionpoint_id
join department dep on dep.department_id=dp.department_id
join customer c on c.customer_id=dep.customer_id
join internetorderline iol on iol.internetorder_id=io.internetorder_id
join product p on p.product_id=iol.product_link_id
where  c.customer_id=CUSTOMER.Customer_Id
and p.product_id=product.product_id
and getabsdaynumber(io.orderdate) = STANDARDDELIVERYAMOUNT.DAY_ID
and io.orderdate= (select max(io2.orderdate)
 from internetorder io2
join internetorderline iol2 on iol2.internetorder_id=io2.internetorder_id
where io2.distributionpoint_link_id=distributionpoint.distributionpoint_id
and iol2.product_link_id=product.product_id
and io2.orderdate<=sysdate
)
)stockcount, (select getabsdaynumber(max(io2.orderdate))
 from internetorder io2
join internetorderline iol2 on iol2.internetorder_id=io2.internetorder_id
where io2.distributionpoint_link_id=distributionpoint.distributionpoint_id
and iol2.product_link_id=product.product_id
and io2.orderdate<=sysdate
) orderday,
(select max(io2.orderdate)
 from internetorder io2
join internetorderline iol2 on iol2.internetorder_id=io2.internetorder_id
where io2.distributionpoint_link_id=distributionpoint.distributionpoint_id
and iol2.product_link_id=product.product_id
and io2.orderdate<=sysdate
) OrderDate, DISTRIBUTIONPOINT.Distributionpoint_Id, PRODUCT.Product_Id, getabsdaynumber(sysdate) CurrentDay
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 STANDARDDELIVERYAMOUNT
               inner join DAY D1 on STANDARDDELIVERYAMOUNT.DAY_ID = D1.DAY_ID
         on STANDARDDELIVERYLINE.STANDARDDELIVERYLINE_ID = STANDARDDELIVERYAMOUNT.STANDARDDELIVERYLINE_ID
         inner join PRODUCTLISTPERDISTRIBPOINT
             left outer 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 (PRODUCTLISTPERDISTRIBPOINT.PRODUCTLISTPERDISTRIBPOINT_ID = NS_AMOUNT.PRODUCTLISTPERDISTRIBPOINT_ID)
             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 PRODUCTLISTPERDISTRIBPOINT.DISTRIBUTIONPOINT_ID = DISTRIBUTIONPOINT.DISTRIBUTIONPOINT_ID
             inner join PRODUCT
                   left outer join PRODUCTGROUP Z ON PRODUCT.PRODUCTGROUP_ID = Z.PRODUCTGROUP_ID
             on PRODUCTLISTPERDISTRIBPOINT.PRODUCT_ID = PRODUCT.PRODUCT_ID
             inner join SIZEDEFINITION on PRODUCTLISTPERDISTRIBPOINT.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID
             inner join FINISHINGMETHOD on PRODUCTLISTPERDISTRIBPOINT.FINISHINGMETHOD_ID = FINISHINGMETHOD.FINISHINGMETHOD_ID
          ON STANDARDDELIVERYLINE.PRODUCTLISTPERDISTRIBPOINT_ID = PRODUCTLISTPERDISTRIBPOINT.PRODUCTLISTPERDISTRIBPOINT_ID
  on STANDARDDELIVERY.STANDARDDELIVERY_ID = STANDARDDELIVERYLINE.STANDARDDELIVERY_ID,
  LANGUAGES LG, reportparam rp, businessunit bu
WHERE sysdate between STANDARDDELIVERYLINE.dateactive and STANDARDDELIVERYLINE.dateinactive
      and DEPARTMENT.ACTIVE = 'Y'
      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)

/
create or replace view V_STANDARDDELIVERYANDSTOCK_SNG
 (CUSTOMERNUMBER, NAME, CUSTOMERLANGUAGECODE, DEPARTMENTNUMBER, DESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESC, DELIVERYPOINTCODE, DELIVERYPOINTDESC, PRODUCTCODE, PRODUCTGROUPCODE, PRODUCTDESC, SIZECODE, FINISHINGMETHODCODE, DELIVERYSCHEMECODE, SEASONCODE, SEASONDESC, DAYNUMBER, AMOUNT, ORDERINGMETHOD, GENERATEZEROLINES, CLEANRETURN, DELIVERSTERILE, CORRECTSHORTAGES, CORRECTOVERDELIVERIES, NUMBEROFTRANSPORTARTICLES, OCCUPANCY, STANDARDQTYDEFINITION, TRANSPORTARTICLE_DESC
, DATEACTIVE, DATEINACTIVE, SYSTEMUSER_ID, TIMESTAMP, STANDARDDELIVERY_ID, LANGUAGECODE, ISTEMPDELSTOP, BUSINESSUNIT_ID, PLANT_CODE)
as select customer.customernumber, customer.name, w.code customerlanguagecode, department.departmentnumber, department.description,
  distributionpoint.distributionpointnumber, distributionpoint.description distributionpointdesc,
  deliverypoint.code deliverypointcode, deliverypoint.description deliverypointdesc, product.code productcode,
  z.code productgroupcode,
  (select description from product_desc a where a.product_id = productlistperdistribpoint.product_id and a.language_id = lg.language_id) productdesc,
  sizedefinition.code sizecode,
  finishingmethod.code finishingmethodcode,
  y.code deliveryschemecode,
  x.code seasoncode,
  (select description from seasontype_desc st where x.seasontype_id=st.seasontype_id and st.language_id = lg.language_id) seasondesc,
  d1.daynumber, standarddeliveryamount.amount,
  --ns_amount.stock_daynumber, ns_amount.stock_amount,
  productlistperdistribpoint.orderingmethod, standarddelivery.generatezerolines, standarddelivery.cleanreturn,
  standarddelivery.deliversterile, standarddelivery.correctshortages, standarddelivery.correctoverdeliveries,
  standarddelivery.numberoftransportarticles,
  department.occupancy, customer.standardqtydefinition,
  (select description from transportarticle_desc d where d.transportarticle_id= standarddelivery.transportarticle_id and d.language_id = lg.language_id) transportarticle_desc,
  standarddeliveryline.dateactive, standarddeliveryline.dateinactive,
  standarddeliveryline.systemuser_id,
  standarddeliveryline.timestamp, standarddeliveryline.standarddelivery_id, lg.code languagecode,
--standarddeliveryline.temporarystopstartweek , standarddeliveryline.temporarystopendweek,
  istemporarydeliverystop(year(sysdate), (select getisoweek(sysdate) from dual), standarddeliveryline.standarddeliveryline_id)
  + istemporarydeliverystop_date(sysdate, standarddeliveryline.standarddeliveryline_id) istempdelstop,
/*  (case
    when tds.temporarystopstartweek = 0 then 0
    when tds.temporarystopstartweek is null then 0
    else year(getcurrentdatetime())*100+tds.temporarystopstartweek
   end) temporarystopstartweek,
  (case
    when tds.temporarystopendweek=0 then 0
    when tds.temporarystopendweek is null then 0
    else f_endyear(tds.temporarystopstartweek,tds.temporarystopendweek)+tds.temporarystopendweek
   end) temporarystopendweek,
  (case
    when tds.temporarystopstartyear=0 then 0
    when tds.temporarystopstartyear is null then 0
    else tds.temporarystopstartyear*100+tds.tempstopstartweekforyear
   end) tempstopstartyearweek,
  (case
    when tds.temporarystopendyear=0 then 0
    when tds.temporarystopendyear is null then 0
    else tds.temporarystopendyear*100+tds.tempstopendweekforyear
   end) tempstopendyearweek, */
   bu.businessunit_id,
   (select p.code from plant p where p.plant_id = bu.plant_id) plant_code
   --, rp.reportparam_id
 -- standarddeliveryline.tempstoprentforweek, standarddeliveryline.tempstoprentforyearweek,
 -- standarddeliveryline.tempstopstartweekforyear, standarddeliveryline.tempstopendweekforyear
from customer, languages w, department, distributionpoint, deliverypoint, businessunit bu,
  product
    left outer join productgroup z on (product.productgroup_id = z.productgroup_id),
  sizedefinition, finishingmethod,
  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),
--    left outer join temporarydeliverystop tds on (tds.standarddeliveryline_id = standarddeliveryline.standarddeliveryline_id),
  productlistperdistribpoint,
/*    left outer 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(productlistperdistribpoint.productlistperdistribpoint_id = ns_amount.productlistperdistribpoint_id),*/
  standarddelivery,
  standarddeliveryamount, day d1,
  languages lg--, reportparam rp
where standarddelivery.standarddelivery_id = standarddeliveryline.standarddelivery_id
  and standarddeliveryamount.day_id=d1.day_id
  and standarddeliveryline.standarddeliveryline_id = standarddeliveryamount.standarddeliveryline_id
  and standarddeliveryline.productlistperdistribpoint_id = productlistperdistribpoint.productlistperdistribpoint_id
  and productlistperdistribpoint.distributionpoint_id = distributionpoint.distributionpoint_id
  and distributionpoint.deliverypoint_id = deliverypoint.deliverypoint_id
  and distributionpoint.department_id = department.department_id
  and department.customer_id = customer.customer_id
  and customer.language_id = w.language_id
  and productlistperdistribpoint.product_id = product.product_id
  and productlistperdistribpoint.sizedefinition_id = sizedefinition.sizedefinition_id
  and productlistperdistribpoint.finishingmethod_id = finishingmethod.finishingmethod_id
/*  and exists (select v.customer_id from v_customersperbusinessunitdp v
              where v.customer_id = customer.customer_id and v.businessunit_id = bu.businessunit_id)*/
  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) -- TD 26314
  and standarddeliveryline.dateactive <= sysdate
  and standarddeliveryline.dateinactive > sysdate
--standarddelivery.ang.rpt
--standarddelivery.rpt

/
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, 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, BILLTO_CHAIN, CUSTDELIVERYSCHEME, REPORTPARAM_ID, COPY_NUMBER, PLANTPHONENO, PLANTFAX, PLANTEMAIL, NETPAYMENTDAYS)
as SELECT A.INVOICEDATE STATEMENTDATE, A.INVOICENUMBER STATEMENTNUMBER, E.CODE INVOICEBUSINESSUNITCODE, E.DESCRIPTION INVOICEBUSINESSUNITDESC,
A.BILLTOCUSTOMERNUMBER, A.BILLTOCUSTOMERNAME, A.DELTOCUSTOMERNUMBER, A.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.CONTACTPERSONNAME, A.CONTACTPERSONPHONE,
A.EMAILSTATUS, A.EMAILADDRESS, A.REALCOLLECTIONTYPE, A.ORIGINALCOLLECTIONTYPE, A.EXPORTED,
A.INVOICECOMMENTS STATEMENTCOMMENTS, A.PREBILLAMOUNT, A.INVOICEFREQUENCY_ID STATEMENTFREQUENCYNUMBER,
 B.CODE CURRENCYCODE, B.DESCRIPTION CURRENCYDESC,
S.STATUSTYPE, S.CODE STATUSCODE, S.FACTORYDESCRIPTION STATUSFACTORYDESCRIPTION,
C.COUNTYTAXRATE, C.CITYTAXRATE, C.STATESTAXRATE,
P.CODE PLANTCODE, P.NAME PLANTNAME, X.STREET PLANTSTREET,X.STREET2 PLANTSTREET2, X.ZIPCODE PLANTZIPCODE,
X.CITY PLANTCITY, X.STATE PLANTSTATE, X.COUNTY PLANTCOUNTY, A.PURCHASEORDER, A.ROUTENUMBER,
A.SYSTEMUSER_ID, A.TIMESTAMP, A.INVOICEHEADER_ID STATEMENTHEADER_ID,
F_GetArAgingAmount(a.billtocustomer_link_id, REPORTPARAM.Number_Value2, 0, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4), null, a.invoiceheader_id) DAYS0,
F_GetArAgingAmount(a.billtocustomer_link_id, REPORTPARAM.Number_Value2, 1, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4), null, a.invoiceheader_id) DAYS30,
F_GetArAgingAmount(a.billtocustomer_link_id, REPORTPARAM.Number_Value2, 2, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4), null, a.invoiceheader_id)  DAYS60,
F_GetArAgingAmount(a.billtocustomer_link_id, REPORTPARAM.Number_Value2, 3, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4), null, a.invoiceheader_id)  DAYS90,
F_GetArAgingAmount(a.billtocustomer_link_id, REPORTPARAM.Number_Value2, 4, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4), null, a.invoiceheader_id)  DAYS120,
F_PREVIOUSSTATEMENT( A.INVOICEDATE, A.BILLTOCUSTOMERNUMBER, A.DELTOCUSTOMERNUMBER) PREVIOUSBALANCE,
--Z.CODE STATEMENTLAYOUTCODE,
IHE.FORMLAYOUTCODE STATEMENTLAYOUTCODE,
(SELECT CHAIN.CODE
        FROM CHAIN, CUSTOMER
        WHERE CHAIN.CHAIN_ID = CUSTOMER.CHAIN_ID AND
              CUSTOMER.CUSTOMER_ID = A.BILLTOCUSTOMER_LINK_ID) BILLTO_CHAIN
, CAST(FSGET_CUST_DELIVERY_DAYS(A.BILLTOCUSTOMER_LINK_ID) AS VARCHAR2(7)) CUSTDELIVERYSCHEME
, REPORTPARAM.REPORTPARAM_ID, REPORTPARAM.COPY_NUMBER
, P.PHONENO PLANTPHONENO, P.FAXNO PLANTFAX, P.EMAIL PLANTEMAIL, A.NETPAYMENTDAYS
FROM INVOICEHEADER A
LEFT OUTER JOIN INVOICEHEADERUS C ON (A.INVOICEHEADER_ID = C.INVOICEHEADER_ID)
,CURRENCY B,BUSINESSUNIT E, STATUS S, PLANT P, ADDRESS X
--, CUSTOMER_LINK W, CUSTOMERBILLINGINFO Y, FORMLAYOUT Z
, INVOICEHEADEREXTRAINFO IHE
, REPORTPARAM
WHERE A.CURRENCY_ID = B.CURRENCY_ID
AND A.DOCUMENTTYPE = 2
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 A.BILLTOCUSTOMER_LINK_ID = W.CUSTOMER_LINK_ID
--AND W.CUSTOMER_ID = Y.CUSTOMER_ID
--AND Y.STATEMENTLAYOUT_ID = Z.FORMLAYOUT_ID
AND A.INVOICEHEADER_ID = IHE.INVOICEHEADER_ID
AND REPORTPARAM.NUMBER_VALUE = A.INVOICENUMBER
AND REPORTPARAM.COPY_NUMBER = 0

/
create or replace view V_STATEMENTHEADER_ARW
 (STATEMENTDATE, STATEMENTNUMBER, INVOICEBUSINESSUNITCODE, INVOICEBUSINESSUNITDESC, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, EXTRANAME1, EXTRANAME2, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, STARTYEAR, ENDYEAR, CITY, COUNTY, STATE, ZIPCODE, STREET2, STREET, CONTACTPERSONNAME, CONTACTPERSONPHONE, EMAILSTATUS, EMAILADDRESS, REALCOLLECTIONTYPE, ORIGINALCOLLECTIONTYPE, EXPORTED, STATEMENTCOMMENTS, PREBILLAMOUNT, STATEMENTFREQUENCYNUMBER, PLANTCODE
, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PLANTFAX, PLANTEMAIL, PURCHASEORDER, ROUTENUMBER, STATEMENTHEADER_ID, DAYS0, DAYS30, DAYS60, DAYS90, DAYS120, PREVIOUSBALANCE, BILLTO_CHAIN, REPORTPARAM_ID, COPY_NUMBER, PLANTCONTACT, PERSONIDENTIFICATION)
as select a.invoicedate statementdate, a.invoicenumber statementnumber, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
a.billtocustomernumber, a.billtocustomername, a.deltocustomernumber, a.deltocustomername, a.extraname1, a.extraname2,
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.contactpersonname, a.contactpersonphone,
a.emailstatus, a.emailaddress, a.realcollectiontype, a.originalcollectiontype, a.exported,
a.invoicecomments statementcomments, a.prebillamount, a.invoicefrequency_id statementfrequencynumber,
--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.email plantemail
, a.purchaseorder, a.routenumber, a.invoiceheader_id statementheader_id,
F_GetArAgingAmount(a.billtocustomer_link_id, REPORTPARAM.Number_Value2, 0, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4), null, a.invoiceheader_id) DAYS0,
F_GetArAgingAmount(a.billtocustomer_link_id, REPORTPARAM.Number_Value2, 1, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4), null, a.invoiceheader_id) DAYS30,
F_GetArAgingAmount(a.billtocustomer_link_id, REPORTPARAM.Number_Value2, 2, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4), null, a.invoiceheader_id)  DAYS60,
F_GetArAgingAmount(a.billtocustomer_link_id, REPORTPARAM.Number_Value2, 3, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4), null, a.invoiceheader_id)  DAYS90,
F_GetArAgingAmount(a.billtocustomer_link_id, REPORTPARAM.Number_Value2, 4, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4), null, a.invoiceheader_id)  DAYS120,/*
F_SDAYS(CASTNUMBERASVARCHAR(a.invoicenumber), 30, 0, GETDATEASVARCHARFIXEDFORMAT(reportparam.date_value1), GETDATEASVARCHARFIXEDFORMAT(reportparam.date_value1)) days0,
F_SDAYS(CASTNUMBERASVARCHAR(a.invoicenumber), 60, 30, GETDATEASVARCHARFIXEDFORMAT(reportparam.date_value2), GETDATEASVARCHARFIXEDFORMAT(reportparam.date_value1)) days30,
F_SDAYS(CASTNUMBERASVARCHAR(a.invoicenumber), 90, 60, GETDATEASVARCHARFIXEDFORMAT(reportparam.date_value3), GETDATEASVARCHARFIXEDFORMAT(reportparam.date_value2)) days60,
F_SDAYS(CASTNUMBERASVARCHAR(a.invoicenumber), 999, 90, GETDATEASVARCHARFIXEDFORMAT(reportparam.date_value4), GETDATEASVARCHARFIXEDFORMAT(reportparam.date_value3)) days90,
F_SDAYS(CASTNUMBERASVARCHAR(a.invoicenumber), 999, 120, GETDATEASVARCHARFIXEDFORMAT(reportparam.date_value4), GETDATEASVARCHARFIXEDFORMAT(reportparam.date_value4)) days120,*/
F_PREVIOUSSTATEMENT( a.invoicedate, a.billtocustomernumber, a.deltocustomernumber) PreviousBalance,
(SELECT CHAIN.CODE FROM CHAIN, CUSTOMER
        WHERE CHAIN.CHAIN_ID = CUSTOMER.CHAIN_ID AND
              CUSTOMER.CUSTOMER_ID = a.billtocustomer_link_id) BILLTO_CHAIN,
reportparam.reportparam_id, reportparam.copy_number
, (select e.name from customer c, customerbillinginfo cb, employee e
where c.customer_id = cb.customer_id and a.billtocustomer_link_id = c.customer_id and cb.collectionresponsible_id = e.employee_id
) PlantContact
, (select ins.personidentification from invoicesignature ins where ins.invoiceheader_id = a.invoiceheader_id) personidentification
from invoiceheader a
--, currency b, status s
, businessunit e, plant p, address x
--, invoiceheaderextrainfo ihe
, reportparam
where --a.currency_id = b.currency_id and
a.documenttype = 2
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 a.invoiceheader_id = ihe.invoiceheader_id
and reportparam.number_value = a.invoicenumber
and reportparam.copy_number = 0

/
create or replace view V_STATEMENTHEADER_HUE
 (STATEMENTDATE, STATEMENTNUMBER, 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
, INVOICEAMOUNTDECIMALS, DECIMALS, STATUSTYPE, STATUSCODE, STATUSFACTORYDESCRIPTION, COUNTYTAXRATE, CITYTAXRATE, STATESTAXRATE, PLANTCODE, PLANTNAME, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PURCHASEORDER, ROUTENUMBER, SYSTEMUSER_ID, TIMESTAMP, STATEMENTHEADER_ID, STATEMENTLAYOUTCODE, ARAGINGMETHOD)
as select a.invoicedate statementdate, a.invoicenumber statementnumber, e.code invoicebusinessunitcode,
      e.description invoicebusinessunitdesc,
      a.billtocustomernumber, a.billtocustomername, a.deltocustomernumber, a.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.contactpersonname, a.contactpersonphone,
      a.emailstatus, a.emailaddress, a.realcollectiontype, a.originalcollectiontype, a.exported,
      a.invoicecomments statementcomments, a.prebillamount, a.invoicefrequency_id statementfrequencynumber,
       b.code currencycode, b.description currencydesc, b.invoiceamountdecimals, b.decimals,
      s.statustype, s.code statuscode, s.factorydescription statusfactorydescription,
      c.countytaxrate, c.citytaxrate, c.statestaxrate,
      p.code plantcode, p.name plantname, x.street plantstreet,x.street2 plantstreet2, x.zipcode plantzipcode,
      x.city plantcity, x.state plantstate, x.county plantcounty, a.purchaseorder, a.routenumber,
      a.systemuser_id, a.timestamp, a.invoiceheader_id statementheader_id
      --, z.code statementlayoutcode
      , ihe.formlayoutcode statementlayoutcode
      , (select ss.value from systemsetting ss where ss.plant_id = e.plant_id and SS.NAME = 'ARAGINGMETHOD') ARAGINGMETHOD
from invoiceheader a LEFT OUTER JOIN invoiceheaderus c ON (a.invoiceheader_id = c.invoiceheader_id)
     , currency b, businessunit e, status s, plant p, address x
     --, customer_link w, customerbillinginfo y, formlayout z
     , invoiceheaderextrainfo ihe
where a.currency_id = b.currency_id
      and a.documenttype = 2
      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 a.billtocustomer_link_id = w.customer_link_id
      --and w.customer_id = y.customer_id
      --and y.statementlayout_id = z.formlayout_id
      and a.invoiceheader_id = ihe.invoiceheader_id

/
create or replace view V_STATEMENTHEADER_LEE
 (STATEMENTDATE, STATEMENTNUMBER, 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, PLANTCODE, PLANTNAME, PLANTSTREET
, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, PLANTPHONE, PURCHASEORDER, ROUTENUMBER, STATEMENTHEADER_ID, DAYS0, DAYS30, DAYS60, DAYS90, DAYS120, BILLTO_CHAIN, REPORTPARAM_ID, COPY_NUMBER)
as select a.invoicedate statementdate, a.invoicenumber statementnumber, e.code invoicebusinessunitcode, e.description invoicebusinessunitdesc,
a.billtocustomernumber, a.billtocustomername, a.deltocustomernumber, a.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.contactpersonname, a.contactpersonphone,
a.emailstatus, a.emailaddress, a.realcollectiontype, a.originalcollectiontype, a.exported,
a.invoicecomments statementcomments, a.prebillamount, a.invoicefrequency_id statementfrequencynumber,
--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, a.purchaseorder, a.routenumber,
a.invoiceheader_id statementheader_id,
F_GetArAgingAmount(a.billtocustomer_link_id, REPORTPARAM.Number_Value2, 0, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4), null, a.invoiceheader_id) DAYS0,
F_GetArAgingAmount(a.billtocustomer_link_id, REPORTPARAM.Number_Value2, 1, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4), null, a.invoiceheader_id) DAYS30,
F_GetArAgingAmount(a.billtocustomer_link_id, REPORTPARAM.Number_Value2, 2, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4), null, a.invoiceheader_id)  DAYS60,
F_GetArAgingAmount(a.billtocustomer_link_id, REPORTPARAM.Number_Value2, 3, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4), null, a.invoiceheader_id)  DAYS90,
F_GetArAgingAmount(a.billtocustomer_link_id, REPORTPARAM.Number_Value2, 4, GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE1), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE2), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE3), GETDATEASVARCHARFIXEDFORMAT(REPORTPARAM.DATE_VALUE4), null, a.invoiceheader_id)  DAYS120,/*
F_SDAYS(CASTNUMBERASVARCHAR(a.invoicenumber), 30, 0, GETDATEASVARCHARFIXEDFORMAT(reportparam.date_value1), GETDATEASVARCHARFIXEDFORMAT(reportparam.date_value1)) days0,
F_SDAYS(CASTNUMBERASVARCHAR(a.invoicenumber), 60, 30, GETDATEASVARCHARFIXEDFORMAT(reportparam.date_value2), GETDATEASVARCHARFIXEDFORMAT(reportparam.date_value1)) days30,
F_SDAYS(CASTNUMBERASVARCHAR(a.invoicenumber), 90, 60, GETDATEASVARCHARFIXEDFORMAT(reportparam.date_value3), GETDATEASVARCHARFIXEDFORMAT(reportparam.date_value2)) days60,
F_SDAYS(CASTNUMBERASVARCHAR(a.invoicenumber), 999, 90, GETDATEASVARCHARFIXEDFORMAT(reportparam.date_value4), GETDATEASVARCHARFIXEDFORMAT(reportparam.date_value3)) days90,*/
(SELECT CHAIN.CODE FROM CHAIN, CUSTOMER
        WHERE CHAIN.CHAIN_ID = CUSTOMER.CHAIN_ID AND
              CUSTOMER.CUSTOMER_ID = a.billtocustomer_link_id) BILLTO_CHAIN,
reportparam.reportparam_id, reportparam.copy_number
from invoiceheader a
--, currency b, status s
, businessunit e, plant p, address x
--, invoiceheaderextrainfo ihe
, reportparam
where --a.currency_id = b.currency_id and
a.documenttype = 2
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 a.invoiceheader_id = ihe.invoiceheader_id
and reportparam.number_value = a.invoicenumber
and reportparam.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)
as select f.invoicedate, f.invoicenumber statementnumber, e.type invoicelinetype,
a.transactiontype_id, x.typenumber transactiontypenumber, x.code transactiontypecode,
a.transactionreference, a.transactiondate, a.debitcredit, a.amount,
a.percentage,a.systemuser_id, a.timestamp, a.statementline_id, a.invoiceheader_id statementheader_id
from statementline a
--LEFT OUTER JOIN customer_link c ON (a.deltocustomer_link_id = c.customer_link_id)
LEFT OUTER JOIN artransactiontype x ON (a.transactiontype_id = x.artransactiontype_id),
 invoicelinetype e, invoiceheader f
where a.invoicelinetype_id = e.invoicelinetype_id
and a.invoiceheader_id = f.invoiceheader_id
and f.documenttype = 2

/
create or replace view V_STATEMENTLINE_AMM
 (INVOICEDATE, STATEMENTNUMBER, INVOICELINETYPE, TRANSACTIONTYPE_ID, TRANSACTIONTYPENUMBER, TRANSACTIONTYPECODE, TRANSACTIONREFERENCE, TRANSACTIONDATE, DEBITCREDIT, AMOUNT, PERCENTAGE, SYSTEMUSER_ID, TIMESTAMP, STATEMENTLINE_ID, STATEMENTHEADER_ID, ARTRANSACTIONTYPE_DESC, DELTO_LEGACYNUMBER, DELTO_CUSTOMERNUMBER, STREET, STREET2, CITY, STATE, ZIPCODE, INVOICEHEADER_ID)
as SELECT F.INVOICEDATE, F.INVOICENUMBER STATEMENTNUMBER, E.TYPE INVOICELINETYPE,
A.TRANSACTIONTYPE_ID, X.TYPENUMBER TRANSACTIONTYPENUMBER, X.CODE TRANSACTIONTYPECODE,
case when A.TRANSACTIONTYPE_ID in (46, 48) then A.TRANSACTIONREFERENCE||'U'
     else A.TRANSACTIONREFERENCE
end as TRANSACTIONREFERENCE,
A.TRANSACTIONDATE, A.DEBITCREDIT, A.AMOUNT,
A.PERCENTAGE,A.SYSTEMUSER_ID, A.TIMESTAMP, A.STATEMENTLINE_ID, A.INVOICEHEADER_ID STATEMENTHEADER_ID
--changed the following for Misapplied to Customer transactions
, (SELECT case when A.TRANSACTIONTYPE_ID in (46, 48) and bill.language_id = 1 then 'Invoice'
             when A.TRANSACTIONTYPE_ID in (46, 48) and bill.language_id = 21 then 'Facture'
             else Y.DESCRIPTION
        end
 FROM ARTRANSACTIONTYPE_DESC Y, CUSTOMER BILL
 WHERE A.TRANSACTIONTYPE_ID = Y.ARTRANSACTIONTYPE_ID AND BILL.CUSTOMER_ID = F.BILLTOCUSTOMER_LINK_ID AND BILL.LANGUAGE_ID = Y.LANGUAGE_ID
) ARTRANSACTIONTYPE_DESC
, C.LEGACYCUSTOMERNUMBER DELTO_LEGACYNUMBER
, C.CUSTOMERNUMBER DELTO_CUSTOMERNUMBER
,(SELECT A.STREET FROM ADDRESS A WHERE
 A.ADDRESS_ID = (SELECT CU.VISITADDRESS_ID FROM CUSTOMER CU WHERE
 CU.CUSTOMER_ID=NVL(C.CUSTOMER_ID,F.BILLTOCUSTOMER_LINK_ID))) STREET,
(SELECT A.STREET2 FROM ADDRESS A WHERE
 A.ADDRESS_ID = (SELECT CU.VISITADDRESS_ID FROM CUSTOMER CU WHERE
 CU.CUSTOMER_ID=NVL(C.CUSTOMER_ID,F.BILLTOCUSTOMER_LINK_ID))) STREET2,
(SELECT A.CITY FROM ADDRESS A WHERE
 A.ADDRESS_ID = (SELECT CU.VISITADDRESS_ID FROM CUSTOMER CU WHERE
 CU.CUSTOMER_ID=NVL(C.CUSTOMER_ID,F.BILLTOCUSTOMER_LINK_ID))) CITY,
(SELECT A.STATE FROM ADDRESS A WHERE
 A.ADDRESS_ID = (SELECT CU.VISITADDRESS_ID FROM CUSTOMER CU WHERE
 CU.CUSTOMER_ID=NVL(C.CUSTOMER_ID,F.BILLTOCUSTOMER_LINK_ID))) STATE,
(SELECT A.ZIPCODE FROM ADDRESS A WHERE
 A.ADDRESS_ID = (SELECT CU.VISITADDRESS_ID FROM CUSTOMER CU WHERE
 CU.CUSTOMER_ID=NVL(C.CUSTOMER_ID,F.BILLTOCUSTOMER_LINK_ID))) ZIPCODE,
 case when X.TYPENUMBER = 1 then f.invoiceheader_id
      end as invoiceheader_id
FROM STATEMENTLINE A
LEFT OUTER JOIN CUSTOMER_LINK C ON (A.DELTOCUSTOMER_LINK_ID = C.CUSTOMER_LINK_ID)
LEFT OUTER JOIN ARTRANSACTIONTYPE X ON (A.TRANSACTIONTYPE_ID = X.ARTRANSACTIONTYPE_ID),
 INVOICELINETYPE E, INVOICEHEADER F
WHERE A.INVOICELINETYPE_ID = E.INVOICELINETYPE_ID
AND A.INVOICEHEADER_ID = F.INVOICEHEADER_ID
AND F.DOCUMENTTYPE = 2

/
create or replace view V_STATEMENTLINE_ARW
 (TRANSACTIONTYPE_ID, TRANSACTIONTYPENUMBER, TRANSACTIONTYPECODE, FACTORYDESCRIPTION, TRANSACTIONREFERENCE, TRANSACTIONDATE, DEBITCREDIT, AMOUNT, PERCENTAGE, SYSTEMUSER_ID, TIMESTAMP, STATEMENTLINE_ID, STATEMENTHEADER_ID, DELTO_NAME, FINANCECHARGEPUTON, FINANCECHARGEDAYS)
as select --f.invoicedate, f.invoicenumber statementnumber, --e.type invoicelinetype,
a.transactiontype_id, x.typenumber transactiontypenumber, x.code transactiontypecode, x.factorydescription,
a.transactionreference, a.transactiondate, a.debitcredit, a.amount,
a.percentage, a.systemuser_id, a.timestamp, a.statementline_id, a.invoiceheader_id statementheader_id
, del.name DelTo_name
, cb.financechargeputon, cb.financechargedays
from --invoiceheader f,
statementline a
--LEFT OUTER JOIN customer_link c ON (a.deltocustomer_link_id = c.customer_link_id)
LEFT OUTER JOIN artransactiontype x ON a.transactiontype_id = x.artransactiontype_id
LEFT OUTER JOIN customer del join customerbillinginfo cb
                             ON del.customer_id = cb.customer_id
ON a.deltocustomer_link_id = del.customer_id
 --invoicelinetype e,
--where a.invoicelinetype_id = e.invoicelinetype_id and
--a.invoiceheader_id = f.invoiceheader_id
--and f.documenttype = 2

/
create or replace view V_STATEMENTLINE_HUE
 (INVOICEDATE, STATEMENTNUMBER, INVOICELINETYPE, TRANSACTIONTYPE_ID, TRANSACTIONTYPENUMBER, TRANSACTIONTYPECODE, TRANSACTIONREFERENCE, TRANSACTIONDATE, DEBITCREDIT, AMOUNT, PERCENTAGE, SYSTEMUSER_ID, TIMESTAMP, STATEMENTLINE_ID, STATEMENTHEADER_ID, DELTO_CUSTOMERNUMBER, DELTO_CUSTOMERNAME)
as select f.invoicedate, f.invoicenumber statementnumber, e.type invoicelinetype,
       a.transactiontype_id, x.typenumber transactiontypenumber, x.code transactiontypecode,
       a.transactionreference, a.transactiondate, a.debitcredit, a.amount,
       a.percentage, a.systemuser_id, a.timestamp, a.statementline_id, a.invoiceheader_id statementheader_id
       , c.customernumber delto_customernumber, c.name delto_customername
from statementline a
        LEFT OUTER JOIN customer_link c ON (a.deltocustomer_link_id = c.customer_link_id)
        LEFT OUTER JOIN artransactiontype x ON (a.transactiontype_id = x.artransactiontype_id),
     invoicelinetype e, invoiceheader f
where a.invoicelinetype_id = e.invoicelinetype_id
      and a.invoiceheader_id = f.invoiceheader_id
      and f.documenttype = 2

/
create or replace view V_STATEMENTLINE_LEE
 (TRANSACTIONTYPE_ID, TRANSACTIONREFERENCE, TRANSACTIONDATE, DEBITCREDIT, AMOUNT, PERCENTAGE, SYSTEMUSER_ID, TIMESTAMP, STATEMENTLINE_ID, STATEMENTHEADER_ID)
as select --f.invoicedate, f.invoicenumber statementnumber, --e.type invoicelinetype,
a.transactiontype_id, --x.typenumber transactiontypenumber, x.code transactiontypecode,
a.transactionreference, a.transactiondate, a.debitcredit, a.amount,
a.percentage, a.systemuser_id, a.timestamp, a.statementline_id, a.invoiceheader_id statementheader_id
from --invoiceheader f,
statementline a
--LEFT OUTER JOIN customer_link c ON (a.deltocustomer_link_id = c.customer_link_id)
--LEFT OUTER JOIN artransactiontype x ON a.transactiontype_id = x.artransactiontype_id
 --invoicelinetype e,
--where a.invoicelinetype_id = e.invoicelinetype_id and
--a.invoiceheader_id = f.invoiceheader_id
--and f.documenttype = 2

/
create or replace view V_STATEMENTLINE_WMU
 (INVOICEDATE, STATEMENTNUMBER, INVOICELINETYPE, TRANSACTIONTYPE_ID, TRANSACTIONTYPENUMBER, TRANSACTIONTYPECODE, TRANSACTIONREFERENCE, TRANSACTIONDATE, DEBITCREDIT, AMOUNT, PERCENTAGE, SYSTEMUSER_ID, TIMESTAMP, STATEMENTLINE_ID, STATEMENTHEADER_ID, REPORTPARAM_ID, CUSTOMERNUMBER, NAME, BILLED, PAID)
as select f.invoicedate, f.invoicenumber statementnumber, e.type invoicelinetype,
a.transactiontype_id, x.typenumber transactiontypenumber, x.code transactiontypecode,
a.transactionreference, a.transactiondate, a.debitcredit, a.amount,
a.percentage,a.systemuser_id, a.timestamp, a.statementline_id, a.invoiceheader_id statementheader_id, rp.reportparam_id,
c.customernumber , c.name
, coalesce(y.amount, 0) Billed, coalesce(y.totalappliedamount - coalesce((select sum(c.amount) from cashapplication c
where c.creditartransaction_id = y.artransaction_id and x.typenumber=4 and y.debitcredit = 'C'), 0)--discount
, 0) Paid
from statementline a
LEFT OUTER JOIN customer_link c ON (a.deltocustomer_link_id = c.customer_link_id)
LEFT OUTER JOIN artransactiontype x ON (a.transactiontype_id = x.artransactiontype_id)
LEFT OUTER JOIN artransaction y ON y.artransaction_id = a.artransaction_id,
 invoicelinetype e, invoiceheader f, reportparam rp
where a.invoicelinetype_id = e.invoicelinetype_id
and a.invoiceheader_id = f.invoiceheader_id
and f.documenttype = 2
and rp.number_value = f.invoicenumber

/
create or replace view V_STATEMENT_OUTSTINV_ARW
 (TRANSACTIONREFERENCE, INVOICEHEADER_ID, AMOUNT)
as select sl.transactionreference, sl.invoiceheader_id, sl.amount
from statementline sl, artransactiontype artt
where sl.transactiontype_id = artt.artransactiontype_id and
sl.debitcredit = 'D' and artt.typenumber in (1,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 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 outer join reasoncode rc on ri.reasoncode_id = rc.reasoncode_id
, weareremployment_link wel, distributionpoint_link dpl
, department_link dl, customer_link cl
, product p, productgroup pg, supplier su, fabric fa, ragreason rr
, languages l, sizedefinition_link sdl
where dl.customer_link_id=cl.customer_link_id
and dpl.department_link_id=dl.department_link_id
and wel.distributionpoint_link_id=dpl.distributionpoint_link_id
and ri.weareremployment_link_id=wel.weareremployment_link_id
and ri.supplier_id=su.supplier_id and ri.product_link_id=p.product_id
and p.productgroup_id=pg.productgroup_id and p.fabric_id=fa.fabric_id
and ri.ragreason_id=rr.ragreason_id
and ri.sizedefinition_link_id=sdl.sizedefinition_link_id
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 outer join reasoncode rc on ri.reasoncode_id = rc.reasoncode_id
, weareremployment_link wel2, distributionpoint_link dpl2
, department_link dl2, customer_link cl2
, product p, productgroup pg, supplier su, fabric fa, ragreason rr
, languages l, sizedefinition_link sdl
where dl2.customer_link_id=cl2.customer_link_id
and dpl2.department_link_id=dl2.department_link_id
and wel2.distributionpoint_link_id=dpl2.distributionpoint_link_id
and ri.lastweareremployment_link_id=wel2.weareremployment_link_id
and ri.weareremployment_link_id is null
and ri.supplier_id=su.supplier_id and ri.product_link_id=p.product_id
and p.productgroup_id=pg.productgroup_id and p.fabric_id=fa.fabric_id
and ri.ragreason_id=rr.ragreason_id
and ri.sizedefinition_link_id=sdl.sizedefinition_link_id
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 outer join reasoncode rc on ri.reasoncode_id = rc.reasoncode_id
, distributionpoint_link dpl3
, department_link dl3, customer_link cl3
, product p, productgroup pg, supplier su, fabric fa, ragreason rr
, languages l, sizedefinition_link sdl
where dl3.customer_link_id=cl3.customer_link_id
and dpl3.department_link_id=dl3.department_link_id
and ri.distributionpoint_link_id=dpl3.distributionpoint_link_id
and ri.lastweareremployment_link_id is null
and ri.weareremployment_link_id is null
and ri.supplier_id=su.supplier_id and ri.product_link_id=p.product_id
and p.productgroup_id=pg.productgroup_id and p.fabric_id=fa.fabric_id
and ri.ragreason_id=rr.ragreason_id
and ri.sizedefinition_link_id=sdl.sizedefinition_link_id
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 outer join reasoncode rc on ri.reasoncode_id = rc.reasoncode_id
, distributionpoint_link dpl4
, department_link dl4, customer_link cl4
, product p, productgroup pg, supplier su, fabric fa, ragreason rr
, languages l, sizedefinition_link sdl
where dl4.customer_link_id=cl4.customer_link_id
and dpl4.department_link_id=dl4.department_link_id
and ri.lastdistributionpoint_link_id=dpl4.distributionpoint_link_id
and ri.distributionpoint_link_id is null
and ri.lastweareremployment_link_id is null
and ri.weareremployment_link_id is null
and ri.supplier_id=su.supplier_id and ri.product_link_id=p.product_id
and p.productgroup_id=pg.productgroup_id and p.fabric_id=fa.fabric_id
and ri.ragreason_id=rr.ragreason_id
and ri.sizedefinition_link_id=sdl.sizedefinition_link_id
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
, 0 customernumber, ' ' 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 outer join reasoncode rc on ri.reasoncode_id = rc.reasoncode_id
, product p, productgroup pg, supplier su, fabric fa, ragreason rr
, languages l, sizedefinition_link sdl
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
and ri.supplier_id=su.supplier_id and ri.product_link_id=p.product_id
and p.productgroup_id=pg.productgroup_id and p.fabric_id=fa.fabric_id
and ri.ragreason_id=rr.ragreason_id
and ri.sizedefinition_link_id=sdl.sizedefinition_link_id

/
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, CARTDESC, PRIMARYID_CHR, PRIMARYID, PRODUCTCODE, PRODUCTDESC, STERILIZATIONRUN_ID, STERILIZERCODE, STERILIZERDESC, TREATMENTTYPE_ID, TREATMENT_CODE, TREATMENT_DESC, EMPLOYEENUMBER, EMPLOYEENAME, CHARGENUMBER, TIMESTAMP, SR_TIMESTAMP, REJECTREASONCODE_ID, BUSINESSUNIT_ID, BUCODE, BUDESC, REJECTREASONCODE, REJECTRC_DESC, LANGUAGECODE)
as select cuid.primaryid cartid,
       crt.cartnumber,
       to_char(crt.cartnumber) chr_cartnr,
			 (select ctd.description
			  from carttype ct, carttype_desc ctd
				where crt.carttype_id = ct.carttype_id and ct.carttype_id = ctd.carttype_id and ctd.language_id = languages.language_id) cartdesc,
       F_GetIDforSterilizationRun(ups.sterilizationrun_id,pr.product_id) primaryid_chr, ui.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,
       ups.sterilizationrun_id,
			 st.code sterilizercode,
			 st.description sterilizerdesc,
			 tt.treatmenttype_id,
			 tt.code treatment_code,
			 (select tt_d.description from treatmenttype_desc tt_d where tt.treatmenttype_id = tt_d.treatmenttype_id and tt_d.language_id = languages.language_id) treatment_desc,
			 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,
			 (select rc.code from reasoncode rc where sr.rejectreasoncode_id = rc.reasoncode_id) rejectreasoncode,
			 (select rcd.description from reasoncode rc, reasoncode_desc rcd where sr.rejectreasoncode_id = rc.reasoncode_id and rc.reasoncode_id = rcd.reasoncode_id and rcd.language_id = languages.language_id) rejectrc_desc,
			 languages.code languagecode
from uniqueitem ui, uniqueorpacksterile ups, product pr, languages, sterilizationrun sr, sterilizer st, treatmenttype tt, employee em, businessunit bu,
     cart crt left outer join cartuniqueid cuid on crt.cart_id = cuid.cart_id
where ui.uniqueitem_id = ups.uniqueitem_id
      and ups.cart_id = crt.cart_id
			and ui.product_id = pr.product_id
			and ups.sterilizationrun_id = sr.sterilizationrun_id
			and sr.sterilizer_id = st.sterilizer_id
			and sr.treatmenttype_id = tt.treatmenttype_id
			and sr.employee_id = em.employee_id
			and sr.businessunit_id = bu.businessunit_id

/
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_STOCKCHANGES_LLG
 (ROUTENR, NOTENUMBER, DELIVERYDATE, BU_CODE, CUSTOMERNUMBER, CUSTOMERNAME, CLUSTER_CODE, PG_CODE, PRODUCTCODE, PRODUCTDESC, SIZECODE, FABRICCODE, FMCODE, QUANTITY, EFFECTIVEDATE, CHANGEDATE, RC_CODE, SAMPLEITEM, ORIGIN, LANGUAGECODE, PLPC_BM, PLPC_CHARGEEXCESS, PACK_REF, DV_REMARK)
as select cast(substr(to_char((select r.routenumber from route r where r.route_id = pn.route_id)),-2)  as varchar2(2)) routenr,
       pn.notenumber,
       pn.deliverydate,
       (select bu.code from businessunit bu where bu.businessunit_id = pn.processbusinessunit_id) bu_code,
       c.customernumber,
       c.name customername,
       (select cc.code from customerspercluster cpc, customercluster cc
               where cpc.cluster_id = cc.cluster_id
               and cpc.customer_id = c.customer_id) cluster_code,
       (select pg.code from productgroup pg where pg.productgroup_id = p.productgroup_id) pg_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,
       (select f.code from fabric f where f.fabric_id = p.fabric_id) fabriccode,
       fm.code fmcode,
       SUM(rqa.quantity) quantity,
       rqa.adjustmentdate effectivedate,
       rqa.timestamp changedate,
       (select rc.code from reasoncode rc where rc.reasoncode_id = rqa.reasoncode_id) rc_code,
       rqa.sampleitem,
       rqa.origin,
       l.code languagecode,
       (select plpc.billingmethod from productlistpercustomer plpc where plpc.product_id = dv.product_id
        and plpc.sizedefinition_id = dv.sizedefinition_id
        and plpc.finishingmethod_id = dv.finishingmethod_id
        and plpc.customer_id = c.customer_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')) plpc_bm,
       (select plpc.chargeexcess from productlistpercustomer plpc where plpc.product_id = dv.product_id
        and plpc.sizedefinition_id = dv.sizedefinition_id
        and plpc.finishingmethod_id = dv.finishingmethod_id
        and plpc.customer_id = c.customer_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')) plpc_chargeexcess,
        (select cn.consignmentnotenumber from consignmentnote cn where cn.consignmentnote_id = pn.consignmentnote_id) pack_ref,
        dv.reference dv_remark
  from packingnote pn,
       department          d,
       distributionpoint   dp,
       customer            c,
       rentalqtyadjustment rqa,
       deliveryvariations  dv,
       product             p,
       sizedefinition      sd,
       finishingmethod     fm,
       languages           l
 where pn.distributionpoint_id = dp.distributionpoint_id
   and dp.department_id = d.department_id
   and d.customer_id = c.customer_id
   and pn.packingnote_id = dv.packingnote_id
   and dv.deliveryvariations_id = rqa.deliveryvariations_id
   and dv.product_id = p.product_id
   and dv.sizedefinition_id = sd.sizedefinition_id
   and dv.finishingmethod_id = fm.finishingmethod_id
   group by pn.route_id, c.customer_id, c.customernumber, c.name, pn.consignmentnote_id, pn.notenumber, pn.deliverydate, pn.processbusinessunit_id,
   p.productgroup_id, dv.product_id, p.product_id, p.code, p.fabric_id, dv.sizedefinition_id, sd.code, dv.finishingmethod_id, fm.code, rqa.reasoncode_id, rqa.adjustmentdate, rqa.timestamp, rqa.sampleitem,
   rqa.origin, l.language_id, l.code,  dv.reference
union
select '' routenr,
       null,
       rqa.adjustmentdate,
       (select bu.code from businessunit bu where bu.businessunit_id = c.defaultbusinessunit_id) bu_code,
       c.customernumber,
       c.name customername,
       (select cc.code from customerspercluster cpc, customercluster cc
              where cpc.cluster_id = cc.cluster_id
              and cpc.customer_id = c.customer_id) cluster_code,
       (select pg.code from productgroup pg where pg.productgroup_id = p.productgroup_id) pg_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,
       (select f.code from fabric f where f.fabric_id = p.fabric_id) fabriccode,
       fm.code fmcode,
       SUM(rqa.quantity) quantity,
       rqa.adjustmentdate effectivedate,
       rqa.timestamp changedate,
       (select rc.code from reasoncode rc where rc.reasoncode_id = rqa.reasoncode_id) rc_code,
       rqa.sampleitem,
       rqa.origin,
       l.code languagecode,
       (select plpc.billingmethod 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
        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')) plpc_bm,
       (select plpc.chargeexcess 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
        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')) plpc_chargeexcess,
        null pack_ref,
        null dv_remark
  from department          d,
       distributionpoint   dp,
       customer            c,
       productlistperdistribpoint plpd,
       rentalqtyadjustment rqa,
       product             p,
       sizedefinition      sd,
       finishingmethod     fm,
       languages           l
 where plpd.distributionpoint_id = dp.distributionpoint_id
   and dp.department_id = d.department_id
   and d.customer_id = c.customer_id
   and rqa.deliveryvariations_id is null
   and plpd.productlistperdistribpoint_id = rqa.productlistperdistribpoint_id
   and plpd.product_id = p.product_id
   and plpd.sizedefinition_id = sd.sizedefinition_id
   and plpd.finishingmethod_id = fm.finishingmethod_id
   group by c.defaultbusinessunit_id, c.customer_id, c.customernumber, c.name, p.productgroup_id, plpd.product_id, p.product_id, p.code,
   p.fabric_id, plpd.sizedefinition_id, sd.code, plpd.finishingmethod_id, fm.code,rqa.adjustmentdate, rqa.timestamp, rqa.reasoncode_id, rqa.sampleitem, rqa.origin, l.language_id, l.code

/
create or replace view V_STOCKCORRECTION
 (STOCKCODE, STOCKNAME, MANAGEDBYBU_ID, ROWCODE, LOCATIONCODE, CYCLECOUNTGROUP, PICKINGSEQUENCE, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMEROWNED, CUSTOMERRELATED, PRODUCTCODE, SIZECODE, SEQUENCENUMBER, PRODUCTDESC, PRODUCTLONGDESC, SIZEDESC, PRODGRCODE, QUALITYGRADECODE, PRIORITY, QUALITYGRADEDESC, MULTIPLELOCATIONS, QTYSTOCK, QTYCOUNTED, QTYSTOCKDIFF, LANGUAGECODE, DATECOUNTED, SKQTIMESTAMP, SKRESGTIMESTAMP)
as select
  sk.code stockCode, sk.name stockName, sk.managedbybu_id
, skl.rowcode, skl.locationcode, skl.cyclecountgroup, skl.pickingsequence
, cu.customernumber, cu.name customerName, ski.customerowned
, case when ski.customer_id is null then 0 else 1 end customerrelated
, prd.code productCode, sz.code sizeCode
, ps.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
, ( select product_desc.longdescription from product_desc where product_desc.product_id = prd.product_id
  and product_desc.language_id = languages.language_id ) productLongDesc
, ( select sizedefinition_desc.description from sizedefinition_desc where sizedefinition_desc.sizedefinition_id = sz.sizedefinition_id
  and sizedefinition_desc.language_id = languages.language_id ) sizeDesc, pg.code prodgrcode
, qg.code qualitygradeCode, qg.priority
, ( select qualitygrade_desc.description from qualitygrade_desc where qualitygrade_desc.qualitygrade_id = qg.qualitygrade_id
  and qualitygrade_desc.language_id = languages.language_id ) qualitygradeDesc
, coalesce(( select count(stockquantity.stockroomlocation_id) from stockquantity
  where stockquantity.stockreservationpergrade_id = skresg.stockreservationpergrade_id ), 0) MultipleLocations
, ( skq.qtyunique + skq.qtyuniquewithmodifications + skq.qtynonunique) qtyStock
, skq.qtycounted
 --( skq.qtyunique + skq.qtyuniquewithmodifications  + skq.qtynonunique + skresg.qtynonunique - skq.qtycounted ) qtyStockDiff
, skq.stockdifference qtyStockDiff
, languages.code languageCode
, skq.datecounted,  trunc(skq.timestamp) skqtimestamp, trunc(skresg.timestamp) skresgtimestamp--todo5500,8325
from
  stockroom sk, stockroomlocation skl
, stockdefinitionperitem ski
    left outer join customer cu on ski.customer_id = cu.customer_id
, stockreservationpergrade skresg, qualitygrade qg, stockquantity skq
, product prd, sizedefinition sz, productsize ps, productgroup pg
, languages
where
    sk.stockroom_id = skl.stockroom_id
and sk.stockroom_id = ski.stockroom_id
    and ski.product_id = prd.product_id
        and prd.product_id = ps.product_id
            and ps.sizedefinition_id = sz.sizedefinition_id
                and sz.sizedefinition_id = ski.sizedefinition_id
and prd.productgroup_id=pg.productgroup_id
and ski.stockdefinitionperitem_id = skresg.stockdefinitionperitem_id
    and skresg.qualitygrade_id = qg.qualitygrade_id
        and skresg.stockreservationpergrade_id = skq.stockreservationpergrade_id
        and skl.stockroomlocation_id = skq.stockroomlocation_id
 --and (skq.datecounted>= trunc(skq.timestamp)and skq.datecounted>=trunc(skresg.timestamp))--moved inside report todo 8325

/
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, PRODUCTGROUPCODE, PRODUCTCODE, PRODUCTDESCRIPTION, COLORCODE, FABRICODE, SUPPLIERNUMBER, SIZEDEFINITIONCODE, SIZEDEFINITIONDESCRIPTION, GRADE1, GRADE2, GRADE3, PRIORITY, SEQUENCENUMBER, QTYSTOCK, LANGUAGECODE, REPORTPARAM_ID, CIRCINV, STATUSQUODATE)
as select
  stockroom.code stockroomCode, stockroom.name stockroomName, bu.code businessunitCode, bu.description businessunitDesc
, employee.employeenumber, employee.name employeeName , sit.customerowned, cu.customernumber
, (select productgroup.code from productgroup where productgroup.productgroup_id = prd.productgroup_id) productgroupCode
, 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, supplier.suppliernumber, 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
, coalesce((select qd.description from qualitygrade_desc qd where qd.qualitygrade_id = qualitygrade.qualitygrade_id
and qd.language_id = languages.language_id and qualitygrade.priority = 2)
, (select qualitygrade.code from qualitygrade where qualitygrade.priority=2))  Grade1
, coalesce((select qd.description from qualitygrade_desc qd where qd.qualitygrade_id = qualitygrade.qualitygrade_id
and qd.language_id = languages.language_id and qualitygrade.priority = 3)
, (select qualitygrade.code from qualitygrade where qualitygrade.priority=3)) Grade2
, coalesce((select qd.description from qualitygrade_desc qd where qd.qualitygrade_id = qualitygrade.qualitygrade_id
and qd.language_id = languages.language_id and qualitygrade.priority = 4)
, (select qualitygrade.code from qualitygrade where qualitygrade.priority=4)) Grade3
, qualitygrade.priority
, productsize.sequencenumber
,  COALESCE((select sum(stockquantity.qtynonunique) + sum(stockquantity.qtyunique)+ sum(stockquantity.qtyuniquewithmodifications) from  stockquantity
where srg.stockreservationpergrade_id = stockquantity.stockreservationpergrade_id),0)  QtyStock
, languages.code  languageCode
, rp.reportparam_id
, (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 = sizdef.sizedefinition_id
        and sqh.statusquodate = (select max(sqh1.statusquodate) from statusquoheader sqh1
                                 where sqh1.processbusinessunit_id = sqh.processbusinessunit_id and sqh1.statusquotype = 1)) circinv
, (select max(sqh2.statusquodate) from statusquoheader sqh2
   where sqh2.processbusinessunit_id = bu.businessunit_id and sqh2.statusquotype = 1) statusquodate
from
  stockroom, employee, BUSINESSUNIT BU
, stockdefinitionperitem sit left outer join customer cu on sit.customer_id = cu.customer_id
, stockreservationpergrade srg, qualitygrade, product prd, productsize, sizedefinition sizdef
, color, fabric, supplier, languages
, reportparam rp
where
    stockroom.responsibleemployee_id = employee.employee_id
and 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.product_id = productsize.product_id
        and productsize.sizedefinition_id = sizdef.sizedefinition_id
    and prd.color_id = color.color_id
    and prd.fabric_id = fabric.fabric_id
    and prd.supplier_id = supplier.supplier_id
and sit.sizedefinition_id = sizdef.sizedefinition_id
AND stockroom.managedbybu_id = BU.BUSINESSUNIT_ID
and languages.code = rp.string_value AND
    supplier.suppliernumber >= rp.number_value1 AND
    supplier.suppliernumber <= rp.number_value2 AND
    prd.code >= rp.string_value1 AND
    prd.code <= rp.string_value2 AND
    sizdef.code >= rp.string_value3 AND
    sizdef.code <= rp.string_value4 AND
    fabric.code >= rp.string_value5 AND
    fabric.code <= rp.string_value6 AND
    stockroom.code = rp.string_value7 AND
(((rp.number_value = 1) and (sit.customerowned='N') and cu.customernumber is null) or
 ((rp.number_value = 2) and (sit.customerowned = 'N') and (cu.customernumber <= rp.number_value4 and cu.customernumber >= rp.number_value3)) or
 ((rp.number_value = 3) and (sit.customerowned = 'Y') and (cu.customernumber <= rp.number_value4 and cu.customernumber >= rp.number_value3)))

/
create or replace view V_STOCKINVENTORY_AMM
 (STOCKROOMCODE, STOCKROOMNAME, BUSINESSUNITCODE, BUSINESSUNITDESC, EMPLOYEENUMBER, EMPLOYEENAME, CUSTOMEROWNED, CUSTOMERNUMBER, PRODUCTGROUPCODE, PRODUCTCODE, PRODUCTDESCRIPTION, COLORCODE, FABRICODE, SUPPLIERNUMBER, SIZEDEFINITIONCODE, SIZEDEFINITIONDESCRIPTION, GRADE1, GRADE2, GRADE3, PRIORITY, SEQUENCENUMBER, QTYSTOCK, LANGUAGECODE, STATUSQUODATE)
as select
  stockroom.code stockroomCode, stockroom.name stockroomName, bu.code businessunitCode, bu.description businessunitDesc
, employee.employeenumber, employee.name employeeName , sit.customerowned, cu.customernumber
, (select productgroup.code from productgroup where productgroup.productgroup_id = prd.productgroup_id) productgroupCode
, 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, supplier.suppliernumber, 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
, coalesce((select qd.description from qualitygrade_desc qd where qd.qualitygrade_id = qualitygrade.qualitygrade_id
and qd.language_id = languages.language_id and qualitygrade.priority = 2)
, (select qualitygrade.code from qualitygrade where qualitygrade.priority=2))  Grade1
, coalesce((select qd.description from qualitygrade_desc qd where qd.qualitygrade_id = qualitygrade.qualitygrade_id
and qd.language_id = languages.language_id and qualitygrade.priority = 3)
, (select qualitygrade.code from qualitygrade where qualitygrade.priority=3)) Grade2
, coalesce((select qd.description from qualitygrade_desc qd where qd.qualitygrade_id = qualitygrade.qualitygrade_id
and qd.language_id = languages.language_id and qualitygrade.priority = 4)
, (select qualitygrade.code from qualitygrade where qualitygrade.priority=4)) Grade3
, qualitygrade.priority
, productsize.sequencenumber
, COALESCE((select sum(stockquantity.qtynonunique) + sum(stockquantity.qtyunique)+ sum(stockquantity.qtyuniquewithmodifications) from  stockquantity
where srg.stockreservationpergrade_id = stockquantity.stockreservationpergrade_id),0)  QtyStock
, languages.code  languageCode
, (select max(sqh2.statusquodate) from statusquoheader sqh2
   where sqh2.processbusinessunit_id = bu.businessunit_id and sqh2.statusquotype = 1) statusquodate
from
  stockroom, employee, BUSINESSUNIT BU
, stockdefinitionperitem sit left outer join customer cu on sit.customer_id = cu.customer_id
, stockreservationpergrade srg, qualitygrade, product prd, productsize, sizedefinition sizdef
, color, fabric, supplier, languages
where
    stockroom.responsibleemployee_id = employee.employee_id
and 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.product_id = productsize.product_id
        and productsize.sizedefinition_id = sizdef.sizedefinition_id
    and prd.color_id = color.color_id
    and prd.fabric_id = fabric.fabric_id
    and prd.supplier_id = supplier.supplier_id
and sit.sizedefinition_id = sizdef.sizedefinition_id
AND stockroom.managedbybu_id = BU.BUSINESSUNIT_ID

/
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_STOCKINVENTORY_CBD
 (STOCKROOMCODE, STOCKROOMNAME, BUSINESSUNITCODE, BUSINESSUNITDESC, EMPLOYEENUMBER, EMPLOYEENAME, CUSTOMEROWNED, CUSTOMERNUMBER, PRODUCTGROUPCODE, PRODUCTCODE, PRODUCTDESCRIPTION, COLORCODE, FABRICODE, SUPPLIERNUMBER, SIZEDEFINITIONCODE, SIZEDEFINITIONDESCRIPTION, GRADE1, GRADE2, GRADE3, PRIORITY, SEQUENCENUMBER, QTYSTOCK, LANGUAGECODE, CIRCINV, STATUSQUODATE)
as select
  stockroom.code stockroomCode, stockroom.name stockroomName, bu.code businessunitCode, bu.description businessunitDesc
, employee.employeenumber, employee.name employeeName , sit.customerowned, cu.customernumber
, pg.code productgroupCode
, 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, supplier.suppliernumber, 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
, coalesce((select qd.description from qualitygrade_desc qd where qd.qualitygrade_id = qualitygrade.qualitygrade_id
and qd.language_id = languages.language_id and qualitygrade.priority = 2)
, (select qualitygrade.code from qualitygrade where qualitygrade.priority=2))  Grade1
, coalesce((select qd.description from qualitygrade_desc qd where qd.qualitygrade_id = qualitygrade.qualitygrade_id
and qd.language_id = languages.language_id and qualitygrade.priority = 3)
, (select qualitygrade.code from qualitygrade where qualitygrade.priority=3)) Grade2
, coalesce((select qd.description from qualitygrade_desc qd where qd.qualitygrade_id = qualitygrade.qualitygrade_id
and qd.language_id = languages.language_id and qualitygrade.priority = 4)
, (select qualitygrade.code from qualitygrade where qualitygrade.priority=4)) Grade3
, qualitygrade.priority
, productsize.sequencenumber
, COALESCE((select sum(stockquantity.qtynonunique) + sum(stockquantity.qtyunique)+ sum(stockquantity.qtyuniquewithmodifications) from  stockquantity
where srg.stockreservationpergrade_id = stockquantity.stockreservationpergrade_id),0)  QtyStock
, languages.code  languageCode
--, rp.reportparam_id
, (select /*+index(XSPTESTSQITEMCIRC)*/  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 = sizdef.sizedefinition_id
        and sqh.statusquodate = (select max(sqh1.statusquodate) from statusquoheader sqh1
                                 where sqh1.processbusinessunit_id = sqh.processbusinessunit_id and sqh1.statusquotype = 1)) circinv
, (select max(sqh2.statusquodate) from statusquoheader sqh2
   where sqh2.processbusinessunit_id = bu.businessunit_id and sqh2.statusquotype = 1) statusquodate
from
  stockroom, employee, BUSINESSUNIT BU
, stockdefinitionperitem sit left outer join customer cu on sit.customer_id = cu.customer_id
, stockreservationpergrade srg, qualitygrade, product prd, productsize, sizedefinition sizdef
, color, fabric, supplier, languages, productgroup pg
--, reportparam rp
where
    stockroom.responsibleemployee_id = employee.employee_id
and 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.product_id = productsize.product_id
        and productsize.sizedefinition_id = sizdef.sizedefinition_id
    and prd.color_id = color.color_id
    and prd.fabric_id = fabric.fabric_id
    and prd.supplier_id = supplier.supplier_id
and sit.sizedefinition_id = sizdef.sizedefinition_id
AND stockroom.managedbybu_id = BU.BUSINESSUNIT_ID
and pg.productgroup_id=prd.productgroup_id
/*and languages.code = rp.string_value AND
    supplier.suppliernumber >= rp.number_value1 AND
    supplier.suppliernumber <= rp.number_value2 AND
    prd.code >= rp.string_value1 AND
    prd.code <= rp.string_value2 AND
    sizdef.code >= rp.string_value3 AND
    sizdef.code <= rp.string_value4 AND
    fabric.code >= rp.string_value5 AND
    fabric.code <= rp.string_value6 AND
    stockroom.code = rp.string_value7 AND
(((rp.number_value = 1) and (sit.customerowned='N') and cu.customernumber is null) or
 ((rp.number_value = 2) and (sit.customerowned = 'N') and (cu.customernumber <= rp.number_value4 and cu.customernumber >= rp.number_value3)) or
 ((rp.number_value = 3) and (sit.customerowned = 'Y') and (cu.customernumber <= rp.number_value4 and cu.customernumber >= rp.number_value3)))
 */

/
create or replace view V_STOCKINVENTORY_DFD
 (STOCKROOMCODE, STOCKROOMNAME, BUSINESSUNITCODE, BUSINESSUNITDESC, EMPLOYEENUMBER, EMPLOYEENAME, CUSTOMEROWNED, CUSTOMERNUMBER, PRODUCTGROUPCODE, PRODUCTCODE, PRODUCTDESCRIPTION, COLORCODE, FABRICODE, SUPPLIERNUMBER, SIZEDEFINITIONCODE, SIZEDEFINITIONDESCRIPTION, GRADE1, GRADE2, GRADE3, PRIORITY, SEQUENCENUMBER, QTYSTOCK, LANGUAGECODE, CIRCINV, STATUSQUODATE)
as select
  stockroom.code stockroomCode, stockroom.name stockroomName, bu.code businessunitCode, bu.description businessunitDesc
, employee.employeenumber, employee.name employeeName , sit.customerowned, cu.customernumber
, (select productgroup.code from productgroup where productgroup.productgroup_id = prd.productgroup_id) productgroupCode
, 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, supplier.suppliernumber, 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
, coalesce((select qd.description from qualitygrade_desc qd where qd.qualitygrade_id = qualitygrade.qualitygrade_id
and qd.language_id = languages.language_id and qualitygrade.priority = 2)
, (select qualitygrade.code from qualitygrade where qualitygrade.priority=2))  Grade1
, coalesce((select qd.description from qualitygrade_desc qd where qd.qualitygrade_id = qualitygrade.qualitygrade_id
and qd.language_id = languages.language_id and qualitygrade.priority = 3)
, (select qualitygrade.code from qualitygrade where qualitygrade.priority=3)) Grade2
, coalesce((select qd.description from qualitygrade_desc qd where qd.qualitygrade_id = qualitygrade.qualitygrade_id
and qd.language_id = languages.language_id and qualitygrade.priority = 4)
, (select qualitygrade.code from qualitygrade where qualitygrade.priority=4)) Grade3
, qualitygrade.priority
, productsize.sequencenumber
, COALESCE((select sum(stockquantity.qtynonunique) + sum(stockquantity.qtyunique)+ sum(stockquantity.qtyuniquewithmodifications) from  stockquantity
where srg.stockreservationpergrade_id = stockquantity.stockreservationpergrade_id),0)  QtyStock
, languages.code  languageCode
, (select /*+index(XSPTESTSQITEMCIRC)*/ 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 = stockroom.managedbybu_id
           and sqin.product_link_id = sit.product_id
           and sqin.sizedefinition_link_id = sit.sizedefinition_id
           and sqh.statusquodate =
               (select max(sqh1.statusquodate)
                  from statusquoheader sqh1
                 where sqh1.processbusinessunit_id =
                       sqh.processbusinessunit_id
                   and sqh1.statusquotype = 1)) circinv
, (select max(sqh2.statusquodate) from statusquoheader sqh2
   where sqh2.processbusinessunit_id = bu.businessunit_id and sqh2.statusquotype = 1) statusquodate
from
  stockroom, employee, BUSINESSUNIT BU
, stockdefinitionperitem sit left outer join customer cu on sit.customer_id = cu.customer_id
, stockreservationpergrade srg, qualitygrade, product prd, productsize, sizedefinition sizdef
, color, fabric, supplier, languages
where
    stockroom.responsibleemployee_id = employee.employee_id
and 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.product_id = productsize.product_id
        and productsize.sizedefinition_id = sizdef.sizedefinition_id
    and prd.color_id = color.color_id
    and prd.fabric_id = fabric.fabric_id
    and prd.supplier_id = supplier.supplier_id
and sit.sizedefinition_id = sizdef.sizedefinition_id
AND stockroom.managedbybu_id = BU.BUSINESSUNIT_ID

/
create or replace view V_STOCKINVENTORY_LST
 (STOCKROOMCODE, STOCKROOMNAME, BUSINESSUNITCODE, BUSINESSUNITDESC, EMPLOYEENUMBER, EMPLOYEENAME, CUSTOMEROWNED, CUSTOMERNUMBER, PRODUCTGROUPCODE, PRODUCTCODE, PRODUCTDESCRIPTION, COLORCODE, FABRICODE, SUPPLIERNUMBER, SIZEDEFINITIONCODE, SIZEDEFINITIONDESCRIPTION, GRADE1, GRADE2, GRADE3, PRIORITY, SEQUENCENUMBER, QTYSTOCK, LANGUAGECODE, REPORTPARAM_ID, CIRCINV, STATUSQUODATE)
as select
  stockroom.code stockroomCode, stockroom.name stockroomName, bu.code businessunitCode, bu.description businessunitDesc
, employee.employeenumber, employee.name employeeName , sit.customerowned, cu.customernumber
, (select productgroup.code from productgroup where productgroup.productgroup_id = prd.productgroup_id) productgroupCode
, 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, supplier.suppliernumber, 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
, coalesce((select qd.description from qualitygrade_desc qd where qd.qualitygrade_id = qualitygrade.qualitygrade_id
and qd.language_id = languages.language_id and qualitygrade.priority = 2)
, (select qualitygrade.code from qualitygrade where qualitygrade.priority=2))  Grade1
, coalesce((select qd.description from qualitygrade_desc qd where qd.qualitygrade_id = qualitygrade.qualitygrade_id
and qd.language_id = languages.language_id and qualitygrade.priority = 3)
, (select qualitygrade.code from qualitygrade where qualitygrade.priority=3)) Grade2
, coalesce((select qd.description from qualitygrade_desc qd where qd.qualitygrade_id = qualitygrade.qualitygrade_id
and qd.language_id = languages.language_id and qualitygrade.priority = 4)
, (select qualitygrade.code from qualitygrade where qualitygrade.priority=4)) Grade3
, qualitygrade.priority
, productsize.sequencenumber
, COALESCE((select sum(stockquantity.qtynonunique) + sum(stockquantity.qtyunique)+ sum(stockquantity.qtyuniquewithmodifications) from  stockquantity
where srg.stockreservationpergrade_id = stockquantity.stockreservationpergrade_id),0)  QtyStock
, languages.code  languageCode
, rp.reportparam_id
, (select /*+INDEX(XAK2SQITEMINCIRCULATION sqin)*/ 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 = sizdef.sizedefinition_id
        and sqh.statusquodate = (select max(sqh1.statusquodate) from statusquoheader sqh1
                                 where sqh1.processbusinessunit_id = sqh.processbusinessunit_id and sqh1.statusquotype = 1)) circinv
, (select max(sqh2.statusquodate) from statusquoheader sqh2
   where sqh2.processbusinessunit_id = bu.businessunit_id and sqh2.statusquotype = 1) statusquodate
from
  stockroom, employee, BUSINESSUNIT BU
, stockdefinitionperitem sit left outer join customer cu on sit.customer_id = cu.customer_id
, stockreservationpergrade srg, qualitygrade, product prd, productsize, sizedefinition sizdef
, color, fabric, supplier, languages
, reportparam rp
where
    stockroom.responsibleemployee_id = employee.employee_id
and 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.product_id = productsize.product_id
        and productsize.sizedefinition_id = sizdef.sizedefinition_id
    and prd.color_id = color.color_id
    and prd.fabric_id = fabric.fabric_id
    and prd.supplier_id = supplier.supplier_id
and sit.sizedefinition_id = sizdef.sizedefinition_id
AND stockroom.managedbybu_id = BU.BUSINESSUNIT_ID
and languages.code = rp.string_value AND
    supplier.suppliernumber >= rp.number_value1 AND
    supplier.suppliernumber <= rp.number_value2 AND
    prd.code >= rp.string_value1 AND
    prd.code <= rp.string_value2 AND
    sizdef.code >= rp.string_value3 AND
    sizdef.code <= rp.string_value4 AND
    fabric.code >= rp.string_value5 AND
    fabric.code <= rp.string_value6 AND
    stockroom.code = rp.string_value7 AND
(((rp.number_value = 1) and (sit.customerowned='N') and cu.customernumber is null) or
 ((rp.number_value = 2) and (sit.customerowned = 'N') and (cu.customernumber <= rp.number_value4 and cu.customernumber >= rp.number_value3)) or
 ((rp.number_value = 3) and (sit.customerowned = 'Y') and (cu.customernumber <= rp.number_value4 and cu.customernumber >= rp.number_value3)))

/
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, PRODUCTDESCRIPTION, SIZEDEFINITIONCODE, 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)
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,
 (select pd.description
   from   product_desc pd
   where  pd.product_id = x.product_id
   and    pd.language_id = l.language_id) productdescription, s.code sizedefinitioncode,
 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
from   (select sr.managedbybu_id businessunit_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 qtyuniquereserved,
                srg.qtynonuniquereserved qtynonuniquereserved,
                srg.qtyuniquewiithmodifreserved qtyuniquewiithmodifreserved,
                srg.qtyuniqueordered qtyuniqueordered,
                srg.qtynonuniqueordered qtynonuniqueordered,
                srg.qtyuniqueordereddirectissue qtyuniqueordereddirectissue,
                srg.qtynonuniqueordereddirectissue qtynonuniqueordereddirectissue,
                sti.minqtynew minqtynew, sti.minqtyused minqtyused,
                sti.maxqtynew maxqtynew, sti.maxqtyused maxqtyused
           from stockdefinitionperitem sti
  join stockroom sr 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 sr.managedbybu_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, locationtypeperstockroom lts, product pr,  sizedefinition sd,productsize ps, qualitygrade qg,
     businessunit bu, plant p,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 lt.locationtype_id=lts.locationtype_id
      and sl.locationtype_id=lt.locationtype_id
      and lts.stockroom_id=sr.stockroom_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=bu.businessunit_id
      and bu.businessunit_id=bug.businessunit_id
      and bu.plant_id=p.plant_id

/
create or replace view V_STOCKQUANTITY_AUS
 (STOCKROOMCODE, CUSTOMEROWNED, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERCITY, CUSTOMERSTREET, CUSTOMERZIPCODE, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDEFINITIONCODE, QUALITYGRADECODE, NEWGARMENT, PRIORITY, QTYNONUNIQUE, QTYUNIQUE_ACTUAL, QTYNONUNIQUE_ACTUAL, QTYUNIQUE_BLOCKED, QTYNONUNIQUE_BLOCKED, QTYUNIQUERESERVED, QTYNONUNIQUERESERVED, QTYUNIQUEWIITHMODIFRESERVED, QTYUNIQUEORDERED, QTYNONUNIQUEORDERED, QTYUNIQUEORDEREDDIRECTISSUE, QTYNONUNIQUEORDEREDDIRECTISSUE
, MINQTYNEW, MINQTYUSED, MAXQTYNEW, MAXQTYUSED, LANGUAGECODE, DEFECTITEM, BUSINESSUNIT_ID, VALUEPRICE, LEDGERACCOUNT)
as select stockroom.code stockroomCode,
       sit.customerowned,
       cu.customernumber,
       cu.name customerName,
       address.city CustomerCity,
       address.street CustomerStreet,
       address.zipcode CustomerZipcode,
       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,
       sizdef.code SizedefinitionCode,
       qualitygrade.code qualitygradeCode,
       qualitygrade.newgarment,
       qualitygrade.priority,
       srg.qtynonunique,
       COALESCE((select sum(sq.qtyunique + sq.qtyuniquewithmodifications)
                  from stockquantity     sq,
                       stockroomlocation sl,
                       locationtype      lt
                 where srg.stockreservationpergrade_id =
                       sq.stockreservationpergrade_id
                   and sl.locationtype_id = lt.locationtype_id
                   and sq.stockroomlocation_id = sl.stockroomlocation_id
                   and lt.pickinglocation = 'Y'),
                0) qtyunique_actual,
       COALESCE((select sum(sq.qtynonunique)
                  from stockquantity     sq,
                       stockroomlocation sl,
                       locationtype      lt
                 where srg.stockreservationpergrade_id =
                       sq.stockreservationpergrade_id
                   and sl.locationtype_id = lt.locationtype_id
                   and sq.stockroomlocation_id = sl.stockroomlocation_id
                   and lt.pickinglocation = 'Y'),
                0) qtynonunique_actual,
       COALESCE((select sum(sq.qtyunique + sq.qtyuniquewithmodifications)
                  from stockquantity     sq,
                       stockroomlocation sl,
                       locationtype      lt
                 where srg.stockreservationpergrade_id =
                       sq.stockreservationpergrade_id
                   and sl.locationtype_id = lt.locationtype_id
                   and sq.stockroomlocation_id = sl.stockroomlocation_id
                   and lt.code = 'BLOCK'),
                0) qtyunique_blocked,
       COALESCE((select sum(sq.qtynonunique)
                  from stockquantity     sq,
                       stockroomlocation sl,
                       locationtype      lt
                 where srg.stockreservationpergrade_id =
                       sq.stockreservationpergrade_id
                   and sl.locationtype_id = lt.locationtype_id
                   and sq.stockroomlocation_id = sl.stockroomlocation_id
                   and lt.code = 'BLOCK'),
                0) qtynonunique_blocked,
       srg.qtyuniquereserved,
       srg.qtynonuniquereserved,
       srg.qtyuniquewiithmodifreserved,
       srg.qtyuniqueordered,
       srg.qtynonuniqueordered,
       srg.QtyUniqueOrderedDirectIssue,
       srg.QtyNonUniqueOrderedDirectIssue,
       sit.minqtynew,
       sit.minqtyused,
       sit.maxqtynew,
       sit.maxqtyused,
       languages.code languageCode,
       qualitygrade.defectitem,
       bu.businessunit_id,
       f_getavgpurchaseprice(srg.stockreservationpergrade_id) valueprice, --- this doesnt work... but we need the right ledger account
       (select la.exportcode
          from ledgeraccntsperproduct lpp,
               ledgeraccnttype        lat,
               ledgeraccounts         la
         where lpp.product_id = (case
                                  when prd.typeofmerchandise = 1 then
                                   (select pm.product_id
                                      from product pm
                                     where pm.code = 'ZZ1')
                                  when prd.typeofmerchandise = 2 then
                                   (select pm.product_id
                                      from product pm
                                     where pm.code = 'ZZ2')
                                  when prd.typeofmerchandise = 3 then
                                   (select pm.product_id
                                      from product pm
                                     where pm.code = 'ZZ3')
                                end)
           and lat.code = 'SHLFST'
           and lat.ledgeraccnttype_id = lpp.ledgeraccnttype_id
           and lpp.ledgeraccounts_id = la.ledgeraccounts_id) ||'.'||
           (select substr(tg.code, -4)
                           from   turnovergroup tg
                           where  tg.turnovergroup_id = prd.rentturnovergroup_id)
           ledgeraccount
  from stockdefinitionperitem sit
  left outer join(customer cu
  left outer join address
    on cu.visitaddress_id = address.address_id) on sit.customer_id = cu.customer_id, stockroom, stockreservationpergrade srg, qualitygrade, product prd, sizedefinition sizdef, languages, businessunit bu
 where sit.stockroom_id = stockroom.stockroom_id
   and sit.stockdefinitionperitem_id = srg.stockdefinitionperitem_id
   and srg.qualitygrade_id = qualitygrade.qualitygrade_id
   and sit.product_id = prd.product_id
   and sit.sizedefinition_id = sizdef.sizedefinition_id
   and bu.businessunit_id = stockroom.managedbybu_id

/
create or replace view V_STOCKQUANTITY_RFL
 (STOCKROOMCODE, CUSTOMEROWNED, CUSTOMERNUMBER, CUSTOMERNAME, PRODUCTCODE, CUSTOMERCITY, CUSTOMERSTREET, CUSTOMERZIPCODE, PRODUCTDESCRIPTION, SIZEDEFINITIONCODE, QUALITYGRADECODE, NEWGARMENT, PRIORITY, QTYUNIQUE_ACTUAL, QTYNONUNIQUE_ACTUAL, QTYUNIQUE_BLOCKED, QTYNONUNIQUE_BLOCKED, QTYUNIQUERESERVED, QTYNONUNIQUERESERVED, QTYUNIQUEWIITHMODIFRESERVED, QTYUNIQUEORDERED, QTYNONUNIQUEORDERED, QTYUNIQUEORDEREDDIRECTISSUE, QTYNONUNIQUEORDEREDDIRECTISSUE, MINQTYNEW, MINQTYUSED
, MAXQTYNEW, MAXQTYUSED, DEFECTITEM, BUSINESSUNIT_ID, LANGUAGECODE, QTYNEWAVAILABLE, QTYUSEDAVAILABLE)
as select
X.stockroomCode, X.customerowned, X.customernumber
, X.customerName
, X.ProductCode,
(select address.city from address where x.visitaddress_id = address.address_id) CustomerCity,
(select address.street from address where x.visitaddress_id = address.address_id) CustomerStreet,
 (select address.street from address where x.visitaddress_id = address.address_id)CustomerZipcode
, (select product_desc.description from product_desc where x.product_id = product_desc.product_id
  and product_desc.language_id = languages.language_id ) ProductDescription
, X.SizedefinitionCode, X.qualitygradeCode, X.newgarment
, X.priority
, sum(X.qtyunique_actual) qtyunique_actual
, sum(X.qtynonunique_actual) qtynonunique_actual
, sum(X.qtyunique_blocked) qtyunique_blocked
, sum(X.qtynonunique_blocked) qtynonunique_blocked
, sum(X.qtyuniquereserved) qtyuniquereserved, sum(X.qtynonuniquereserved) qtynonuniquereserved, sum(X.qtyuniquewiithmodifreserved) qtyuniquewiithmodifreserved
, sum(X.qtyuniqueordered) qtyuniqueordered, sum(X.qtynonuniqueordered) qtynonuniqueordered, sum(X.QtyUniqueOrderedDirectIssue) QtyUniqueOrderedDirectIssue, sum(X.QtyNonUniqueOrderedDirectIssue) QtyNonUniqueOrderedDirectIssue
, sum(X.minqtynew) minqtynew, sum(X.minqtyused) minqtyused, sum(X.maxqtynew) maxqtynew, sum(X.maxqtyused) maxqtyused
, X.defectitem
, X.businessunit_id,  languages.code  languageCode,
sum(X.qtynewavailable) qtynewavailable,
sum(X.qtyusedavailable) qtyusedavailable
from (select
  stockroom.code stockroomCode, sit.customerowned, cu.customernumber, sit.product_id, cu.visitaddress_id
, cu.name customerName
, prd.code ProductCode
, sizdef.code SizedefinitionCode, qualitygrade.code qualitygradeCode, qualitygrade.newgarment
, qualitygrade.priority
, COALESCE((select
sum(sq.qtyunique + sq.qtyuniquewithmodifications)
from  stockquantity sq, stockroomlocation sl, locationtype lt
where srg.stockreservationpergrade_id = sq.stockreservationpergrade_id
and sl.locationtype_id = lt.locationtype_id and sq.stockroomlocation_id = sl.stockroomlocation_id
and lt.pickinglocation = 'Y'),0) qtyunique_actual
, COALESCE((select sum(sq.qtynonunique)
from  stockquantity sq, stockroomlocation sl, locationtype lt
where srg.stockreservationpergrade_id = sq.stockreservationpergrade_id
and sl.locationtype_id = lt.locationtype_id and sq.stockroomlocation_id = sl.stockroomlocation_id
and lt.pickinglocation = 'Y'),0) qtynonunique_actual
, COALESCE((select sum(sq.qtyunique + sq.qtyuniquewithmodifications)
from  stockquantity sq, stockroomlocation sl, locationtype lt
where srg.stockreservationpergrade_id = sq.stockreservationpergrade_id
and sl.locationtype_id = lt.locationtype_id and sq.stockroomlocation_id = sl.stockroomlocation_id
and lt.code = 'BLOCK'),0) qtyunique_blocked
, COALESCE((select sum(sq.qtynonunique)
from  stockquantity sq, stockroomlocation sl, locationtype lt
where srg.stockreservationpergrade_id = sq.stockreservationpergrade_id
and sl.locationtype_id = lt.locationtype_id and sq.stockroomlocation_id = sl.stockroomlocation_id
and lt.code = 'BLOCK'),0) qtynonunique_blocked
, srg.qtyuniquereserved, srg.qtynonuniquereserved, srg.qtyuniquewiithmodifreserved
, srg.qtyuniqueordered, srg.qtynonuniqueordered, srg.QtyUniqueOrderedDirectIssue, srg.QtyNonUniqueOrderedDirectIssue
, sit.minqtynew, sit.minqtyused, sit.maxqtynew, sit.maxqtyused
, qualitygrade.defectitem
, bu.businessunit_id,
COALESCE((select sum(sq.qtynonunique+ sq.qtyunique+Sq.Qtyuniquewithmodifications)
from  stockquantity sq, stockroomlocation sl, locationtype lt
where sq.stockreservationpergrade_id = srg.stockreservationpergrade_id
and qualitygrade.newgarment='Y'
and sq.stockroomlocation_id = sl.stockroomlocation_id
and sl.locationtype_id = lt.locationtype_id
and lt.pickinglocation='Y' ),0) qtynewavailable,
COALESCE((select sum(sq.qtynonunique+ sq.qtyunique+Sq.Qtyuniquewithmodifications)
from  stockquantity sq,   stockroomlocation sl, locationtype lt
where sq.stockreservationpergrade_id = srg.stockreservationpergrade_id
and qualitygrade.newgarment='N'and qualitygrade.defectitem='N'
and sq.stockroomlocation_id = sl.stockroomlocation_id
and sl.locationtype_id = lt.locationtype_id
and lt.pickinglocation='Y'),0) qtyusedavailable
from
stockdefinitionperitem sit
       left outer join customer cu
        --    left outer join address on cu.visitaddress_id = address.address_id
       on sit.customer_id = cu.customer_id
, stockroom, stockreservationpergrade srg
, qualitygrade, product prd, sizedefinition sizdef
, businessunit bu
where
    sit.stockroom_id = stockroom.stockroom_id
and srg.stockdefinitionperitem_id = sit.stockdefinitionperitem_id
and srg.qualitygrade_id = qualitygrade.qualitygrade_id
and sit.product_id = prd.product_id
and sit.sizedefinition_id = sizdef.sizedefinition_id
and bu.businessunit_id = stockroom.managedbybu_id) X, languages
where x.qtyunique_actual + x.qtynonunique_actual + x.QTYUNIQUERESERVED + x.QTYNONUNIQUERESERVED + x.QTYUNIQUEWIITHMODIFRESERVED
      + x.QTYUNIQUE_BLOCKED + x.QTYNONUNIQUE_BLOCKED + x.QTYUNIQUEORDERED + x.QTYNONUNIQUEORDERED - x.QtyNonUniqueOrderedDirectIssue - x.QtyUniqueOrderedDirectIssue <> 0
group by X.stockroomCode, X.customerowned, X.customernumber
, X.customerName , x.visitaddress_id
, X.ProductCode,
  x.product_id
, X.SizedefinitionCode, X.qualitygradeCode, X.newgarment
, X.priority, languages.code, languages.language_id
, X.defectitem
, X.businessunit_id
/
create or replace view V_STOCKRECEPSTICKER_UNIQUE_SMG
 (UNIQUEITEM_ID, PRIMARYID, PRODUCT_ID, SIZEDEFINITION_ID, SIZECODE, EMBLEM, SIZECODEDESCRIPTION, MODIFICATIONS, LANGUAGECODE)
as select ui.uniqueitem_id,
       ui.primaryid,
       ui.product_id,
       ui.sizedefinition_id,
       sz.code sizeCode,
       (select max(wi.weareremployment_id)
          from wearerinventory wi
         where ui.lastweareremployment_link_id = wi.weareremployment_id
           and wi.emblemtemplate_id is not null) emblem,
       (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,
       l.code languagecode
  from uniqueitem ui, sizedefinition sz, languages l
 where ui.sizedefinition_id = sz.sizedefinition_id

/
create or replace view V_STOCKRECEPSTICK_LOCATION_SMG
 (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_STOCKRECEPSTICK_PRODUCT_SMG
 (PRODUCT_ID, PRODUCTCODE, SUPPLIER_ID, PRODUCTDESCRIPTION, PRODUCTLONGDESCRIPTION, PRODUCTRANKING, REGISTRATIONUNITCODE, REGISTRATIONUNITDESC, PRODUCTGROUPCODE, PRODUCTGROUPDESC, 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,
           --code below is for future (in case new fields will be requested for StockReceptionSticker report)
       /*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
    --code below is for future (in case new fields will be requested for StockReceptionSticker report)
  /*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_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, GETDATEONLY(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
,(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_STOCKRECEPTIONPRODWO_AUX_SMG
 (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)
wolr.quantity QtyDiff
,(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_STOCKRECEPTIONPRODWO_SMG
 (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, OOSPRODUCT)
as select
  sk.code stockCode, sk.name stockName, sk.stockroom_id, recSkhis.Receivedate, GETDATEONLY(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
, (select coalesce(oosp.status,0)
                from stockdefinitionperitem sdi,stockreservationpergrade srg
                left outer join outofserviceproduct oosp on srg.stockreservationpergrade_id = oosp.stockreservationpergrade_id
                where 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 srg.qualitygrade_id = qq.qualitygrade_id
                and sdi.customer_id is null
                and (oosp.sequencenumber is null or oosp.sequencenumber = (select max(oosp1.sequencenumber) from outofserviceproduct oosp1
                where oosp1.stockreservationpergrade_id = srg.stockreservationpergrade_id))) OOSProduct
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_STOCKRECEPTIONSTICKER_SMG
 (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, getcurrentdate())
        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, getcurrentdate())
        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 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
          F_GETSUPPLIERPRODUCTCODE(slpp.product_id, slps.sizedefinition_id)
       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_STOCKROOMLOCATIONLABEL_DFD
 (STOCKROOMLOCATION_ID, STANDARDLOCATIONPERPRODUCT_ID, PLANT_ID, BUCODE, PLANT, STOCKROOM, UNIQUEID, AREACODE, ROWCODE, LOCATIONCODE, PRODUCTCODE, PRODUCTDESCRIPTION, SIZECODE, SUPPLIERPRODUCTCODE, LANGUAGECODE, REPORTPARAM_ID, CUSTOMERNUMBER)
as select sl.stockroomlocation_id,
       slpp.standardlocationperproduct_id,
       pl.plant_id,
       bu.code bucode,
       pl.code plant,
       st.code stockroom,
       rtrim(sl.uniqueid) 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
          F_GETSUPPLIERPRODUCTCODE(slpp.product_id, slps.sizedefinition_id)
       end supplierproductcode,
       l.code languagecode,
       rp.reportparam_id,
       (select min(c.customernumber) from customer c where c.customer_id=slpp.customer_id) CustomerNumber
 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, PRODUCTDESCRIPTION, SIZEDEFINITIONCODE, QGRESERVEDCODE, MODIFICATIONCODEA, MODIFICATIONCODEB, MODIFICATIONCODEC, QTYUNIQUE, QTYUNIQUERESERVED, QTYNONUNIQUE, QTYNONUNIQUERESERVED, ROUTENUMBER, DAYCODE, WORKORDERNUMBER, REQSTDDELIVERY, WORKORDERQUANTITYORDERED, WORKORDERLINERESERVATIONQTY, CUSTOMERNUMBER, CUSTOMERNAME, WEARERNUMBER, WEARERSEARCHNAME, LANGUAGECODE
, ORDEREDSIZECODE, ORIGIN, SUMQTYUNIQUE, SUMQTYNONUNIQUE, STOCKLOCAREACODE)
as select
  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,
  COALESCE((sq.qtyunique + sq.qtyuniquewithmodifications), 0) qtyunique,
  COALESCE ((select sum(wy.quantity)from workorderlinereservation wy where wy.workorderline_id=wokli.workorderline_id and wy.stocktype in(2,3)), 0) qtyuniquereserved ,
 --srg.qtynonunique,todo9367
COALESCE((select sq.qtynonunique from  locationtype lt
 where sl.locationtype_id = lt.locationtype_id and lt.pickinglocation = 'Y'),0) qtynonunique,
--srg.qtynonuniquereserved,
COALESCE ((select sum(wy.quantity)from workorderlinereservation wy where wy.workorderline_id=wokli.workorderline_id and wy.stocktype = 1), 0) 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.neededdate ReqstdDelivery, wokli.quantityordered WorkOrderquantityordered
, WRE.QUANTITY WorkOrderLineReservationQTY
, cu.customernumber, cu.name customerName, we.wearernumber, we.wearersearchname wearerSearchname
, languages.code languageCode
, (select osd.code from sizedefinition_link osd where wokli.sizedefinition_link_id = osd.sizedefinition_link_id)  OrderedSizeCode
, wok.origin ,  COALESCE((select sum(a.qtyunique) from stockquantity a where a.stockreservationpergrade_id=srg.stockreservationpergrade_id), 0) sumqtyunique,
(select sum(a.qtynonunique) from stockquantity a where a.stockreservationpergrade_id=srg.stockreservationpergrade_id) sumqtynonunique
,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.processingstockroom_id = s.stockroom_id
--AND (wokli.purchaseorderline_id IS NULL or (wokli.purchaseorderline_id is not null and qgReserved.Newgarment='Y')) todo 9948
union all
select
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
, COALESCE((sq.qtyunique + sq.qtyuniquewithmodifications), 0) qtyunique,
  COALESCE ((select sum(wy.quantity)from workorderlinereservation wy where wy.workorderline_id=wokli.workorderline_id and wy.stocktype in(2,3)), 0) qtyuniquereserved ,
 --srg.qtynonunique  do do 9367,
(COALESCE((select sq.qtynonunique from  locationtype lt
 where sl.locationtype_id = lt.locationtype_id and lt.pickinglocation = 'Y'),0) + srg.qtynonunique)qtynonunique,
COALESCE ((select sum(wy.quantity)from workorderlinereservation wy where wy.workorderline_id=wokli.workorderline_id and wy.stocktype = 1), 0) 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.neededdate 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,
(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
, (select osd.code from sizedefinition_link osd where wokli.sizedefinition_link_id = osd.sizedefinition_link_id)  OrderedSizeCode
, wok.origin , (select sum(a.qtyunique) from stockquantity a where a.stockreservationpergrade_id=srg.stockreservationpergrade_id) sumqtyunique,
(select sum(a.qtynonunique) from stockquantity a where a.stockreservationpergrade_id=srg.stockreservationpergrade_id) sumqtynonunique
,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.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.weareremployment_link_id is NULL--and wok.processingstockroom_id = s.stockroom_id
--AND (wokli.purchaseorderline_id IS NULL or (wokli.purchaseorderline_id is not null and qgReserved.Newgarment='Y')) todo 9948

/
create or replace view V_STOCKROOMPICKLIST_AMM
 (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, LANGUAGECODE
, ORDEREDSIZECODE, ORIGIN, WORKORDER_ID, WORKORDERLINE_ID)
as select
  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
, COALESCE((sq.qtyunique + sq.qtyuniquewithmodifications), 0) qtyunique, (srg.qtyuniquereserved+srg.qtyuniquewiithmodifreserved) qtyuniquereserved
, --srg.qtynonunique,todo9367
(COALESCE((select sq.qtynonunique from  locationtype lt
 where sl.locationtype_id = lt.locationtype_id and lt.pickinglocation = 'Y'),0))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.neededdate ReqstdDelivery, wokli.quantityordered WorkOrderquantityordered
, WRE.QUANTITY WorkOrderLineReservationQTY
, cu.customernumber, cu.name customerName, we.wearernumber, we.wearersearchname wearerSearchname
, languages.code languageCode
, (select osd.code from sizedefinition_link osd where wokli.sizedefinition_link_id = osd.sizedefinition_link_id) OrderedSizeCode
, wok.origin, wok.workorder_id, wokli.workorderline_id
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.processingstockroom_id = s.stockroom_id
AND (wokli.purchaseorderline_id IS NULL or
     ((wokli.purchaseorderline_id is not null) and (srg.QtyUniqueReserved + srg.QtyNonUniqueReserved + srg.qtyuniquewiithmodifreserved > srg.QtyUniqueOrdered + srg.QtyNonUniqueOrdered)))
union all
select
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
, COALESCE((sq.qtyunique + sq.qtyuniquewithmodifications), 0) qtyunique, (srg.qtyuniquereserved+srg.qtyuniquewiithmodifreserved) qtyuniquereserved
, --srg.qtynonunique  do do 9367,
(COALESCE((select sq.qtynonunique from  locationtype lt
 where sl.locationtype_id = lt.locationtype_id and lt.pickinglocation = 'Y'),0))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.neededdate 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,
(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
, (select osd.code from sizedefinition_link osd where wokli.sizedefinition_link_id = osd.sizedefinition_link_id)  OrderedSizeCode
, wok.origin, wok.workorder_id, wokli.workorderline_id
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.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.weareremployment_link_id is NULL--and wok.processingstockroom_id = s.stockroom_id
AND (wokli.purchaseorderline_id IS NULL or
     ((wokli.purchaseorderline_id is not null) and (srg.QtyUniqueReserved + srg.QtyNonUniqueReserved + srg.qtyuniquewiithmodifreserved > srg.QtyUniqueOrdered + srg.QtyNonUniqueOrdered)))

/
create or replace view V_STOCKROOMPICKLIST_AUJ
 (QGORDERCODE, STOCKROOMCODE, STOCKROOMDESCRIPTION, ROWCODE, LOCATIONCODE, PICKINGSEQUENCE, UNIQUEYN, PRODUCTCODE, PRODUCTDESCRIPTION, RESERVEDSIZECODE, QGRESERVEDCODE, REQUESTEDSIZECODE, WORKORDERNUMBER, WORKORDERLINE_ID, REQSTDDELIVERY, QUANTITYORDERED, QUANTITYCANCELLED, WORKORDERLINERESERVATIONQTY, CUSTOMERNUMBER, CUSTOMERNAME, WEARERNUMBER, WEARERSEARCHNAME, LANGUAGECODE, CODEUNIQUELY, QTYONSTOCK)
as select
  qgOrder.Code qgOrderCode, s.code stockroomCode, s.name stockroomDescription, sl.rowcode rowCode
, sl.locationcode locationCode, sl.pickingsequence, qgReserved.Newgarment 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 ReservedSizeCode, qgReserved.code qgReservedCode
, (select sl.code from sizedefinition_link sl where sl.sizedefinition_link_id = wokli.sizedefinition_link_id) RequestedSizeCode
, wok.workordernumber, wokli.workorderline_id
, wok.neededdate ReqstdDelivery, wokli.quantityordered
, wokli.quantitycancelled
, sum(WRE.QUANTITY)  WorkOrderLineReservationQTY
, cu.customernumber, cu.name customerName, we.wearernumber, we.wearersearchname wearerSearchname
, languages.code languageCode
, wokli.codeuniquely
, (sq.qtyunique + sq.qtynonunique) qtyonstock
from
  workorder wok
, weareremployment_link we
, workorderline wokli
, product_link prd, qualitygrade qgReserved, qualitygrade qgOrder
, stockroom s
, stockdefinitionperitem sdi, workorderlinereservation wre,
  stockreservationpergrade srg
    left outer
join (
      stockquantity sq join stockroomlocation sl on sl.stockroomlocation_id = sq.stockroomlocation_id and sl.locationtype_id <> 11
          ) 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 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 wokli.workorderline_id = wre.workorderline_id
and wre.stockreservationpergrade_id = srg.stockreservationpergrade_id
group by qgOrder.Code, s.code, s.name, sl.rowcode
, sl.locationcode , sl.pickingsequence, qgReserved.Newgarment, prd.code
, prd.product_id, languages.language_id
, sizedef.code, qgReserved.code
, wok.workordernumber ,wokli.workorderline_id
, wok.neededdate, wokli.quantityordered
, wokli.quantitycancelled
, cu.customernumber, cu.name
, we.wearernumber, we.wearersearchname
, languages.code, wokli.codeuniquely, wokli.sizedefinition_link_id, sq.qtyunique, sq.qtynonunique
union all
select
qgOrder.Code qgOrderCode, s.code stockroomCode, s.name stockroomDescription, sl.rowcode rowCode
, sl.locationcode locationCode, sl.pickingsequence, qgReserved.Newgarment 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 ReservedSizeCode, qgReserved.code qgReservedCode
, (select sl.code from sizedefinition_link sl where sl.sizedefinition_link_id = wokli.sizedefinition_link_id) RequestedSizeCode
, wok.workordernumber,wokli.workorderline_id
, wok.neededdate ReqstdDelivery, wokli.quantityordered
, wokli.quantitycancelled
, sum(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,
(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
, wokli.codeuniquely
, (sq.qtyunique + sq.qtynonunique) qtyonstock
from
  workorder wok
, workorderline wokli
, product_link prd, qualitygrade qgReserved, qualitygrade qgOrder
, stockroom s
, stockdefinitionperitem sdi, workorderlinereservation wre,
  stockreservationpergrade srg
    left outer
join (
      stockquantity sq join stockroomlocation sl on sl.stockroomlocation_id = sq.stockroomlocation_id and sl.locationtype_id <> 11
          ) on srg.stockreservationpergrade_id = sq.stockreservationpergrade_id
, sizedefinition_link sizedef
, languages
where   wok.workorder_id = wokli.workorder_id
and wokli.requestedgrade_id = qgOrder.Qualitygrade_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 wokli.workorderline_id = wre.workorderline_id
and wre.stockreservationpergrade_id = srg.stockreservationpergrade_id
and wok.weareremployment_link_id is NULL
group by qgOrder.Code, s.code, s.name, sl.rowcode
, sl.locationcode , sl.pickingsequence, qgReserved.Newgarment, prd.code
, prd.product_id, languages.language_id
, sizedef.code, qgReserved.code
, wok.workordernumber ,wokli.workorderline_id
, wok.neededdate, wokli.quantityordered
, wokli.quantitycancelled
, wok.customer_link_id
, wok.distributionpoint_link_id
, languages.code, wokli.codeuniquely, wokli.sizedefinition_link_id, sq.qtyunique, sq.qtynonunique

/
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_STOCKROOMPICKLIST_LST
 (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, LANGUAGECODE
, ORDEREDSIZECODE, ORIGIN, SUMQTYUNIQUE, SUMQTYNONUNIQUE)
as select
  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
, COALESCE((COALESCE((select sq.qtyunique from  locationtype lt
 where sl.locationtype_id = lt.locationtype_id and lt.pickinglocation = 'Y'),0) + sq.qtyuniquewithmodifications), 0) qtyunique, (srg.qtyuniquereserved+srg.qtyuniquewiithmodifreserved) qtyuniquereserved
, --srg.qtynonunique,todo9367
(COALESCE((select sq.qtynonunique from  locationtype lt
 where sl.locationtype_id = lt.locationtype_id and lt.pickinglocation = 'Y'),0))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.neededdate ReqstdDelivery, wokli.quantityordered WorkOrderquantityordered
, WRE.QUANTITY WorkOrderLineReservationQTY
, cu.customernumber, cu.name customerName, we.wearernumber, we.wearersearchname wearerSearchname
, languages.code languageCode
, (select osd.code from sizedefinition_link osd where wokli.sizedefinition_link_id = osd.sizedefinition_link_id)  OrderedSizeCode
, wok.origin
, COALESCE((select sum(a.qtyunique) from stockquantity a where a.stockreservationpergrade_id=srg.stockreservationpergrade_id), 0) sumqtyunique
, (select sum(a.qtynonunique) from stockquantity a where a.stockreservationpergrade_id=srg.stockreservationpergrade_id) sumqtynonunique
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.processingstockroom_id = s.stockroom_id
--AND (wokli.purchaseorderline_id IS NULL or (wokli.purchaseorderline_id is not null and qgReserved.Newgarment='Y')) todo 9948
and nvl((select lt.pickinglocation from locationtype lt where sl.locationtype_id=lt.locationtype_id),'Y')='Y'
union all
select
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
, COALESCE((COALESCE((select sq.qtyunique from  locationtype lt
 where sl.locationtype_id = lt.locationtype_id and lt.pickinglocation = 'Y'),0) + sq.qtyuniquewithmodifications), 0) qtyunique, (srg.qtyuniquereserved+srg.qtyuniquewiithmodifreserved) qtyuniquereserved
, --srg.qtynonunique  do do 9367,
(COALESCE((select sq.qtynonunique from  locationtype lt
 where sl.locationtype_id = lt.locationtype_id and lt.pickinglocation = 'Y'),0))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.neededdate 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,
(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
, (select osd.code from sizedefinition_link osd where wokli.sizedefinition_link_id = osd.sizedefinition_link_id)  OrderedSizeCode
, wok.origin
, COALESCE((select sum(a.qtyunique) from stockquantity a where a.stockreservationpergrade_id=srg.stockreservationpergrade_id), 0) sumqtyunique
, (select sum(a.qtynonunique) from stockquantity a where a.stockreservationpergrade_id=srg.stockreservationpergrade_id) sumqtynonunique
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.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.weareremployment_link_id is NULL--and wok.processingstockroom_id = s.stockroom_id
--AND (wokli.purchaseorderline_id IS NULL or (wokli.purchaseorderline_id is not null and qgReserved.Newgarment='Y')) todo 9948
and nvl((select lt.pickinglocation from locationtype lt where sl.locationtype_id=lt.locationtype_id),'Y')='Y'

/
create or replace view V_STOCKROOMPICKLIST_POS
 (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, LANGUAGECODE
, ORDEREDSIZECODE, ORIGIN, SUMQTYUNIQUE, SUMQTYNONUNIQUE, STOCKLOCAREACODE, REASON_DESC, QOPEN)
as select
  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,
  COALESCE((sq.qtyunique + sq.qtyuniquewithmodifications), 0) qtyunique,
  COALESCE ((select sum(wy.quantity)from workorderlinereservation wy where wy.workorderline_id=wokli.workorderline_id and wy.stocktype in(2,3)), 0) qtyuniquereserved ,
 --srg.qtynonunique,todo9367
COALESCE((select sq.qtynonunique from  locationtype lt
 where sl.locationtype_id = lt.locationtype_id and lt.pickinglocation = 'Y'),0) qtynonunique,
--srg.qtynonuniquereserved,
COALESCE ((select sum(wy.quantity)from workorderlinereservation wy where wy.workorderline_id=wokli.workorderline_id and wy.stocktype = 1), 0) 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.neededdate ReqstdDelivery, wokli.quantityordered WorkOrderquantityordered
, WRE.QUANTITY WorkOrderLineReservationQTY
, cu.customernumber, cu.name customerName, we.wearernumber, we.wearersearchname wearerSearchname
, languages.code languageCode
, (select osd.code from sizedefinition_link osd where wokli.sizedefinition_link_id = osd.sizedefinition_link_id)  OrderedSizeCode
, wok.origin ,  COALESCE((select sum(a.qtyunique) from stockquantity a where a.stockreservationpergrade_id=srg.stockreservationpergrade_id), 0) sumqtyunique,
(select sum(a.qtynonunique) from stockquantity a where a.stockreservationpergrade_id=srg.stockreservationpergrade_id) sumqtynonunique
, sl.areacode StockLocAreaCode
, (select rcd.description from reasoncode_desc rcd where rcd.reasoncode_id = wok.reasoncode_id and rcd.language_id = languages.language_id) reason_desc
, (wokli.quantityordered - wokli.quantityfilled - wokli.quantitycancelled) qOpen
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.processingstockroom_id = s.stockroom_id
--AND (wokli.purchaseorderline_id IS NULL or (wokli.purchaseorderline_id is not null and qgReserved.Newgarment='Y')) todo 9948
union all
select
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
, COALESCE((sq.qtyunique + sq.qtyuniquewithmodifications), 0) qtyunique,
  COALESCE ((select sum(wy.quantity)from workorderlinereservation wy where wy.workorderline_id=wokli.workorderline_id and wy.stocktype in(2,3)), 0) qtyuniquereserved ,
 --srg.qtynonunique  do do 9367,
(COALESCE((select sq.qtynonunique from  locationtype lt
 where sl.locationtype_id = lt.locationtype_id and lt.pickinglocation = 'Y'),0))qtynonunique,
COALESCE ((select sum(wy.quantity)from workorderlinereservation wy where wy.workorderline_id=wokli.workorderline_id and wy.stocktype = 1), 0) 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.neededdate 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,
(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
, (select osd.code from sizedefinition_link osd where wokli.sizedefinition_link_id = osd.sizedefinition_link_id)  OrderedSizeCode
, wok.origin , (select sum(a.qtyunique) from stockquantity a where a.stockreservationpergrade_id=srg.stockreservationpergrade_id) sumqtyunique,
(select sum(a.qtynonunique) from stockquantity a where a.stockreservationpergrade_id=srg.stockreservationpergrade_id) sumqtynonunique
, sl.areacode StockLocAreaCode
, (select rcd.description from reasoncode_desc rcd where rcd.reasoncode_id = wok.reasoncode_id and rcd.language_id = languages.language_id) reason_desc
, (wokli.quantityordered - wokli.quantityfilled - wokli.quantitycancelled) qOpen
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.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.weareremployment_link_id is NULL--and wok.processingstockroom_id = s.stockroom_id
--AND (wokli.purchaseorderline_id IS NULL or (wokli.purchaseorderline_id is not null and qgReserved.Newgarment='Y')) todo 9948

/
create or replace view V_STOCKROOMTRANSACTIONS
 (LINETYPE, 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 --+ordered index(scan XSPEEDSCAN) index(x XPKCUSTOMER)
distinct 1 linetype, x.customernumber, x.customername, x.debtornumber, x.debname, x.street, x.zipcode, x.city,
         x.state, x.siccode,  trunc(scan.scantimestamp) scandate,
         (select prd.code from product prd where prd.product_id = scan.product_link_id) productcode,
         (select reasoncode.code from reasoncode where scan.reasoncode_id = reasoncode.reasoncode_id) reasoncode,
         (select product_desc.description
           from   product_desc
           where  product_desc.product_id = scan.product_link_id
           and    product_desc.language_id = languages.language_id) productdesc,
         (select reasoncode_desc.description
           from   reasoncode_desc
           where  reasoncode_desc.reasoncode_id = scan.reasoncode_id
           and    reasoncode_desc.language_id = languages.language_id) reasondesc,
         (select wl.wearernumber
           from   weareremployment_link wl
           where  wl.weareremployment_link_id = scan.weareremployment_link_id) wearernumber,
         (select wl.wearername
           from   weareremployment_link wl
           where  wl.weareremployment_link_id = scan.weareremployment_link_id) wearername,
         (select d.departmentnumber
           from   distributionpoint_link l, department d
           where  l.distributionpoint_link_id = scan.distributionpoint_link_id
           and    l.department_link_id = d.department_id) departmentnumber,
         (select d.description
           from   distributionpoint_link l, department d
           where  l.distributionpoint_link_id = scan.distributionpoint_link_id
           and    l.department_link_id = d.department_id) departmentdesc,
         (select pg.code
           from   product_link pk, productgroup pg
           where  pk.product_link_id = scan.product_link_id
           and    pk.productgroupcode = pg.code) productgroup,
         (select ms.code
           from   marketsegment ms
           where  ms.marketsegment_id = x.marketsegment_id ) marketsegment,
         scan.transactiontype_id transactiontype, languages.code languagecode, languages.language_id,
         x.language_id customerlanguage_id, CASE WHEN scan.primaryid IS NULL
         THEN (select raggeditem.primaryid
           from   raggeditem
           where  raggeditem.raggeditem_id = scan.uniqueitem_link_id)
           ELSE scan.primaryid END primaryid,
         (select bu.code from businessunit bu where bu.businessunit_id = scan.businessunit_id) bu_code,
         (select p.code from businessunit bu, plant p where bu.businessunit_id = scan.businessunit_id and bu.plant_id = p.plant_id) plant_code,
         (select p.name from businessunit bu, plant p where bu.businessunit_id = scan.businessunit_id and bu.plant_id = p.plant_id) plant_name,
         1 numberofscans,
         (select sd.code from sizedefinition sd where sd.sizedefinition_id = scan.sizedefinition_link_id) sizecode,
         (select prsz.sequencenumber from productsize prsz where prsz.product_id = scan.product_link_id and prsz.sizedefinition_id = scan.sizedefinition_link_id) sizeseq
from   scan,
       (select --+ index(cu XPKCUSTOMER) index(deb XPKCUSTOMER) index(address XPKADDRESS)
          cu.customer_id, cu.customernumber, cu.name customername, deb.customernumber debtornumber,
          deb.name debname, address.street, address.zipcode, address.city, address.state, cu.siccode,
          cu.language_id, cu.marketsegment_id
         from   customer cu, customer deb, address
         where  cu.debtor_id = deb.customer_id
         and    deb.invoiceaddress_id = address.address_id) x, languages
where  scan.customer_link_id = x.customer_id
UNION ALL
select --+ordered index(scan XSPEEDSCAN) index(x XPKCUSTOMER)
       2 linetype, x.customernumber, x.customername, x.debtornumber, x.debname, x.street, x.zipcode, x.city,
         x.state, x.siccode, trunc(scan.scantimestamp) scandate,
         (select prd.code from product prd where prd.product_id = scan.product_link_id) productcode,
         (select reasoncode.code from reasoncode where scan.reasoncode_id = reasoncode.reasoncode_id) reasoncode,
         (select product_desc.description
           from   product_desc
           where  product_desc.product_id = scan.product_link_id
           and    product_desc.language_id = languages.language_id) productdesc,
         (select reasoncode_desc.description
           from   reasoncode_desc
           where  reasoncode_desc.reasoncode_id = scan.reasoncode_id
           and    reasoncode_desc.language_id = languages.language_id) reasondesc,
         (select wl.wearernumber
           from   weareremployment_link wl
           where  wl.weareremployment_link_id = scan.weareremployment_link_id) wearernumber,
         (select wl.wearername
           from   weareremployment_link wl
           where  wl.weareremployment_link_id = scan.weareremployment_link_id) wearername,
         (select d.departmentnumber
           from   distributionpoint_link l, department d
           where  l.distributionpoint_link_id = scan.distributionpoint_link_id
           and    l.department_link_id = d.department_id) departmentnumber,
         (select d.description
           from   distributionpoint_link l, department d
           where  l.distributionpoint_link_id = scan.distributionpoint_link_id
           and    l.department_link_id = d.department_id) departmentdesc,
         (select pg.code
           from product_link pk, productgroup pg
           where pk.product_link_id = scan.product_link_id
           and   pk.productgroupcode = pg.code) productgroup,
         (select ms.code
           from   marketsegment ms
           where  ms.marketsegment_id = x.marketsegment_id ) marketsegment,
         scan.transactiontype_id transactiontype, languages.code languagecode, languages.language_id,
         x.language_id customerlanguage_id, NULL primaryid,
         (select bu.code from businessunit bu where bu.businessunit_id = scan.businessunit_id) bu_code,
         (select p.code from businessunit bu, plant p where bu.businessunit_id = scan.businessunit_id and bu.plant_id = p.plant_id) plant_code,
         (select p.name from businessunit bu, plant p where bu.businessunit_id = scan.businessunit_id and bu.plant_id = p.plant_id) plant_name,
         count(1) numberofscans,
         (select sd.code from sizedefinition sd where sd.sizedefinition_id = scan.sizedefinition_link_id) sizecode,
         (select prsz.sequencenumber from productsize prsz where prsz.product_id = scan.product_link_id and prsz.sizedefinition_id = scan.sizedefinition_link_id) sizeseq
from   scan,
       (select --+ index(cu XPKCUSTOMER) index(deb XPKCUSTOMER) index(address XPKADDRESS)
          cu.customer_id, cu.customernumber, cu.name customername, deb.customernumber debtornumber,
          deb.name debname, address.street, address.zipcode, address.city, address.state, cu.siccode,
          cu.language_id, cu.marketsegment_id
         from   customer cu, customer deb, address
         where  cu.debtor_id = deb.customer_id
         and    deb.invoiceaddress_id = address.address_id) x, languages
where  scan.customer_link_id = x.customer_id
GROUP BY x.customernumber, x.customername, x.debtornumber, x.debname, x.street, x.zipcode, x.city,
         x.state, x.siccode, x.marketsegment_id, trunc(scan.scantimestamp), scan.product_link_id, scan.reasoncode_id,
         languages.language_id, scan.weareremployment_link_id, scan.distributionpoint_link_id,
         scan.transactiontype_id, languages.code, x.language_id, scan.businessunit_id, scan.sizedefinition_link_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
    left outer 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_SUMMARIZEDINVACTIVITY13W_POS
 (LANGUAGE_ID, LANGUAGECODE, BUSINESSUNIT, BU_DESC, CUSTOMERNUMBER, CUSTOMERNAME, STREET, STREET2, CITY, STATE, ZIPCODE, WEARERNUMBER, DATEACTIVE, DATEINACTIVE, PRODUCTCODE, PRODUCTDESCRIPTION, SIZECODE, NOTSCANNED, SCANNED, FLAGGEDRETURN2STOCK, FLAGGEDLOSTTAGREPLACEMENT, RAGGED, ADJUSTEDLOST, CANCELLEDLOSTTAGREPLACEMENT, WORNOUT, RETURNED2STOCK, REPLACED, SIZEEXCHANGE, DEPARTMENTNUMBER, DEPARTMENTDESC, NONUNIQUE)
as select l.language_id, l.code languagecode, bu.code businessunit, bu.description bu_desc, c.customernumber, c.name customername, a.street,
       a.street2, a.city, a.state, a.zipcode, w.wearernumber, wi.dateactive, wi.dateinactive,
       p.code productcode, pd.description productdescription, s.code sizecode,
/*       wi.circinventory + wi.freeofchargeqty -
        (select count(1)
         from   uniqueitem u, uniqueitemnonpool un, uniqueitemflag uf, flag f
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    u.uniqueitem_id = uf.uniqueitem_id
         and    uf.flag_id = f.flag_id
         and    f.code = 'A14'
         and    uf.startdate between trunc(sysdate) - (13*7) and trunc(sysdate)) productsincirculation,
*/
/*       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.uniqueitem_id=un.uniqueitem_id --wbo add 15072009
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    not exists
          (select 1
                 from   scan s
                 where  s.uniqueitem_link_id = u.uniqueitem_id
                 and    trunc(s.scantimestamp) between trunc(sysdate) - (13*7) and trunc(sysdate))) notscanned,
       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    exists
          (select 1
                 from   scan s
                 where  s.uniqueitem_link_id = u.uniqueitem_id
                 and    trunc(s.scantimestamp) between trunc(sysdate) - (13*7) and trunc(sysdate))) scanned,
*/
       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.uniqueitem_id=un.uniqueitem_id --wbo add 15072009
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    (u.lastoutscandate is null or u.lastoutscandate < trunc(sysdate) - (13*7))
         ) notscanned,
       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    u.lastoutscandate >= trunc(sysdate) - (13*7)) scanned,
         /*(select count(1)
         from   uniqueitem u, uniqueitemnonpool un, uniqueitemflag uf, automaticflag af
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    u.uniqueitem_id = uf.uniqueitem_id
         and    uf.flag_id = af.flag_id
         and    af.automaticflag_id = 4
         and    uf.startdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 flaggedreturn2stock,
       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un, uniqueitemflag uf, flag f
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    u.uniqueitem_id = uf.uniqueitem_id
         and    uf.flag_id = f.flag_id
         and    f.code = 'A14'
         and    uf.startdate >= trunc(sysdate) - (13*7))
 flaggedlosttagreplacement,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id in
                (select rs.reasoncode_id from reasoncode rs where rs.code in ('2', '3'))
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate)) */
0 ragged,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id = (select rs.reasoncode_id from reasoncode rs where rs.code = '33')
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 adjustedlost,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id = (select rs.reasoncode_id from reasoncode rs where rs.code = '22')
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 cancelledlosttagreplacement,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id in
                (select rs.reasoncode_id from reasoncode rs where rs.code in ('31', '32'))
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 wornout,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id in
                (select rs.reasoncode_id from reasoncode rs where rs.code in ('4', '13', '21'))
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 returned2stock,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id = (select rs.reasoncode_id from reasoncode rs where rs.code = '6')
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 replaced,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id = (select rs.reasoncode_id from reasoncode rs where rs.code = '5')
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 sizeexchange
,      ( select dep.departmentnumber
         from   department dep
         where  dep.department_id = (select dp.department_id
                                     from   distributionpoint dp
                                     where  dp.distributionpoint_id = we.distributionpoint_id)) departmentnumber
,      ( select dep.description
         from   department dep
         where  dep.department_id = (select dp.department_id
                                     from   distributionpoint dp
                                     where  dp.distributionpoint_id = we.distributionpoint_id)) departmentdesc
, (select count(1) from nonuniqueitem n
  where n.wearerinventory_id = wi.wearerinventory_id) NonUnique
from   wearerinventory wi, weareremployment we, wearer w, customer c, address a, languages l,
       product p, product_desc pd, sizedefinition s, businessunit bu
where  wi.weareremployment_id = we.weareremployment_id
and    we.wearer_id = w.wearer_id
and    w.customer_id = c.customer_id
and    c.defaultbusinessunit_id = bu.businessunit_id
and    c.visitaddress_id = a.address_id
and    wi.product_id = p.product_id
and    wi.product_id = pd.product_id
and    pd.language_id = l.language_id
and    wi.sizedefinition_id = s.sizedefinition_id
order  by c.customernumber, p.code, s.code
/
create or replace view V_SUMMARIZEDINVACTIVITY26W_POS
 (LANGUAGE_ID, LANGUAGECODE, BUSINESSUNIT, BU_DESC, CUSTOMERNUMBER, CUSTOMERNAME, STREET, STREET2, CITY, STATE, ZIPCODE, WEARERNUMBER, DATEACTIVE, DATEINACTIVE, PRODUCTCODE, PRODUCTDESCRIPTION, SIZECODE, NOTSCANNED, SCANNED, FLAGGEDRETURN2STOCK, FLAGGEDLOSTTAGREPLACEMENT, RAGGED, ADJUSTEDLOST, CANCELLEDLOSTTAGREPLACEMENT, WORNOUT, RETURNED2STOCK, REPLACED, SIZEEXCHANGE, DEPARTMENTNUMBER, DEPARTMENTDESC, NONUNIQUE)
as select l.language_id, l.code languagecode, bu.code businessunit, bu.description bu_desc, c.customernumber, c.name customername, a.street,
       a.street2, a.city, a.state, a.zipcode, w.wearernumber, wi.dateactive, wi.dateinactive,
       p.code productcode, pd.description productdescription, s.code sizecode,
/*       wi.circinventory + wi.freeofchargeqty -
        (select count(1)
         from   uniqueitem u, uniqueitemnonpool un, uniqueitemflag uf, flag f
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    u.uniqueitem_id = uf.uniqueitem_id
         and    uf.flag_id = f.flag_id
         and    f.code = 'A14'
         and    uf.startdate between trunc(sysdate) - (13*7) and trunc(sysdate)) productsincirculation,
*/
/*       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.uniqueitem_id=un.uniqueitem_id --wbo add 15072009
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    not exists
          (select 1
                 from   scan s
                 where  s.uniqueitem_link_id = u.uniqueitem_id
                 and    trunc(s.scantimestamp) between trunc(sysdate) - (13*7) and trunc(sysdate))) notscanned,
       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    exists
          (select 1
                 from   scan s
                 where  s.uniqueitem_link_id = u.uniqueitem_id
                 and    trunc(s.scantimestamp) between trunc(sysdate) - (13*7) and trunc(sysdate))) scanned,
*/
       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.uniqueitem_id=un.uniqueitem_id --wbo add 15072009
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    (u.lastoutscandate is null or u.lastoutscandate < trunc(sysdate) - (26*7))
         ) notscanned,
       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    u.lastoutscandate >= trunc(sysdate) - (26*7)) scanned,
         /*(select count(1)
         from   uniqueitem u, uniqueitemnonpool un, uniqueitemflag uf, automaticflag af
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    u.uniqueitem_id = uf.uniqueitem_id
         and    uf.flag_id = af.flag_id
         and    af.automaticflag_id = 4
         and    uf.startdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 flaggedreturn2stock,
       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un, uniqueitemflag uf, flag f
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    u.uniqueitem_id = uf.uniqueitem_id
         and    uf.flag_id = f.flag_id
         and    f.code = 'A14'
         and    uf.startdate >= trunc(sysdate) - (26*7))
 flaggedlosttagreplacement,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id in
                (select rs.reasoncode_id from reasoncode rs where rs.code in ('2', '3'))
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate)) */
0 ragged,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id = (select rs.reasoncode_id from reasoncode rs where rs.code = '33')
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 adjustedlost,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id = (select rs.reasoncode_id from reasoncode rs where rs.code = '22')
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 cancelledlosttagreplacement,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id in
                (select rs.reasoncode_id from reasoncode rs where rs.code in ('31', '32'))
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 wornout,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id in
                (select rs.reasoncode_id from reasoncode rs where rs.code in ('4', '13', '21'))
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 returned2stock,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id = (select rs.reasoncode_id from reasoncode rs where rs.code = '6')
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 replaced,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id = (select rs.reasoncode_id from reasoncode rs where rs.code = '5')
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 sizeexchange
,      ( select dep.departmentnumber
         from   department dep
         where  dep.department_id = (select dp.department_id
                                     from   distributionpoint dp
                                     where  dp.distributionpoint_id = we.distributionpoint_id)) departmentnumber
,      ( select dep.description
         from   department dep
         where  dep.department_id = (select dp.department_id
                                     from   distributionpoint dp
                                     where  dp.distributionpoint_id = we.distributionpoint_id)) departmentdesc
, (select count(1) from nonuniqueitem n
  where n.wearerinventory_id = wi.wearerinventory_id) NonUnique
from   wearerinventory wi, weareremployment we, wearer w, customer c, address a, languages l,
       product p, product_desc pd, sizedefinition s, businessunit bu
where  wi.weareremployment_id = we.weareremployment_id
and    we.wearer_id = w.wearer_id
and    w.customer_id = c.customer_id
and    c.defaultbusinessunit_id = bu.businessunit_id
and    c.visitaddress_id = a.address_id
and    wi.product_id = p.product_id
and    wi.product_id = pd.product_id
and    pd.language_id = l.language_id
and    wi.sizedefinition_id = s.sizedefinition_id
order  by c.customernumber, p.code, s.code
/
create or replace view V_SUMMARIZEDINVACTIVITY4W_POS
 (LANGUAGE_ID, LANGUAGECODE, BUSINESSUNIT, BU_DESC, CUSTOMERNUMBER, CUSTOMERNAME, STREET, STREET2, CITY, STATE, ZIPCODE, WEARERNUMBER, DATEACTIVE, DATEINACTIVE, PRODUCTCODE, PRODUCTDESCRIPTION, SIZECODE, NOTSCANNED, SCANNED, FLAGGEDRETURN2STOCK, FLAGGEDLOSTTAGREPLACEMENT, RAGGED, ADJUSTEDLOST, CANCELLEDLOSTTAGREPLACEMENT, WORNOUT, RETURNED2STOCK, REPLACED, SIZEEXCHANGE, DEPARTMENTNUMBER, DEPARTMENTDESC, NONUNIQUE)
as select l.language_id, l.code languagecode, bu.code businessunit, bu.description bu_desc, c.customernumber, c.name customername, a.street,
       a.street2, a.city, a.state, a.zipcode, w.wearernumber, wi.dateactive, wi.dateinactive,
       p.code productcode, pd.description productdescription, s.code sizecode,
/*       wi.circinventory + wi.freeofchargeqty -
        (select count(1)
         from   uniqueitem u, uniqueitemnonpool un, uniqueitemflag uf, flag f
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    u.uniqueitem_id = uf.uniqueitem_id
         and    uf.flag_id = f.flag_id
         and    f.code = 'A14'
         and    uf.startdate between trunc(sysdate) - (13*7) and trunc(sysdate)) productsincirculation,
*/
/*       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.uniqueitem_id=un.uniqueitem_id --wbo add 15072009
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    not exists
          (select 1
                 from   scan s
                 where  s.uniqueitem_link_id = u.uniqueitem_id
                 and    trunc(s.scantimestamp) between trunc(sysdate) - (13*7) and trunc(sysdate))) notscanned,
       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    exists
          (select 1
                 from   scan s
                 where  s.uniqueitem_link_id = u.uniqueitem_id
                 and    trunc(s.scantimestamp) between trunc(sysdate) - (13*7) and trunc(sysdate))) scanned,
*/
       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.uniqueitem_id=un.uniqueitem_id --wbo add 15072009
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    (u.lastoutscandate is null or u.lastoutscandate < trunc(sysdate) - (4*7))
         ) notscanned,
       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    u.lastoutscandate >= trunc(sysdate) - (4*7)) scanned,
         /*(select count(1)
         from   uniqueitem u, uniqueitemnonpool un, uniqueitemflag uf, automaticflag af
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    u.uniqueitem_id = uf.uniqueitem_id
         and    uf.flag_id = af.flag_id
         and    af.automaticflag_id = 4
         and    uf.startdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 flaggedreturn2stock,
       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un, uniqueitemflag uf, flag f
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    u.uniqueitem_id = uf.uniqueitem_id
         and    uf.flag_id = f.flag_id
         and    f.code = 'A14'
         and    uf.startdate >= trunc(sysdate) - (4*7))
 flaggedlosttagreplacement,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id in
                (select rs.reasoncode_id from reasoncode rs where rs.code in ('2', '3'))
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate)) */
0 ragged,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id = (select rs.reasoncode_id from reasoncode rs where rs.code = '33')
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 adjustedlost,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id = (select rs.reasoncode_id from reasoncode rs where rs.code = '22')
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 cancelledlosttagreplacement,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id in
                (select rs.reasoncode_id from reasoncode rs where rs.code in ('31', '32'))
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 wornout,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id in
                (select rs.reasoncode_id from reasoncode rs where rs.code in ('4', '13', '21'))
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 returned2stock,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id = (select rs.reasoncode_id from reasoncode rs where rs.code = '6')
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 replaced,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id = (select rs.reasoncode_id from reasoncode rs where rs.code = '5')
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 sizeexchange
,      ( select dep.departmentnumber
         from   department dep
         where  dep.department_id = (select dp.department_id
                                     from   distributionpoint dp
                                     where  dp.distributionpoint_id = we.distributionpoint_id)) departmentnumber
,      ( select dep.description
         from   department dep
         where  dep.department_id = (select dp.department_id
                                     from   distributionpoint dp
                                     where  dp.distributionpoint_id = we.distributionpoint_id)) departmentdesc
, (select count(1) from nonuniqueitem n
  where n.wearerinventory_id = wi.wearerinventory_id) NonUnique
from   wearerinventory wi, weareremployment we, wearer w, customer c, address a, languages l,
       product p, product_desc pd, sizedefinition s, businessunit bu
where  wi.weareremployment_id = we.weareremployment_id
and    we.wearer_id = w.wearer_id
and    w.customer_id = c.customer_id
and    c.defaultbusinessunit_id = bu.businessunit_id
and    c.visitaddress_id = a.address_id
and    wi.product_id = p.product_id
and    wi.product_id = pd.product_id
and    pd.language_id = l.language_id
and    wi.sizedefinition_id = s.sizedefinition_id
order  by c.customernumber, p.code, s.code
/
create or replace view V_SUMMARIZEDINVACTIVITY52W_POS
 (LANGUAGE_ID, LANGUAGECODE, BUSINESSUNIT, BU_DESC, CUSTOMERNUMBER, CUSTOMERNAME, STREET, STREET2, CITY, STATE, ZIPCODE, WEARERNUMBER, DATEACTIVE, DATEINACTIVE, PRODUCTCODE, PRODUCTDESCRIPTION, SIZECODE, NOTSCANNED, SCANNED, FLAGGEDRETURN2STOCK, FLAGGEDLOSTTAGREPLACEMENT, RAGGED, ADJUSTEDLOST, CANCELLEDLOSTTAGREPLACEMENT, WORNOUT, RETURNED2STOCK, REPLACED, SIZEEXCHANGE, DEPARTMENTNUMBER, DEPARTMENTDESC, NONUNIQUE)
as select l.language_id, l.code languagecode, bu.code businessunit, bu.description bu_desc, c.customernumber, c.name customername, a.street,
       a.street2, a.city, a.state, a.zipcode, w.wearernumber, wi.dateactive, wi.dateinactive,
       p.code productcode, pd.description productdescription, s.code sizecode,
       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.uniqueitem_id=un.uniqueitem_id --wbo add 15072009
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    (u.lastoutscandate is null or u.lastoutscandate < trunc(sysdate) - (52*7))
         ) notscanned,
       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    u.lastoutscandate >= trunc(sysdate) - (52*7)) scanned,
0 flaggedreturn2stock,
       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un, uniqueitemflag uf, flag f
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    u.uniqueitem_id = uf.uniqueitem_id
         and    uf.flag_id = f.flag_id
         and    f.code = 'A14'
         and    uf.startdate >= trunc(sysdate) - (52*7))
 flaggedlosttagreplacement,
0 ragged,
0 adjustedlost,
0 cancelledlosttagreplacement,
0 wornout,
0 returned2stock,
0 replaced,
0 sizeexchange
,      ( select dep.departmentnumber
         from   department dep
         where  dep.department_id = (select dp.department_id
                                     from   distributionpoint dp
                                     where  dp.distributionpoint_id = we.distributionpoint_id)) departmentnumber
,      ( select dep.description
         from   department dep
         where  dep.department_id = (select dp.department_id
                                     from   distributionpoint dp
                                     where  dp.distributionpoint_id = we.distributionpoint_id)) departmentdesc
, (select count(1) from nonuniqueitem n
  where n.wearerinventory_id = wi.wearerinventory_id) NonUnique
from   wearerinventory wi, weareremployment we, wearer w, customer c, address a, languages l,
       product p, product_desc pd, sizedefinition s, businessunit bu
where  wi.weareremployment_id = we.weareremployment_id
and    we.wearer_id = w.wearer_id
and    w.customer_id = c.customer_id
and    c.defaultbusinessunit_id = bu.businessunit_id
and    c.visitaddress_id = a.address_id
and    wi.product_id = p.product_id
and    wi.product_id = pd.product_id
and    pd.language_id = l.language_id
and    wi.sizedefinition_id = s.sizedefinition_id
order  by c.customernumber, p.code, s.code
/
create or replace view V_SUMMARIZEDINVACTIVITY8W_POS
 (LANGUAGE_ID, LANGUAGECODE, BUSINESSUNIT, BU_DESC, CUSTOMERNUMBER, CUSTOMERNAME, STREET, STREET2, CITY, STATE, ZIPCODE, WEARERNUMBER, DATEACTIVE, DATEINACTIVE, PRODUCTCODE, PRODUCTDESCRIPTION, SIZECODE, NOTSCANNED, SCANNED, FLAGGEDRETURN2STOCK, FLAGGEDLOSTTAGREPLACEMENT, RAGGED, ADJUSTEDLOST, CANCELLEDLOSTTAGREPLACEMENT, WORNOUT, RETURNED2STOCK, REPLACED, SIZEEXCHANGE, DEPARTMENTNUMBER, DEPARTMENTDESC, NONUNIQUE)
as select l.language_id, l.code languagecode, bu.code businessunit, bu.description bu_desc, c.customernumber, c.name customername, a.street,
       a.street2, a.city, a.state, a.zipcode, w.wearernumber, wi.dateactive, wi.dateinactive,
       p.code productcode, pd.description productdescription, s.code sizecode,
/*       wi.circinventory + wi.freeofchargeqty -
        (select count(1)
         from   uniqueitem u, uniqueitemnonpool un, uniqueitemflag uf, flag f
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    u.uniqueitem_id = uf.uniqueitem_id
         and    uf.flag_id = f.flag_id
         and    f.code = 'A14'
         and    uf.startdate between trunc(sysdate) - (13*7) and trunc(sysdate)) productsincirculation,
*/
/*       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.uniqueitem_id=un.uniqueitem_id --wbo add 15072009
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    not exists
          (select 1
                 from   scan s
                 where  s.uniqueitem_link_id = u.uniqueitem_id
                 and    trunc(s.scantimestamp) between trunc(sysdate) - (13*7) and trunc(sysdate))) notscanned,
       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    exists
          (select 1
                 from   scan s
                 where  s.uniqueitem_link_id = u.uniqueitem_id
                 and    trunc(s.scantimestamp) between trunc(sysdate) - (13*7) and trunc(sysdate))) scanned,
*/
       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.uniqueitem_id=un.uniqueitem_id --wbo add 15072009
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    (u.lastoutscandate is null or u.lastoutscandate < trunc(sysdate) - (8*7))
         ) notscanned,
       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    u.lastoutscandate >= trunc(sysdate) - (8*7)) scanned,
         /*(select count(1)
         from   uniqueitem u, uniqueitemnonpool un, uniqueitemflag uf, automaticflag af
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    u.uniqueitem_id = uf.uniqueitem_id
         and    uf.flag_id = af.flag_id
         and    af.automaticflag_id = 4
         and    uf.startdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 flaggedreturn2stock,
       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un, uniqueitemflag uf, flag f
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    u.uniqueitem_id = uf.uniqueitem_id
         and    uf.flag_id = f.flag_id
         and    f.code = 'A14'
         and    uf.startdate >= trunc(sysdate) - (8*7))
 flaggedlosttagreplacement,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id in
                (select rs.reasoncode_id from reasoncode rs where rs.code in ('2', '3'))
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate)) */
0 ragged,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id = (select rs.reasoncode_id from reasoncode rs where rs.code = '33')
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 adjustedlost,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id = (select rs.reasoncode_id from reasoncode rs where rs.code = '22')
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 cancelledlosttagreplacement,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id in
                (select rs.reasoncode_id from reasoncode rs where rs.code in ('31', '32'))
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 wornout,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id in
                (select rs.reasoncode_id from reasoncode rs where rs.code in ('4', '13', '21'))
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 returned2stock,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id = (select rs.reasoncode_id from reasoncode rs where rs.code = '6')
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 replaced,
       /*(select sum(oh.amount)
         from   outofcirculationhistory oh
         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    oh.reasoncode_id = (select rs.reasoncode_id from reasoncode rs where rs.code = '5')
         and    oh.outofcircdate between trunc(sysdate) - (13*7) and trunc(sysdate))*/
0 sizeexchange
,      ( select dep.departmentnumber
         from   department dep
         where  dep.department_id = (select dp.department_id
                                     from   distributionpoint dp
                                     where  dp.distributionpoint_id = we.distributionpoint_id)) departmentnumber
,      ( select dep.description
         from   department dep
         where  dep.department_id = (select dp.department_id
                                     from   distributionpoint dp
                                     where  dp.distributionpoint_id = we.distributionpoint_id)) departmentdesc
, (select count(1) from nonuniqueitem n
  where n.wearerinventory_id = wi.wearerinventory_id) NonUnique
from   wearerinventory wi, weareremployment we, wearer w, customer c, address a, languages l,
       product p, product_desc pd, sizedefinition s, businessunit bu
where  wi.weareremployment_id = we.weareremployment_id
and    we.wearer_id = w.wearer_id
and    w.customer_id = c.customer_id
and    c.defaultbusinessunit_id = bu.businessunit_id
and    c.visitaddress_id = a.address_id
and    wi.product_id = p.product_id
and    wi.product_id = pd.product_id
and    pd.language_id = l.language_id
and    wi.sizedefinition_id = s.sizedefinition_id
order  by c.customernumber, p.code, s.code
/
create or replace view V_SUMMARIZEDINVACTIVITY_POS
 (LANGUAGE_ID, MAXINVENTORY, LANGUAGECODE, BUSINESSUNIT, BU_DESC, CUSTOMERNUMBER, CUSTOMERNAME, STREET, STREET2, CITY, STATE, ZIPCODE, WEARERNUMBER, DATEACTIVE, DATEINACTIVE, PRODUCTCODE, SIZECODE, PRODUCTDESCRIPTION, NOTSCANNED, SCANNED, FLAGGEDRETURN2STOCK, FLAGGEDLOSTTAGREPLACEMENT, RAGGED, ADJUSTEDLOST, CANCELLEDLOSTTAGREPLACEMENT, WORNOUT, RETURNED2STOCK, REPLACED, SIZEEXCHANGE, DEPARTMENTNUMBER, DEPARTMENTDESC, REPORTPARAM_ID, NONUNIQUE, CHAIN_CODE, INPROCESS)
as select l.language_id, case when we.sequencenumber = 1 then wi.maxinventory else 0 end maxinventory, --ABS-39349 only Employment#1
       l.code languagecode, bu.code businessunit, bu.description bu_desc, c.customernumber, c.name customername, a.street,
       a.street2, a.city, a.state, a.zipcode, w.wearernumber, wi.dateactive, wi.dateinactive,
       p.code productcode, s.code sizecode,
			 (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = l.language_id) productdescription,
       (select count(1)
         from   uniqueitem u , uniqueitemnonpool un, stay s, status st
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.uniqueitem_id=un.uniqueitem_id --wbo add 15072009
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    u.stay_id = s.stay_id
         and    u.status_id = st.status_id
         and ((u.lastoutscandate is null or u.lastoutscandate < rp.date_value1)
                 and
             ((u.lastscandate is null or u.lastscandate < rp.date_value1) or st.statustype <> 'UI' or st.code not in (20,30)))
         ) notscanned,
       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un, stay s, status st
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    u.stay_id = s.stay_id
         and    u.status_id = st.status_id
         and    (u.lastoutscandate >= rp.date_value1
                 or (u.lastscandate >= rp.date_value1 and st.statustype = 'UI' and st.code in (20,30))
                 )
         ) scanned,
0 flaggedreturn2stock,
       (select count(1)
         from   uniqueitem u, uniqueitemnonpool un, uniqueitemflag uf, flag f
         where  u.businessunit_id = c.defaultbusinessunit_id
         and    u.uniqueitem_id = un.uniqueitem_id
         and    un.weareremployment_id = wi.weareremployment_id
         and    u.product_id = wi.product_id
         and    u.sizedefinition_id = wi.sizedefinition_id
         and    u.finishingmethod_id = wi.finishingmethod_id
         and    u.uniqueitem_id = uf.uniqueitem_id
         and    uf.flag_id = f.flag_id
         and    f.code = 'A14'
         and    uf.startdate between rp.date_value1 and trunc(sysdate)+1)
 flaggedlosttagreplacement,
0 ragged,
0 adjustedlost,
0 cancelledlosttagreplacement,
0 wornout,
0 returned2stock,
0 replaced,
0 sizeexchange
,      ( select dep.departmentnumber
         from   department dep
         where  dep.department_id = (select dp.department_id
                                     from   distributionpoint dp
                                     where  dp.distributionpoint_id = we.distributionpoint_id)) departmentnumber
,      ( select dep.description
         from   department dep
         where  dep.department_id = (select dp.department_id
                                     from   distributionpoint dp
                                     where  dp.distributionpoint_id = we.distributionpoint_id)) departmentdesc
, rp.reportparam_id
, (select count(1) from nonuniqueitem n
  where n.wearerinventory_id = wi.wearerinventory_id) NonUnique    ,
  ch.code chain_code
, coalesce((select Sum(WOL.QuantityOrdered - WOL.QuantityCancelled -  WOL.QuantityFilled) From WorkOrderLine WOL, WorkOrder WO
    Where WOL.WorkOrder_ID = WO.WorkOrder_ID And WOL.Product_link_ID = WI.Product_ID And WOL.SizeDefinition_link_ID = WI.SizeDefinition_ID
    And WO.Status_ID <> (select st.status_id from status st where st.Code = '30' /*(Completed)*/ and st.statustype = 'WO')
    And WO.Status_ID <> (select st.status_id from status st where st.Code = '40' /*(Cancelled)*/ and st.StatusType = 'WO')
    And WO.Weareremployment_Link_Id = We.WearerEmployment_ID and we.sequencenumber = 1), 0) InProcess
from   wearerinventory wi, weareremployment we, wearer w, customer c
       LEFT OUTER JOIN chain ch ON ch.chain_id = c.chain_id,
       address a, languages l, product p, sizedefinition s, businessunit bu, reportparam rp
where  wi.weareremployment_id = we.weareremployment_id
and    we.wearer_id = w.wearer_id
and    w.customer_id = c.customer_id
and    c.defaultbusinessunit_id = bu.businessunit_id
and    c.visitaddress_id = a.address_id
and    wi.product_id = p.product_id
and    wi.sizedefinition_id = s.sizedefinition_id
and    c.customernumber between trunc(rp.number_value1) and rp.number_value2

/
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 SUPPLIER.SUPPLIERNUMBER, SUPPLIER.NAME, SUPPLIER.FAX, SUPPLIER.PHONE, SUPPLIER.EMAIL,
 SUPPLIER.WEBSITE,
 SUPPLIER.CREDITORNUMBER, ADDRESS.STREET, ADDRESS.ZIPCODE, ADDRESS.CITY, ADDRESS.COUNTY,
 ADDRESS.STATE, SUPPLIER.ORDERFORMREMARK, CURRENCY.CODE, CURRENCY.DESCRIPTION,
SUPPLIER.SYSTEMUSER_ID, SUPPLIER.TIMESTAMP
       FROM SUPPLIER, ADDRESS, CURRENCY
       WHERE SUPPLIER.ADDRESS_ID = ADDRESS.ADDRESS_ID
       and SUPPLIER.CURRENCY_ID = CURRENCY.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_SURVEYFORM_BOH
 (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
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
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

/
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, SYSTEMSETTINGVALUE, PLANTCODE, PLANTNAME, LANGUAGECODE, REPORTPARAM_ID, REALWEIGHTCLEAN, REALWEIGHTSOIL)
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.weighingdate REMOVED BECAUSE IS NOT PRINTED AND IT ONLY MULTIPLIES THE ROWS
, v.weighingcategory_id
, v.department_link_id
, v.systemsettingValue
, v.PlantCode, v.PlantName, v.LanguageCode
, v.reportparam_id, v.RealWeightClean, v.RealWeightSoil--, v.number_value
from  (
      select distinct /*+index(prd XPKPRODUCT) index(ps XPKPRODUCTSIZE) index(delk XPKDEPARTMENT_LINK)*/
      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
      --, case when rp.string_value3 = 'true' then coalesce((ps.theoreticalweight * coalesce(dh.amountdelivered,0)),0) else 0 end CalculatedWeight
			, 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' and rp.number_value = delk.department_link_id)
                or
                (rp.string_value4 <> 'true' and rp.number_value = c.customernumber))
      union all
      select /*+index(delk XPKDEPARTMENT_LINK)*/
      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
      , ( 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))
) v
group by v.PlantCode, v.PlantName, v.LanguageCode, v.linetype, v.systemsettingValue
, 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.weighingdate
, v.ProductCode
, v.ProductDesc
, v.SizeCode
, v.theoreticalweight--, v.amountdelivered, v.CalculatedWeight
, v.RealWeightClean, v.RealWeightSoil
, v.number_value

/
create or replace view V_THEORETICALWEIGHTCOMP_BUB
 (LINETYPE, CUSTOMERNUMBER, CUSTOMER_ID, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESC, WEIGHINGCATCODE, WEIGHINGCATDESC, CLEANWEIGHT, SOILWEIGHT, PRODUCTCODE, PRODUCTDESC, SIZECODE, THEORETICALWEIGHT, AMOUNTDELIVERED, CALCULATEDWEIGHT, WEIGHINGCATEGORY_ID, DEPARTMENT_LINK_ID, SYSTEMSETTINGVALUE, PLANTCODE, PLANTNAME, LANGUAGECODE, REPORTPARAM_ID, REALWEIGHTCLEAN, REALWEIGHTSOIL)
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.weighingdate REMOVED BECAUSE IS NOT PRINTED AND IT ONLY MULTIPLIES THE ROWS
, v.weighingcategory_id
, v.department_link_id
, v.systemsettingValue
, v.PlantCode, v.PlantName, v.LanguageCode
, v.reportparam_id, v.RealWeightClean, v.RealWeightSoil--, v.number_value
from  (
      select distinct /*+index(prd XPKPRODUCT) index(ps XPKPRODUCTSIZE) index(delk XPKDEPARTMENT_LINK)*/
      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(plpc.soilweight, 0) else 0 end theoreticalweight
      , case when rp.string_value3 = 'true' then coalesce(dh.amountdelivered, 0) else 0 end amountdelivered
      --, case when rp.string_value3 = 'true' then coalesce((ps.theoreticalweight * coalesce(dh.amountdelivered,0)),0) else 0 end CalculatedWeight
			, coalesce((plpc.soilweight * 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 left outer join productlistpercustomer plpc on(
           plpc.customer_id=dh.customer_link_id
            and plpc.product_id=dh.product_link_id
            and plpc.sizedefinition_id=dh.sizedefinition_link_id
            and plpc.finishingmethod_id=dh.finishingmethod_id
      ), product prd
      , sizedefinition sz, department_link delk
      , businessunit bu, plant pla, languages lan
      , reportparam rp, customer c
      where dh.customer_link_id = c.customer_id  and dh.sizedefinition_link_id = sz.sizedefinition_id
            and prd.product_id = dh.product_link_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' and rp.number_value = delk.department_link_id)
                or
                (rp.string_value4 <> 'true' and rp.number_value = c.customernumber))
      union all
      select /*+index(delk XPKDEPARTMENT_LINK)*/
      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
      , ( 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))
) v
group by v.PlantCode, v.PlantName, v.LanguageCode, v.linetype, v.systemsettingValue
, 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.weighingdate
, v.ProductCode
, v.ProductDesc
, v.SizeCode
, v.theoreticalweight--, v.amountdelivered, v.CalculatedWeight
, 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_TOBEDELIVEREDPRODUCTS_SGS
 (CUSTOMERNUMBER, NAME, DRIVINGDATE, ROUTENUMBER, STOPNUMBER, PRODUCT_CODE, PRODUCT_DESCRIPTION, DELIVEREDAMOUNT, DAYDESCRIPTION, PG_CODE, LANGUAGECODE)
as SELECT C.CUSTOMERNUMBER,
       C.NAME,
       RC.DRIVINGDATE,
       R.ROUTENUMBER,
       S.STOPNUMBER,
       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_DESCRIPTION,
       PNL.DELIVEREDAMOUNT,
        (SELECT DESCRIPTION FROM DAY_DESC
         WHERE DAY_DESC.LANGUAGE_ID = L.LANGUAGE_ID
         AND DAY_DESC.DAY_ID = PN.DAYNUMBER) DAYDESCRIPTION,
       PG.CODE PG_CODE,
       L.CODE LANGUAGECODE
  FROM
       ROUTE           R,
       ROUTECONTROL    RC,
       STOP S,
       PACKINGNOTE     PN,
       CUSTOMER        C,
       PACKINGNOTELINE PNL,
       PRODUCT         P,
       PRODUCTGROUP    PG,
       LANGUAGES       L
 WHERE
 PN.STOP_ID = S.STOP_ID
 AND S.CUSTOMER_LINK_ID = C.CUSTOMER_ID
 AND S.ROUTECONTROL_ID = RC.ROUTECONTROL_ID
 AND PN.ROUTE_ID = R.ROUTE_ID
 AND PN.ROUTECONTROL_ID = RC.ROUTECONTROL_ID
 AND PN.PACKINGNOTE_ID = PNL.PACKINGNOTE_ID
 AND PNL.PRODUCT_ID = P.PRODUCT_ID
 AND P.PRODUCTGROUP_ID = PG.PRODUCTGROUP_ID

/
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
, GETDATEONLY(uq.lastscandate) lastscandate, GETDATEONLY(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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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 <= GETCURRENTDATE())
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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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 <= GETCURRENTDATE())
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 <= GETCURRENTDATE() 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 <= GETCURRENTDATE() 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
, GETDATEONLY(uq.lastscandate) lastscandate, GETDATEONLY(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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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 <= GETCURRENTDATE() 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 <= GETCURRENTDATE())

/
create or replace view V_TOBERETURNEDGARMENTS_CBD
 (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
, STREET, ZIPCODE, CITY, DEFAULTBUSINESSUNIT_ID, WEARERNUMBER, WEARERNAME, WEARERSEARCHNAME, WEARERACTIVE, WEARERDATEACTIVE, WEARERDATEINACTIVE, LANGUAGECODE, LANGUAGE_ID, CUSTOMERLANGUAGE_ID, SUBSTITUTEYN, QUALITYGRADE_CODE, LEASEWEEKS, SPLITUPCODE, INVOICENUMBER, INVOICEHEADER_ID, INVOICEDATE, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, BUDESCRIPTION, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTPHONENO, PLANTFAXNO, SECONDARYID
, REASON_DESC, SALESAREA)
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
, case when (lk.bank is null or lk.bank = '') then '' else cast(CONCATENATEWITHSIGN(lk.bank, '/', lk.locker) as varchar2(255)) end
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
, GETDATEONLY(uq.lastscandate) lastscandate, GETDATEONLY(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,
 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.street, address.zipcode, address.city, cu.defaultbusinessunit_id
, we.wearernumber, we.fullname wearername, we.searchname wearersearchname
, GETDATEDIFF(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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, ih.billtocustomernumber, ih.billtocustomername
, bu.description budescription, plant.code plantcode, plant.name plantname
, plant.website plantwebsite, plant.email plantemail, plantaddress.street plantstreet
, plantaddress.zipcode plantzipcode, plantaddress.city plantcity, plant.phoneno plantphoneno, plant.faxno plantfaxno
, (select sui.secondaryid from secondaryuniqueitem sui where sui.uniqueitem_id = uq.uniqueitem_id) secondaryid
, ( select rcd.description
    from   reasoncode_desc rcd
    where  rcd.reasoncode_id = r.reasoncode_id
       and rcd.LANGUAGE_ID = languages.LANGUAGE_ID) reason_desc, cu.salesarea_id Salesarea
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
, businessunit bu, plant, address plantaddress
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.visitaddress_id = address.address_id
and cu.currency_id = currency.currency_id
and ih.deltocustomer_link_id = cu.customer_id
and coalesce(ih.splitupcode, cc.code) = cc.code
AND we.dateactive <= GETCURRENTDATE()
and ih.invoicebusinessunit_id = bu.businessunit_id
and bu.plant_id = plant.plant_id
and plant.address_id = plantaddress.address_id
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
, case when (lk.bank is null or lk.bank = '') then '' else cast(CONCATENATEWITHSIGN(lk.bank, '/', lk.locker) as varchar2(255)) end
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.street, address.zipcode, address.city, cu.defaultbusinessunit_id
, we.wearernumber, we.fullname wearername, we.searchname wearersearchname
, GETDATEDIFF(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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, ih.billtocustomernumber, ih.billtocustomername
, bu.description budescription, plant.code plantcode, plant.name plantname
, plant.website plantwebsite, plant.email plantemail, plantaddress.street plantstreet
, plantaddress.zipcode plantzipcode, plantaddress.city plantcity, plant.phoneno plantphoneno, plant.faxno plantfaxno
, null secondaryid
, ( select rcd.description
    from   reasoncode_desc rcd
    where  rcd.reasoncode_id = rc.reasoncode_id
       and rcd.LANGUAGE_ID = languages.LANGUAGE_ID) reason_desc, cu.salesarea_id Salesarea
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
, businessunit bu, plant, address plantaddress
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.visitaddress_id = address.address_id
    and cu.currency_id = currency.currency_id
and ih.deltocustomer_link_id = cu.customer_id
and coalesce(ih.splitupcode, cc.code) = cc.code
AND we.dateactive <= GETCURRENTDATE()
and ih.invoicebusinessunit_id = bu.businessunit_id
and bu.plant_id = plant.plant_id
and plant.address_id = plantaddress.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
, wf.code functioncode, wf.description functiondesc, wey.sequencenumber employment
, case when (lk.bank is null or lk.bank = '') then '' else cast(CONCATENATEWITHSIGN(lk.bank, '/', lk.locker) as varchar2(255)) end
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 <= GETCURRENTDATE() and af.automaticflag_id in (12, 4, 5, 7, 2,16,17,18)) 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 <= GETCURRENTDATE() and af.automaticflag_id in (12, 4, 5, 7, 2,16,17,18)) uiflagcode
, ( select count(*) from uniqueitemmodification um where um.uniqueitem_id=uq.uniqueitem_id) modifications
, r.code reason, uq.customerowned, uqnp.freeextragarment
, GETDATEONLY(uq.lastscandate) lastscandate, GETDATEONLY(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,
 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.street, address.zipcode, address.city, cu.defaultbusinessunit_id
, we.wearernumber, we.fullname wearername, we.searchname wearersearchname
, (-1)*GETDATEDIFF(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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, ih.billtocustomernumber, ih.billtocustomername
, bu.description budescription, plant.code plantcode, plant.name plantname
, plant.website plantwebsite, plant.email plantemail, plantaddress.street plantstreet
, plantaddress.zipcode plantzipcode, plantaddress.city plantcity, plant.phoneno plantphoneno, plant.faxno plantfaxno
, (select sui.secondaryid from secondaryuniqueitem sui where sui.uniqueitem_id = uq.uniqueitem_id) secondaryid
, ( select rcd.description
    from   reasoncode_desc rcd
    where  rcd.reasoncode_id = r.reasoncode_id
       and rcd.LANGUAGE_ID = languages.LANGUAGE_ID) reason_desc, cu.salesarea_id Salesarea
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
, businessunit bu, plant, address plantaddress
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.visitaddress_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 <= GETCURRENTDATE() and af.automaticflag_id in (12, 4, 5, 7, 2,16,17,18) )
and ih.deltocustomer_link_id = cu.customer_id
and coalesce(ih.splitupcode, cc.code) = cc.code
AND we.dateactive <= GETCURRENTDATE()
and ih.invoicebusinessunit_id = bu.businessunit_id
and bu.plant_id = plant.plant_id
and plant.address_id = plantaddress.address_id

/
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_TREATMENTCERTIFICATION_POS
 (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, BUCODE, TREATMENTSCAN_ID)
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
       CASTNUMBERASVARCHARWITHFORMAT(TSC.NUMBERVALUE, '9.99EEEE') SCIENTIFICVALUE -- WBO test change 10-06-2009
       , (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
       , (select bu.code from businessunit bu where bu.businessunit_id=sc.businessunit_id) BUCODE --add WBO 10-02-2009
       , ts.treatmentscan_id
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
      TS.SCAN_ID = SC.SCAN_ID
      and (RP.STRING_VALUE IS NULL OR (RP.STRING_VALUE IS not NULL and RP.STRING_VALUE = SC.BATCHNUMBER))

/
create or replace view V_TREATMENTCERT_MONTH_POS
 (TREATMENTTYPE_CODE, SCANTIMESTAMP, TREATMENTDATE, PRIMARYID, BATCHNUMBER, YEAR, MONTH, PRODUCT_CODE, PRODUCT_DESC, SIZE_CODE, CHARACTERISTIC_ID, LENGTH, DATATYPE, DECIMALS, NUMBERVALUE, STRINGVALUE, DATEVALUE, SCIENTIFICVALUE, CHARACTERISTIC_DESC, SEQUENCENUMBER, CUSTOMERNAME, CUSTOMERNUMBER, DAYNUMBER, ROUTENUMBER, LANGUAGE_CODE, BUCODE)
as SELECT TT.CODE TREATMENTTYPE_CODE, SC.SCANTIMESTAMP, TS.TREATMENTDATE, SC.PRIMARYID, SC.BATCHNUMBER, year(ts.treatmentdate) year, month(ts.treatmentdate) month
       , (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.99EEEE') SCIENTIFICVALUE -- WBO test change 10-06-2009
       , (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
       , LAN.CODE LANGUAGE_CODE
       , (select bu.code from businessunit bu where bu.businessunit_id=sc.businessunit_id) BUCODE --add WBO 10-02-2009
FROM SCAN SC, TREATMENTTYPE TT, TREATMENTSCAN TS, TREATMENTSCANCHARACTERISTIC TSC, CHARACTERISTIC CH
     , LANGUAGES LAN
WHERE TS.TREATMENTTYPE_ID = TT.TREATMENTTYPE_ID AND
      TSC.CHARACTERISTIC_ID = CH.CHARACTERISTIC_ID AND TSC.TREATMENTSCAN_ID = TS.TREATMENTSCAN_ID AND
      TS.SCAN_ID = SC.SCAN_ID
and TT.CODE<>'DETAIL'
and not(TSC.NUMBERVALUE is null and TSC.STRINGVALUE is null and TSC.DATEVALUE is null)

/
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 ) < GETCURRENTDATE()
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 ds.uniqueitem_link_id, ds.businessunit_id, ds.scantimestamp, dp.department_link_id, ds.scanstation, ds.plantdepartment_id
  from DeliveryScan DS, distributionpoint_link dp
 where dp.distributionpoint_link_id = ds.distributionpoint_link_id
   and DS.outscannodelivery = 0
   and NVL(PACKINGNOTE_ID, 0) = 0
 order by ds.scantimestamp asc

/
create or replace view V_TURNOVERACCOUNTMANAGER_SMG
 (EMPLOYEENUMBER, EMPLOYEENAME, CUSTOMERNUMBER, CUSTOMERNAME, TOTAL, PLANTCODE, BUCODE, INVOICEDATE)
as SELECT EM1.EMPLOYEENUMBER EMPLOYEENUMBER,
       EM1.NAME EMPLOYEENAME,
       CU1.CUSTOMERNUMBER CUSTOMERNUMBER,
       CU1.NAME CUSTOMERNAME,
       SUM(coalesce(ihc.TOTALAMOUNTEXCLVAT, IH1.TOTALAMOUNTEXCLVAT)) TOTAL,
       PLNT1.CODE PLANTCODE,
       BU1.CODE BUCODE,
       IH1.INVOICEDATE
  FROM ARTRANSACTION ART1,
       CUSTOMER      CU1,
       CONTRACT      CT1,
       EMPLOYEE      EM1,
       INVOICEHEADER IH1
       left outer join invoiceheadercurrency ihc on ihc.invoiceheader_id = ih1.invoiceheader_id and ihc.invoicecurrencytype = 2,--Plant Currency
       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(coalesce(ihc.TOTALAMOUNTEXCLVAT, IH.TOTALAMOUNTEXCLVAT)) TOTAL,
       PLNT.CODE PLANTCODE,
       BU.CODE BUCODE,
       IH.INVOICEDATE
  FROM ARTRANSACTION            ART,
       CUSTOMER                 CU,
       CONTRACTSPERCUSTOMER     CPC,
       EMPLOYEE                 EM,
       INVOICEHEADER            IH
       left outer join invoiceheadercurrency ihc on ihc.invoiceheader_id = ih.invoiceheader_id and ihc.invoicecurrencytype = 2,--Plant Currency
       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_TURNOVERBYPDPG_ECL
 (NAME, INVOICEDATE, PG_DESC, PCK_DEP, AMOUNT)
as select sb.name, sb.invoicedate, sb.pg_desc, sb.pck_dep, sum(sb.amount) amount
from (select c.name,
               C.CUSTOMERNUMBER,
               ih.invoicedate,
               (select pgd.description
                  from productgroup_desc pgd
                 where pgd.productgroup_id = pg.productgroup_id
                   and pgd.language_id = l.language_id) pg_desc,
               coalesce((select max(pd.description)
                          from distributionpoint dp
                          join standarddelivery sd
                            on sd.distributionpoint_id =
                               dp.distributionpoint_id
                          join plantdepartment pd
                            on sd.plantdepartment_id = pd.plantdepartment_id
                          join standarddeliveryline sdl
                            on sdl.standarddelivery_id =
                               sd.standarddelivery_id
                           and sdl.dateinactive > sysdate
                          join productlistperdistribpoint plpd
                            on plpd.productlistperdistribpoint_id =
                               sdl.productlistperdistribpoint_id
                          join distributionpoint dp
                            on sd.distributionpoint_id =
                               dp.distributionpoint_id
                          join department dep
                            on dep.department_id = dp.department_id
                         where dep.customer_id = c.customer_id
                             and plpd.product_id = p.product_id and
                               (plpd.sizedefinition_id =
                               ilp.sizedefinition_link_id or
                               ilp.sizedefinition_link_id =
                               (select sz.sizedefinition_id
                                    from sizedefinition sz
                                   where sz.code = '*')) and
                               plpd.finishingmethod_id =
                               ilp.finishingmethod_id),
                        (select pd.description
                           from productgroup pgi
                           join packingdepartmentdefinition pkd
                             on pgi.productgroup_id = pkd.productgroup_id
                           join plantdepartment pd
                             on pkd.plantdepartment_id = pd.plantdepartment_id
                          where pgi.productgroup_id = pg.productgroup_id)) pck_dep,
               sum(il.amount) amount
          from customer c
          join invoiceheader ih
            on ih.deltocustomer_link_id = c.customer_id
          join invoiceline il
            on il.invoiceheader_id = ih.invoiceheader_id
          join invoicelineproduct ilp
            on il.invoiceline_id = ilp.invoiceline_id
          join product p
            on ilp.product_link_id = p.product_id
          join productgroup pg
            on pg.productgroup_id = p.productgroup_id
         cross join languages l
         where l.code = 'EN_GB'
           AND P.TYPEOFMERCHANDISE = 1
         group by c.name,
                  C.CUSTOMERNUMBER,
                  ih.invoicedate,
                  p.product_id,
                  ilp.sizedefinition_link_id,
                  ilp.finishingmethod_id,
                  l.language_id,
                  pg.productgroup_id,
                  c.customer_id) sb
 group by name, invoicedate, pg_desc, pck_dep

/
create or replace view V_TURNOVERBYTG_ECL
 (NAME, INVOICEDATE, TURNOVERGROUP_ID, CHAINCODE, CHAINNAME, CODE, TG_DESC, AMOUNT)
as select c.name, ih.invoicedate, il.turnovergroup_id, ch.code chaincode, ch.name chainname,
tg.code, (select tgd.description from turnovergroup_desc tgd where tg.turnovergroup_id=tgd.turnovergroup_id and tgd.language_id=l.language_id) tg_desc,
sum(il.amount) amount
from customer c join invoiceheader ih on ih.deltocustomer_link_id=c.customer_id
join chain ch on c.chain_id=ch.chain_id
join invoiceline il on il.invoiceheader_id=ih.invoiceheader_id
join turnovergroup tg on il.turnovergroup_id=tg.turnovergroup_id
cross join languages l where l.code='EN_GB'
group by c.name, ih.invoicedate, tg.turnovergroup_id, l.language_id, tg.code, il.turnovergroup_id,  ch.code , ch.name

/
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_TURNOVERCOMPARISON_AUJ
 (REPORTPARAM_ID, CURRENCYCODE, INVOICEAMOUNTDECIMALS, GROUPCODE, GROUPDESC, CUSTOMERPHONENO, CUSTOMERCITY, TURNOVERGROUPCODE, TURNOVERGROUPDESCRIPTION, LANGUAGECODE, PERIOD_1_AMOUNT, PERIOD_2_AMOUNT)
as select
       rp.reportparam_id,
       art.currencycode,
       art.invoiceamountdecimals,
       art.groupcode,
       art.groupdesc,
       art.customerphoneno,
       art.customercity,
       tog.turnovergroupcode,
       tog.turnovergroupdescription,
       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_TURNOVERCOMPARISON_SGS
 (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.deltocustomer_link_id--.billtocustomer_link_id for SGS show DelTo
         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_TURNOVERCOMPARISON_SMG
 (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,
       art.exchangerate * SUM(case when art.ARTRANSACTIONDATE between rp.date_value1 and rp.date_value2
                then AD.AMOUNT
                else 0
           end) PERIOD_1_AMOUNT,
       art.exchangerate * 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.exchangerate,
             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 = coalesce(a.plantcountrycurrency_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.exchangerate,
             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 = coalesce(a.plantcountrycurrency_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.exchangerate,
             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 = coalesce(a.plantcountrycurrency_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.exchangerate,
             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 = coalesce(a.plantcountrycurrency_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.exchangerate,
             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 = coalesce(a.plantcountrycurrency_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.exchangerate,
             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 = coalesce(a.plantcountrycurrency_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.exchangerate,
             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 = coalesce(a.plantcountrycurrency_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.exchangerate,
         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, VA1UE, INVOICEAMOUNTDECIMALS, NROFDELIVERYDAYS)
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, cu.customer_id, cu.debtor_id
, 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.City, addressCu.City) City, day.daynumber
, coalesce(addressDlv.Zipcode, addressCu.Zipcode) Zipcode, dsk.code DeliveryschemeCode
, route.routenumber, route.description RouteDesc, route.route_id
, (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
, (select sum(ih.totalamountexclvat / (ih.endweek - ih.startweek + 1))
   from invoiceheader ih, status st where ih.billtocustomer_link_id = cu.debtor_id --and ih.route_id = route.route_id
   and st.status_id = ih.status_id and st.code = '2' --Finalized
   and ih.invoicedate between add_months(trunc(sysdate,'mm'),-1) and last_day(add_months(trunc(sysdate,'mm'),-1))) va1ue
, ( 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 --- 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
    GETCURRENTDATETIME() 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 <= GetCurrentDate()
and rst.dateinactive > GetCurrentDate()

/
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_TURNOVERREPORTDETAIL_SMG
 (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(coalesce(ilc.amount, 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,
     left outer join invoicelinecurrency ilc on ilc.invoiceline_id = il.invoiceline_id and ilc.invoicecurrencytype = 2, --Plant Currency
     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_TURNOVERREPORT_SMG
 (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,
       coalesce(ilc.amount, il.amount) 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
     left outer join invoicelinecurrency ilc on ilc.invoiceline_id = il.invoiceline_id and ilc.invoicecurrencytype = 2, --Plant Currency
     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_UIPERBUSINESSUNIT
 (BUSINESSUNIT_ID, CUSTOMER_ID)
as select ui.businessunit_id, ui.uniqueitem_id
  from uniqueitem ui
union
select ordb.orbusinessunit_id, ui.uniqueitem_id
  from ordeliverbusinessunit ordb, uniqueitem ui
	WHERE ui.businessunit_id = ordb.delivertobusinessunit_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, PROD_DESC, SIZE_CODE, SIZE_DESC, FINMETH_CODE, FINMETH_DESC)
as 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,
       ub.businessunit_id, ub.primaryid, ub.creationdate, ub.contentstype, ub.quantity, ub.maxquantity,
       ub.outscandate, ub.deliverynotenumber, ub.uniquebundle_id,
       p.code prod_code, (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = pl.language_id) prod_desc,
       s.code size_code, (select sd.description from sizedefinition_desc sd where sd.sizedefinition_id = s.sizedefinition_id and sd.language_id = pl.language_id) size_desc,
       f.code finMeth_code, (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 outer join finishingmethod f on ub.finishingmethod_id = f.finishingmethod_id,
     product p, sizedefinition s, businessunit bu, plant pl
where ub.product_link_id = p.product_id and
      ub.sizedefinition_link_id = s.sizedefinition_id and
      ub.businessunit_id = bu.businessunit_id and
      bu.plant_id = pl.plant_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 prod_desc,
       null size_code, null size_desc,
       null finMeth_code, null finMeth_desc
from businessunit bu, plant pl
where  bu.plant_id = pl.plant_id

/
create or replace view V_UNIQUEBUNDLESTICKER_BUB
 (REPORTPARAM_ID, 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, PROD_DESC, SIZE_CODE, SIZE_DESC, FINMETH_CODE, FINMETH_DESC, CUSTOMER_NAME, EMPLOYEE_NAME, STRING_VALUE2)
as select --+ INDEX(ub XAK1UNIQUEBUNDLE)
       rp.reportparam_id, 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, (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = pl.language_id) prod_desc,
       s.code size_code, (select sd.description from sizedefinition_desc sd where sd.sizedefinition_id = s.sizedefinition_id and sd.language_id = pl.language_id) size_desc,
       f.code finMeth_code, (select fd.description from finishingmethod_desc fd where fd.finishingmethod_id = f.finishingmethod_id and fd.language_id = pl.language_id) finMeth_desc
       , (select cl.name from customer_link cl where cl.customer_link_id = ub.customer_link_id) customer_name
       , cast(F_GetStationNameFromBundle(ub.uniquebundle_id) as varchar2(60)) Employee_Name
       , rp.string_value2
from uniquebundle ub left outer join finishingmethod f on ub.finishingmethod_id = f.finishingmethod_id,
     product p, sizedefinition s, businessunit bu, plant pl, reportparam rp
where ub.product_link_id = p.product_id and
      ub.sizedefinition_link_id = s.sizedefinition_id and
      ub.businessunit_id = bu.businessunit_id and
      bu.plant_id = pl.plant_id and
      ub.primaryid = rp.string_value and
      ub.businessunit_id = rp.number_value
union
select rp.reportparam_id, 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 prod_desc,
       null size_code, null size_desc,
       null finMeth_code, null finMeth_desc, null customer_name, null Employee_Name,
       rp.string_value2
from businessunit bu, plant pl, reportparam rp
where  bu.plant_id = pl.plant_id
and rp.string_value = 'ERRORSTICKER'
and rp.number_value = bu.businessunit_id

/
create or replace view V_UNIQUEBUNDLESTICKER_CBD
 (PLANT_CODE, PLANT_NAME, PLANT_PHONE, PLANT_FAX, PLANTSTREET, PLANTSTREET2, PLANTZIPCODE, PLANTCITY, PLANTSTATE, PLANTCOUNTY, HOUSENUMBER, HOUSENUMBEREXT, BU_CODE, DU_DESCRIPTION, BUSINESSUNIT_ID, PRIMARYID, CREATIONDATE, CONTENTSTYPE, QUANTITY, MAXQUANTITY, OUTSCANDATE, DELIVERYNOTENUMBER, UNIQUEBUNDLE_ID, PROD_CODE, PROD_DESC, SIZE_CODE, SIZE_DESC, FINMETH_CODE, FINMETH_DESC)
as select pl.code plant_code, pl.name plant_name, pl.phoneno plant_phone, pl.faxno plant_fax,
       x.street plantstreet, x.street2 plantstreet2, x.zipcode plantzipcode,
       x.city plantcity, x.state plantstate, x.county plantcounty, x.housenumber, x.housenumberext,
       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, (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = pl.language_id) prod_desc,
       s.code size_code, (select sd.description from sizedefinition_desc sd where sd.sizedefinition_id = s.sizedefinition_id and sd.language_id = pl.language_id) size_desc,
       f.code finMeth_code, (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 outer join finishingmethod f on ub.finishingmethod_id = f.finishingmethod_id,
     product p, sizedefinition s, businessunit bu, plant pl, address x
where ub.product_link_id = p.product_id and
      ub.sizedefinition_link_id = s.sizedefinition_id and
      ub.businessunit_id = bu.businessunit_id and
      bu.plant_id = pl.plant_id and pl.address_id = x.address_id
union
select pl.code plant_code, pl.name plant_name, pl.phoneno plant_phone, pl.faxno plant_fax,
       x.street plantstreet, x.street2 plantstreet2, x.zipcode plantzipcode,
       x.city plantcity, x.state plantstate, x.county plantcounty, x.housenumber, x.housenumberext,
       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 prod_desc,
       null size_code, null size_desc,
       null finMeth_code, null finMeth_desc
from businessunit bu, plant pl, address x
where  bu.plant_id = pl.plant_id and pl.address_id = x.address_id

/
create or replace view V_UNIQUEBUNDLESTICKER_SGS
 (REPORTPARAM_ID, 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, PROD_DESC, SIZE_CODE, SIZE_DESC, FINMETH_CODE, FINMETH_DESC, STRING_VALUE2)
as select rp.reportparam_id, 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, (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = pl.language_id) prod_desc,
       s.code size_code, (select sd.description from sizedefinition_desc sd where sd.sizedefinition_id = s.sizedefinition_id and sd.language_id = pl.language_id) size_desc,
       f.code finMeth_code, (select fd.description from finishingmethod_desc fd where fd.finishingmethod_id = f.finishingmethod_id and fd.language_id = pl.language_id) finMeth_desc,
       rp.string_value2
from uniquebundle ub left outer join finishingmethod f on ub.finishingmethod_id = f.finishingmethod_id,
     product p, sizedefinition s, businessunit bu, plant pl, reportparam rp
where ub.product_link_id = p.product_id and
      ub.sizedefinition_link_id = s.sizedefinition_id and
      ub.businessunit_id = bu.businessunit_id and
      bu.plant_id = pl.plant_id and
      ub.primaryid = rp.string_value and
      ub.businessunit_id = rp.number_value
union
select rp.reportparam_id, 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 prod_desc,
       null size_code, null size_desc,
       null finMeth_code, null finMeth_desc,
       rp.string_value2
from businessunit bu, plant pl, reportparam rp
where  bu.plant_id = pl.plant_id
and rp.string_value = 'ERRORSTICKER'
and rp.number_value = bu.businessunit_id

/
create or replace view V_UNIQUEITEMSONSTOCK
 (STOCKCODE, STOCKNAME, RELATEDCUSTOMER_ID, CUSTOMEROWNED, RELATEDCUSTOMER, PRODUCTCODE, SEQUENCENUMBER, SIZECODE, COLORCODE, FABRICCODE, PRODUCTDESC, SIZEDESC, COLORDESC, FABRICDESC, PRIMARYID, WASHESTOTAL, REPAIRSTOTAL, WEEKSUSED, WEEKSSTOCK, PURCHASEDATE, LASTISSUEDATE, LASTSCANDATE, QUALITYGRADECODE, QUALITYGRADEPRIORITY, MODIFICATIONCODE, ISMODIFIED, LANGUAGECODE)
as select 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, psz.sequencenumber, sz.code sizeCode, color.code colorCode, fabric.code fabricCode
, ( 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(GETCURRENTDATETIME(), 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 join modification modif on uqm.modification_id = modif.modification_id )
           on uq.uniqueitem_id = uqm.uniqueitem_id
, status, stockroomlocation skl, stockroom sk
, uniqueitemfixedinfo uqfx
    left outer join qualitygrade qg on uqfx.qualitygrade_id = qg.qualitygrade_id
, product prd, sizedefinition sz, productsize psz, color, fabric
, languages
where
    uq.status_id = status.status_id
    and status.statustype = 'UI'
        and status.code = '10'  -- stock
and uq.uniqueitem_id = uqfx.uniqueitem_id
    and uqfx.stockroomlocation_id = skl.stockroomlocation_id -- row, location
        and skl.stockroom_id = sk.stockroom_id
and uq.product_id = prd.product_id
    and prd.product_id = psz.product_id
        and psz.sizedefinition_id = sz.sizedefinition_id
and uq.sizedefinition_id = sz.sizedefinition_id
and prd.color_id = color.color_id
and prd.fabric_id = fabric.fabric_id

/
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 V2.REPORTPARAM_ID             REPORTPARAM_ID,
       getweeksinyear(yeardel) weeksinyear,
       V1.CUSTOMERID                 CUSTOMERID,
       V1.CUSTOMERNUMBER             CUSTOMERNUMBER,
       V1.CUSTOMERNAME               CUSTOMERNAME,
       V1.DEPARTMENTID               DEPARTMENTID,
       V1.DEPARTMENTNUMBER           DEPARTMENTNUMBER,
       V1.DEPARTMENTDESC             DEPARTMENTDESC,
       V1.DISTRIBUTIONPOINTID        DISTRIBUTIONPOINTID,
       V1.DISTRIBUTIONPOINTNUMBER    DISTRIBUTIONPOINTNUMBER,
       V1.DISTRIBUTIONPOINTDESC      DISTRIBUTIONPOINTDESC,
       V1.PRODUCT_ID                 PRODUCT_ID,
       V1.PRODUCTCODE                PRODUCTCODE,
       V1.PRODUCTDESCRIPTION         PRODUCTDESCRIPTION,
       V1.SIZEDEFINITION_ID          SIZEDEFINITION_ID,
       V1.SIZEDEFINITIONCODE         SIZEDEFINITIONCODE,
       V1.SIZEDESCRIPTION            SIZEDESCRIPTION,
       V1.FINISHINGMETHOD_ID         FINISHINGMETHOD_ID,
       V1.FINISHINGMETHODCODE        FINISHINGMETHODCODE,
       V1.FINISHINGMETHODDESCRIPTION FINISHINGMETHODDESCRIPTION,
       V1.QTYPOOL                    QTYPOOL,
       V1.CIRCINVENTORY              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) */    -- HINT TO USE INDEX ON DISTRIBUTIONPOINT
                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,
         CUSTOMER               C,
         DEPARTMENT             D,
         DISTRIBUTIONPOINT      DP,
         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 D.DEPARTMENT_ID = DP.DEPARTMENT_ID
     AND C.CUSTOMER_ID = D.CUSTOMER_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,
               DEPARTMENT           D,
               DISTRIBUTIONPOINT    DP,
               REPORTPARAM          RP
         WHERE DH.DISTRIBUTIONPOINT_LINK_ID = DP.DISTRIBUTIONPOINT_ID
           AND D.DEPARTMENT_ID = DP.DEPARTMENT_ID
           AND D.CUSTOMER_ID = RP.NUMBER_VALUE
           AND DH.DELIVERYDATE >= RP.DATE_VALUE1
           AND DH.DELIVERYDATE <= RP.DATE_VALUE2
--           AND RP.REPORTPARAM_ID = 1767653
         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, GETCURRENTDATE() currentdate,
  cl.clientnumber, cl.name clientname,
  d.departmentnumber, d.description departmentdesc, dr.roomnumber,
  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 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 client 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,
  uniqueresidentialitem uri,
  uniqueresidentialitemproduct urip,
  product pr, sizedefinition sz, finishingmethod fm,
  status st, stay sy,
  languages
where cl.client_id = uri.client_id
  and uri.uniqueresidentialitem_id = urip.uniqueresidentialitem_id
  and urip.product_id = pr.product_id
  and urip.sizedefinition_id = sz.sizedefinition_id
  and urip.finishingmethod_id = fm.finishingmethod_id
  and uri.status_id = st.status_id
  and uri.stay_id = sy.stay_id
union all
select cl.customer_id, st.code statuscode,
  sy.stay_id,
  uri.statuschangedate, uri.laststaydate, GETCURRENTDATE() 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 client 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,
  uniqueresidentialitem uri,
  status st, stay sy,
  languages
where cl.client_id = uri.client_id
  and uri.status_id = st.status_id
  and uri.stay_id = sy.stay_id
  and not exists (select * from uniqueresidentialitemproduct urip2
    where urip2.uniqueresidentialitem_id = uri.uniqueresidentialitem_id)

/
create or replace view V_UNIQUERESIDENTIALITEMS_CBD
 (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, DATEINACTIVE)
as select cl.customer_id, st.code statuscode,
  sy.stay_id,
  uri.statuschangedate, uri.laststaydate, GETCURRENTDATE() currentdate,
  cl.clientnumber, cl.name clientname,
  d.departmentnumber, d.description departmentdesc, dr.roomnumber,
  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 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,
  Cl.Dateinactive
from client 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,
  uniqueresidentialitem uri,
  uniqueresidentialitemproduct urip,
  product pr, sizedefinition sz, finishingmethod fm,
  status st, stay sy,
  languages
where cl.client_id = uri.client_id
  and uri.uniqueresidentialitem_id = urip.uniqueresidentialitem_id
  and urip.product_id = pr.product_id
  and urip.sizedefinition_id = sz.sizedefinition_id
  and urip.finishingmethod_id = fm.finishingmethod_id
  and uri.status_id = st.status_id
  and uri.stay_id = sy.stay_id
union all
select cl.customer_id, st.code statuscode,
  sy.stay_id,
  uri.statuschangedate, uri.laststaydate, GETCURRENTDATE() 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,
  Cl.Dateinactive
  from client 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,
  uniqueresidentialitem uri,
  status st, stay sy,
  languages
where cl.client_id = uri.client_id
  and uri.status_id = st.status_id
  and uri.stay_id = sy.stay_id
  and not exists (select * 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 urif.uniqueresidentialitem_id, f.flag_id, l.code languagecode,
  f.code flagcode, fd.description flagdesc,
  urif.startdate, urif.freetextitem
from uniqueresidentialitemflag urif,
  flag f
    left outer join (flag_desc fd
      left outer join languages l
        on fd.language_id = l.language_id)
    on fd.flag_id = f.flag_id
where 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_USAGEREPORT_ECL
 (CUSTOMERNUMBER, CUSTOMERNAME, PRODUCT_CODE, PRODUCTLISTPERDISTRIBPOINT_ID, PRODUCT_DESC, DELIVERYDATE, DELAMOUNT, DELREQUIRED, DELFOC, REJECTS, ADJUSTMENTS, STOCKLEVEL, MINIMUMTURNAROUND, RENTPRICE, LANGUAGE_CODE, LANGUAGE_ID, REPORTPARAM_ID, CUSTOMER_ID, PRODUCT_ID, SIZEDEFINITION_ID, FINISHINGMETHOD_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(pnl.standardamount+pnl.variationamount) from packingnote pn join packingnoteline pnl on pn.packingnote_id=pnl.packingnote_id
         where  pn.distributionpoint_id = dp.distributionpoint_id
         and pnl.product_id = pr.product_id
         and pn.deliverydate >= rp.date_value1 and pn.deliverydate <= rp.date_value2), 0) delrequired,
         coalesce((select sum(pnl.nochargeprevshortage) from packingnote pn join packingnoteline pnl on pn.packingnote_id=pnl.packingnote_id
         where  pn.distributionpoint_id = dp.distributionpoint_id
         and pnl.product_id = pr.product_id
         and pn.deliverydate >= rp.date_value1 and pn.deliverydate <= rp.date_value2), 0) delfoc,
coalesce((select sum(dv.amount) from deliveryvariations dv
  inner join packingnote pn on pn.packingnote_id = dv.packingnote_id and pn.status_id <>8  -- Added to take out cancelled ones
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,
PACK_PRICE.Rent_Price(plpc.customer_id, plpc.product_id, plpc.sizedefinition_id, plpc.finishingmethod_id) RentPrice,
lan.code Language_Code, lan.language_id, rp.reportparam_id, plpc.customer_id, plpc.product_id, plpc.sizedefinition_id, plpc.finishingmethod_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(pnl.standardamount+pnl.variationamount) from packingnote pn join packingnoteline pnl on pn.packingnote_id=pnl.packingnote_id
         where  pn.distributionpoint_id = dp.distributionpoint_id
         and pnl.product_id = pr.product_id
         and pn.deliverydate >= rp.date_value1 and pn.deliverydate <= rp.date_value2), 0) delrequired,
         coalesce((select sum(pnl.nochargeprevshortage) from packingnote pn join packingnoteline pnl on pn.packingnote_id=pnl.packingnote_id
         where  pn.distributionpoint_id = dp.distributionpoint_id
         and pnl.product_id = pr.product_id
         and pn.deliverydate >= rp.date_value1 and pn.deliverydate <= rp.date_value2), 0) delfoc,
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,
PACK_PRICE.Rent_Price(plpc.customer_id, plpc.product_id, plpc.sizedefinition_id, plpc.finishingmethod_id) RentPrice,
lan.code Language_Code, lan.language_id, rp.reportparam_id, plpc.customer_id, plpc.product_id, plpc.sizedefinition_id, plpc.finishingmethod_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('BatchDeliveryNote')),
          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, chain ch where ih.deltocustomer_link_id = del.customer_id and del.chain_id = ch.chain_id) DelChain_code
, (select ch.code from customer bill, chain ch where ih.billtocustomer_link_id = bill.customer_id and bill.chain_id = ch.chain_id) BillChain_code
, (select ch.code from customer cl, customer ma, chain ch where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.customer_id and ma.chain_id = ch.chain_id) MAChain_code
, (select ma.customernumber from customer cl, customer ma where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.customer_id) MA_number
, (select ma.name from customer cl, customer ma where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.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 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, customer delto where ih.deltocustomer_link_id = delto.customer_id and dbu.businessunit_id = delto.defaultbusinessunit_id) deltodefaultbu
, (select bbu.code from businessunit bbu, customer billto where ih.billtocustomer_link_id = billto.customer_id and bbu.businessunit_id = billto.defaultbusinessunit_id) billtodefaultbu
, (select mabu.code from businessunit mabu, customer bill, customer ma where ih.billtocustomer_link_id = bill.customer_id and bill.masteraccount_id = ma.customer_id and mabu.businessunit_id = ma.defaultbusinessunit_id) madefaultbu
, su.systemuser_id
from invoiceheader ih, invoiceline il, invoicelineproduct ip, status st
, product pr, productgroup pg
, languages lan, systemuser su
where ih.invoiceheader_id = il.invoiceheader_id and ip.invoiceline_id = il.invoiceline_id
and ip.product_link_id = pr.product_id and pr.productgroup_id = pg.productgroup_id
and ih.documenttype = 1 and ih.status_id = st.status_id 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, chain ch where ih.deltocustomer_link_id = del.customer_id and del.chain_id = ch.chain_id) DelChain_code
, (select ch.code from customer bill, chain ch where ih.billtocustomer_link_id = bill.customer_id and bill.chain_id = ch.chain_id) BillChain_code
, (select ch.code from customer cl, customer ma, chain ch where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.customer_id and ma.chain_id = ch.chain_id) MAChain_code
, (select ma.customernumber from customer cl, customer ma where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.customer_id) MA_number
, (select ma.name from customer cl, customer ma where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.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
, (select sum(pnl.deliveredamount) from packingnoteline pnl--, packingnote pn
where --pnl.packingnote_id = pn.packingnote_id and
pnl.invoiceheader_id = ih.invoiceheader_id and pnl.product_id = ip.product_link_id) QTYWashLog
--, il.billedqty QTYWashLog, il.amount TurnoverLog
--, (select sum(pnl.deliveredamount) * F_WashPrice(ih.billtocustomer_link_id, ip.product_link_id, ip.sizedefinition_link_id, ip.finishingmethod_id, ih.invoicedate) from packingnoteline pnl, packingnote pn where pnl.packingnote_id = pn.packingnote_id and pn.invoiceheader_id = ih.invoiceheader_id and pnl.product_id = ip.product_link_id) TurnoverLog
, (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--, packingnote pn where pnl.packingnote_id = pn.packingnote_id and
          where pnl.invoiceheader_id = ih.invoiceheader_id and pnl.product_id = ip.product_link_id) TurnoverLog
, 0 QTYWashCog, 0 TurnoverCog, 0 SalesQty, 0 SalesTurnover
, lan.code Lan_code
, (select dbu.code from businessunit dbu, customer delto where ih.deltocustomer_link_id = delto.customer_id and dbu.businessunit_id = delto.defaultbusinessunit_id) deltodefaultbu
, (select bbu.code from businessunit bbu, customer billto where ih.billtocustomer_link_id = billto.customer_id and bbu.businessunit_id = billto.defaultbusinessunit_id) billtodefaultbu
, (select mabu.code from businessunit mabu, customer bill, customer ma where ih.billtocustomer_link_id = bill.customer_id and bill.masteraccount_id = ma.customer_id and mabu.businessunit_id = ma.defaultbusinessunit_id) madefaultbu
, su.systemuser_id
from invoiceheader ih, invoiceline il, invoicelineproduct ip, status st
, product pr, productgroup pg
, languages lan, systemuser su
where ih.invoiceheader_id = il.invoiceheader_id and ip.invoiceline_id = il.invoiceline_id
and ip.product_link_id = pr.product_id and pr.productgroup_id = pg.productgroup_id
and ih.documenttype = 1 and ih.status_id = st.status_id 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, chain ch where ih.deltocustomer_link_id = del.customer_id and del.chain_id = ch.chain_id) DelChain_code
, (select ch.code from customer bill, chain ch where ih.billtocustomer_link_id = bill.customer_id and bill.chain_id = ch.chain_id) BillChain_code
, (select ch.code from customer cl, customer ma, chain ch where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.customer_id and ma.chain_id = ch.chain_id) MAChain_code
, (select ma.customernumber from customer cl, customer ma where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.customer_id) MA_number
, (select ma.name from customer cl, customer ma where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.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
, (select sum(pnl.deliveredcogqty) from packingnoteline pnl--, packingnote pn where pnl.packingnote_id = pn.packingnote_id and
where pnl.invoiceheader_id = ih.invoiceheader_id and pnl.product_id = ip.product_link_id) QTYWashCog
--, il.billedqty QTYWashCog, il.amount TurnoverCog
--, (select sum(pnl.deliveredcogqty) * F_WashPrice(ih.billtocustomer_link_id, ip.product_link_id, ip.sizedefinition_link_id, ip.finishingmethod_id, ih.invoicedate) from packingnoteline pnl, packingnote pn where pnl.packingnote_id = pn.packingnote_id and pn.invoiceheader_id = ih.invoiceheader_id and pnl.product_id = ip.product_link_id) TurnoverCog
, (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--, packingnote pn where pnl.packingnote_id = pn.packingnote_id and
          where pnl.invoiceheader_id = ih.invoiceheader_id and pnl.product_id = ip.product_link_id) TurnoverCog
, 0 SalesQty, 0 SalesTurnover
, lan.code Lan_code
, (select dbu.code from businessunit dbu, customer delto where ih.deltocustomer_link_id = delto.customer_id and dbu.businessunit_id = delto.defaultbusinessunit_id) deltodefaultbu
, (select bbu.code from businessunit bbu, customer billto where ih.billtocustomer_link_id = billto.customer_id and bbu.businessunit_id = billto.defaultbusinessunit_id) billtodefaultbu
, (select mabu.code from businessunit mabu, customer bill, customer ma where ih.billtocustomer_link_id = bill.customer_id and bill.masteraccount_id = ma.customer_id and mabu.businessunit_id = ma.defaultbusinessunit_id) madefaultbu
, su.systemuser_id
from invoiceheader ih, invoiceline il, invoicelineproduct ip, status st
, product pr, productgroup pg
, languages lan, systemuser su
where ih.invoiceheader_id = il.invoiceheader_id and ip.invoiceline_id = il.invoiceline_id
and ip.product_link_id = pr.product_id and pr.productgroup_id = pg.productgroup_id
and ih.documenttype = 1 and ih.status_id = st.status_id 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, chain ch where ih.deltocustomer_link_id = del.customer_id and del.chain_id = ch.chain_id) DelChain_code
, (select ch.code from customer bill, chain ch where ih.billtocustomer_link_id = bill.customer_id and bill.chain_id = ch.chain_id) BillChain_code
, (select ch.code from customer cl, customer ma, chain ch where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.customer_id and ma.chain_id = ch.chain_id) MAChain_code
, (select ma.customernumber from customer cl, customer ma where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.customer_id) MA_number
, (select ma.name from customer cl, customer ma where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.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 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, customer delto where ih.deltocustomer_link_id = delto.customer_id and dbu.businessunit_id = delto.defaultbusinessunit_id) deltodefaultbu
, (select bbu.code from businessunit bbu, customer billto where ih.billtocustomer_link_id = billto.customer_id and bbu.businessunit_id = billto.defaultbusinessunit_id) billtodefaultbu
, (select mabu.code from businessunit mabu, customer bill, customer ma where ih.billtocustomer_link_id = bill.customer_id and bill.masteraccount_id = ma.customer_id and mabu.businessunit_id = ma.defaultbusinessunit_id) madefaultbu
, su.systemuser_id
from invoiceheader ih, invoiceline il, invoicelineproduct ip, status st
, product pr, productgroup pg
, languages lan, systemuser su
where ih.invoiceheader_id = il.invoiceheader_id and ip.invoiceline_id = il.invoiceline_id
and ip.product_link_id = pr.product_id and pr.productgroup_id = pg.productgroup_id
and ih.documenttype = 1 and ih.status_id = st.status_id 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_WASHRENTREVENUEPERCUST_SMG
 (SELECT_NR, 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
1 select_nr, 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, chain ch where ih.deltocustomer_link_id = del.customer_id and del.chain_id = ch.chain_id) DelChain_code
, (select ch.code from customer bill, chain ch where ih.billtocustomer_link_id = bill.customer_id and bill.chain_id = ch.chain_id) BillChain_code
, (select ch.code from customer cl, customer ma, chain ch where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.customer_id and ma.chain_id = ch.chain_id) MAChain_code
, (select ma.customernumber from customer cl, customer ma where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.customer_id) MA_number
, (select ma.name from customer cl, customer ma where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.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, coalesce(ilc.amount, il.amount) 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 theoreticalweight
, il.billedqty QTYRent, 0 QTYWashLog, coalesce(ilc.amount, il.amount) TurnoverLog, 0 QTYWashCog, 0 TurnoverCog, 0 SalesQty, 0 SalesTurnover
, lan.code Lan_code
, (select dbu.code from businessunit dbu, customer delto where ih.deltocustomer_link_id = delto.customer_id and dbu.businessunit_id = delto.defaultbusinessunit_id) deltodefaultbu
, (select bbu.code from businessunit bbu, customer billto where ih.billtocustomer_link_id = billto.customer_id and bbu.businessunit_id = billto.defaultbusinessunit_id) billtodefaultbu
, (select mabu.code from businessunit mabu, customer bill, customer ma where ih.billtocustomer_link_id = bill.customer_id and bill.masteraccount_id = ma.customer_id and mabu.businessunit_id = ma.defaultbusinessunit_id) madefaultbu
, su.systemuser_id
from invoiceheader ih, invoiceline il
     left outer join invoicelinecurrency ilc on ilc.invoiceline_id = il.invoiceline_id and ilc.invoicecurrencytype = 2
, invoicelineproduct ip, status st, product pr, productgroup pg, languages lan, systemuser su
where ih.invoiceheader_id = il.invoiceheader_id and ip.invoiceline_id = il.invoiceline_id
and ip.product_link_id = pr.product_id and pr.productgroup_id = pg.productgroup_id
and ih.documenttype = 1 and ih.status_id = st.status_id 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
2 select_nr, 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, chain ch where ih.deltocustomer_link_id = del.customer_id and del.chain_id = ch.chain_id) DelChain_code
, (select ch.code from customer bill, chain ch where ih.billtocustomer_link_id = bill.customer_id and bill.chain_id = ch.chain_id) BillChain_code
, (select ch.code from customer cl, customer ma, chain ch where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.customer_id and ma.chain_id = ch.chain_id) MAChain_code
, (select ma.customernumber from customer cl, customer ma where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.customer_id) MA_number
, (select ma.name from customer cl, customer ma where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.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, coalesce(ilc.amount, il.amount) 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
, (select sum(pnl.deliveredamount) from packingnoteline pnl--, packingnote pn
where --pnl.packingnote_id = pn.packingnote_id and
pnl.invoiceheader_id = ih.invoiceheader_id and pnl.product_id = ip.product_link_id) QTYWashLog
--, il.billedqty QTYWashLog, il.amount TurnoverLog
--, (select sum(pnl.deliveredamount) * F_WashPrice(ih.billtocustomer_link_id, ip.product_link_id, ip.sizedefinition_link_id, ip.finishingmethod_id, ih.invoicedate) from packingnoteline pnl, packingnote pn where pnl.packingnote_id = pn.packingnote_id and pn.invoiceheader_id = ih.invoiceheader_id and pnl.product_id = ip.product_link_id) TurnoverLog
, (select sum(pnl.deliveredamount) * coalesce(ilc.price, 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--, packingnote pn where pnl.packingnote_id = pn.packingnote_id and
          where pnl.invoiceheader_id = ih.invoiceheader_id and pnl.product_id = ip.product_link_id) TurnoverLog
, 0 QTYWashCog, 0 TurnoverCog, 0 SalesQty, 0 SalesTurnover
, lan.code Lan_code
, (select dbu.code from businessunit dbu, customer delto where ih.deltocustomer_link_id = delto.customer_id and dbu.businessunit_id = delto.defaultbusinessunit_id) deltodefaultbu
, (select bbu.code from businessunit bbu, customer billto where ih.billtocustomer_link_id = billto.customer_id and bbu.businessunit_id = billto.defaultbusinessunit_id) billtodefaultbu
, (select mabu.code from businessunit mabu, customer bill, customer ma where ih.billtocustomer_link_id = bill.customer_id and bill.masteraccount_id = ma.customer_id and mabu.businessunit_id = ma.defaultbusinessunit_id) madefaultbu
, su.systemuser_id
from invoiceheader ih, invoiceline il
     left outer join invoicelinecurrency ilc on ilc.invoiceline_id = il.invoiceline_id and ilc.invoicecurrencytype = 2
, invoicelineproduct ip, status st, product pr, productgroup pg, languages lan, systemuser su
where ih.invoiceheader_id = il.invoiceheader_id and ip.invoiceline_id = il.invoiceline_id
and ip.product_link_id = pr.product_id and pr.productgroup_id = pg.productgroup_id
and ih.documenttype = 1 and ih.status_id = st.status_id 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
3 select_nr, 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, chain ch where ih.deltocustomer_link_id = del.customer_id and del.chain_id = ch.chain_id) DelChain_code
, (select ch.code from customer bill, chain ch where ih.billtocustomer_link_id = bill.customer_id and bill.chain_id = ch.chain_id) BillChain_code
, (select ch.code from customer cl, customer ma, chain ch where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.customer_id and ma.chain_id = ch.chain_id) MAChain_code
, (select ma.customernumber from customer cl, customer ma where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.customer_id) MA_number
, (select ma.name from customer cl, customer ma where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.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, coalesce(ilc.amount, il.amount) 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
, (select sum(pnl.deliveredcogqty) from packingnoteline pnl--, packingnote pn where pnl.packingnote_id = pn.packingnote_id and
where pnl.invoiceheader_id = ih.invoiceheader_id and pnl.product_id = ip.product_link_id) QTYWashCog
--, il.billedqty QTYWashCog, il.amount TurnoverCog
--, (select sum(pnl.deliveredcogqty) * F_WashPrice(ih.billtocustomer_link_id, ip.product_link_id, ip.sizedefinition_link_id, ip.finishingmethod_id, ih.invoicedate) from packingnoteline pnl, packingnote pn where pnl.packingnote_id = pn.packingnote_id and pn.invoiceheader_id = ih.invoiceheader_id and pnl.product_id = ip.product_link_id) TurnoverCog
, (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--, packingnote pn where pnl.packingnote_id = pn.packingnote_id and
          where pnl.invoiceheader_id = ih.invoiceheader_id and pnl.product_id = ip.product_link_id) TurnoverCog
, 0 SalesQty, 0 SalesTurnover
, lan.code Lan_code
, (select dbu.code from businessunit dbu, customer delto where ih.deltocustomer_link_id = delto.customer_id and dbu.businessunit_id = delto.defaultbusinessunit_id) deltodefaultbu
, (select bbu.code from businessunit bbu, customer billto where ih.billtocustomer_link_id = billto.customer_id and bbu.businessunit_id = billto.defaultbusinessunit_id) billtodefaultbu
, (select mabu.code from businessunit mabu, customer bill, customer ma where ih.billtocustomer_link_id = bill.customer_id and bill.masteraccount_id = ma.customer_id and mabu.businessunit_id = ma.defaultbusinessunit_id) madefaultbu
, su.systemuser_id
from invoiceheader ih, invoiceline il
     left outer join invoicelinecurrency ilc on ilc.invoiceline_id = il.invoiceline_id and ilc.invoicecurrencytype = 2
, invoicelineproduct ip, status st, product pr, productgroup pg, languages lan, systemuser su
where ih.invoiceheader_id = il.invoiceheader_id and ip.invoiceline_id = il.invoiceline_id
and ip.product_link_id = pr.product_id and pr.productgroup_id = pg.productgroup_id
and ih.documenttype = 1 and ih.status_id = st.status_id 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
4 select_nr, 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, chain ch where ih.deltocustomer_link_id = del.customer_id and del.chain_id = ch.chain_id) DelChain_code
, (select ch.code from customer bill, chain ch where ih.billtocustomer_link_id = bill.customer_id and bill.chain_id = ch.chain_id) BillChain_code
, (select ch.code from customer cl, customer ma, chain ch where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.customer_id and ma.chain_id = ch.chain_id) MAChain_code
, (select ma.customernumber from customer cl, customer ma where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.customer_id) MA_number
, (select ma.name from customer cl, customer ma where ih.billtocustomer_link_id = cl.customer_id and cl.masteraccount_id = ma.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, coalesce(ilc.amount, il.amount) 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 theoreticalweight
, 0 QTYRent, 0 QTYWashLog, 0 TurnoverLog, 0 QTYWashCog, 0 TurnoverCog, il.billedqty SalesQty, coalesce(ilc.amount, il.amount) SalesTurnover
, lan.code Lan_code
, (select dbu.code from businessunit dbu, customer delto where ih.deltocustomer_link_id = delto.customer_id and dbu.businessunit_id = delto.defaultbusinessunit_id) deltodefaultbu
, (select bbu.code from businessunit bbu, customer billto where ih.billtocustomer_link_id = billto.customer_id and bbu.businessunit_id = billto.defaultbusinessunit_id) billtodefaultbu
, (select mabu.code from businessunit mabu, customer bill, customer ma where ih.billtocustomer_link_id = bill.customer_id and bill.masteraccount_id = ma.customer_id and mabu.businessunit_id = ma.defaultbusinessunit_id) madefaultbu
, su.systemuser_id
from invoiceheader ih, invoiceline il
     left outer join invoicelinecurrency ilc on ilc.invoiceline_id = il.invoiceline_id and ilc.invoicecurrencytype = 2
, invoicelineproduct ip, status st, product pr, productgroup pg, languages lan, systemuser su
where ih.invoiceheader_id = il.invoiceheader_id and ip.invoiceline_id = il.invoiceline_id
and ip.product_link_id = pr.product_id and pr.productgroup_id = pg.productgroup_id
and ih.documenttype = 1 and ih.status_id = st.status_id 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)
as select GB.GarmentBatch_ID, GB.GARMENTBATCHNUMBER, GBSRT.BoxNumber,
       WR.WearerNumber, WR.Fullname WearerName, --cast(
       wr.remark --as varchar2(60))
       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, DP.Description DelPoint_Desc,
       d.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
from GarmentBatch GB
     inner join GarmentBatchSort GBSRT
           inner join GarmentBatchScan GBSCAN
                 inner join UniqueItemNonPool UINP
                       inner join WearerEmployment WE
                                  inner join distributionpoint distp
                                  on distp.distributionpoint_id = we.distributionpoint_id
                                  inner join department d
                                  on distp.department_id = d.department_id
                             inner join Wearer WR on WR.Wearer_ID = WE.Wearer_ID
                             left outer join Locker LO on LO.Locker_ID = WE.Locker_Id
                       on WE.WearerEmployment_ID = UINP.WearerEmployment_ID
                       inner join UniqueItem UI
                             inner join product pr on pr.product_id = ui.product_id
                       on UI.UniqueItem_ID = UINP.UniqueItem_ID
                 on UINP.UniqueItem_ID = GBSCAN.UniqueItem_ID
                 inner join DeliveryScan DS
                       inner join PackingNote PN
                             left outer join Route RO on RO.Route_Id = PN.Route_Id
                             --inner join Route RO on RO.Route_Id = PN.Route_Id
                       on PN.Packingnote_Id = DS.Packingnote_Id
                       inner join Deliverypoint DP
                             inner join Address ADR on ADR.Address_Id = DP.Deliveryaddress_Id
                       on DP.Deliverypoint_Id = DS.Deliverypoint_Link_Id
                 on DS.UniqueItem_Link_ID = GBSCAN.UniqueItem_ID
           on GBSCAN.GarmentBatchSort_ID = GBSRT.GarmentBatchSort_ID
           inner join customer cu on cu.customer_id = GBSRT.Customer_Link_Id
     on GBSRT.GarmentBatch_ID = GB.GarmentBatch_ID
     inner join BusinessUnit BU
          inner join Plant PL
                inner join Address PLAD on PLAD.Address_Id = PL.Address_Id
          on PL.Plant_Id = BU.Plant_Id
     on BU.Businessunit_Id = GB.Businessunit_Id,
     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_WEARERINVENTORYLIST_CBD
 (CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, VATNUMBER, CUSTOMERCITY, WEARERNUMBER, WEARERNAME, ADMINNUMBER, EMPLOYMENT, WEARERFUNCTIONCODE, WEARERFUNCTIONDESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, COSTCENTERCODE, COSTCENTERDESCRIPTION, BANK, LOCKER, GARMENTDISPENSERCODE, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDEFINITIONCODE, MODIFICATIONSQTY, STARTDATE, ENDDATE, SEASONDESCRIPTION, EMBLEMTEMPLATEDESC, WEARERACTIVE, DELIVERYPOINTCODE, DELIVERYPOINTDESC, LANGUAGECODE, INVOICEHEADER_ID
, INVOICENUMBER, ACTIVITYREFERENCE, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, DELTOSTREET, DELTOZIPCODE, DELTOCITY, CITY, ZIPCODE, STREET, CONTACTPERSONNAME, INVOICE_STARTDATE, INVOICE_ENDDATE, DELTOSENDINVOICETO, INVOICEDATE, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESC, WEARERSEARCHNAME, WEARERFIRSTNAME, MAXINVENTORY, CHANGESPERWEEK, CIRCINVENTORY, QTYRENTEDDEPOSITSTOCK, RENTSTOP
, BUDESCRIPTION, PLANTCODE, PLANTNAME, PLANTWEBSITE, PLANTEMAIL, PLANTSTREET, PLANTZIPCODE, PLANTCITY, PLANTPHONENO, PLANTFAXNO, SALESAREA)
as select cu.customer_id,
  cu.customernumber, cu.name CustomerName, cu.vatnumber, address.city CustomerCity, we.wearernumber
, we.fullname WearerName, we.customeremployeenumber AdminNumber, wey.sequencenumber Employment
, wearerfunction.code wearerfunctionCode, wearerfunction.description wearerfunctionDesc
, d.departmentnumber, d.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
, sd.code sizedefinitionCode--, wi.maxinventory, wi.changesperweek, wi.circinventory
, (select count(wm.modification_id) from wearerinventorymodification wm where wm.wearerinventory_id = wi.wearerinventory_id) ModificationsQty
, wi.dateactive StartDate, wi.dateinactive EndDate
, (select seasontype_desc.description from seasontype_desc,season where wi.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
, GETDATEDIFF(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) wearerActive
, coalesce(d1.code, d2.code, d3.code) deliverypointCode, coalesce(d1.description, d2.description, d3.description) deliverypointDesc
, languages.code languageCode
, ih.invoiceheader_id, ih.invoicenumber, ih.activityreference, ih.startweek, ih.endweek, ih.startmonth, ih.endmonth
, ih.billtocustomernumber, ih.billtocustomername, ih.deltocustomernumber, ih.deltocustomername, ih.deltostreet, ih.deltozipcode, ih.deltocity
, ih.city, ih.zipcode, ih.street, ih.contactpersonname, ih.startdate Invoice_startdate, ih.enddate Invoice_enddate
, cu.sendinvoiceto deltosendinvoiceto, ih.invoicedate
, dp.distributionpointnumber, dp.description distributionpointdesc, we.searchname WearerSearchname, we.firstname WearerFirstname
, sq.maxinv maxinventory, sq.changesperweek, --sq.qtyrentedperpiece circinventory
sq.totalcircinv circinventory
, sq.qtyrenteddepositstock, (sq.qtyrentstop+ sq.qtycustomerrentstop) RentStop--, F_GetCustType_smg(ih.invoiceheader_id) custtype
, bu.description budescription, plant.code plantcode, plant.name plantname
, plant.website plantwebsite, plant.email plantemail, plantaddress.street plantstreet
, plantaddress.zipcode plantzipcode, plantaddress.city plantcity, plant.phoneno plantphoneno, plant.faxno plantfaxno
, Cu.Salesarea_Id Salesarea
from customer cu, weareremployment wey
    left outer join deliverypoint d1 on wey.deliverypoint_id = d1.deliverypoint_id
    left outer join wearerfunction on (wey.wearerfunction_id = wearerfunction.wearerfunction_id)
    left outer join locker
         inner join deliverypoint d2 on locker.deliverypoint_id = d2.deliverypoint_id
    on wey.locker_id = locker.locker_id
    left outer join garmentdispenser
         inner join deliverypoint d3 on d3.deliverypoint_id = garmentdispenser.deliverypoint_id
    on wey.garmentdispenser_id = garmentdispenser.garmentdispenser_id
, wearer we, address, distributionpoint dp, department d, costcenter
, wearerinventory wi
  left outer join emblemtemplate on emblemtemplate.emblemtemplate_id = wi.emblemtemplate_id
, product prd, sizedefinition sd, languages, invoiceheader ih
, statusquoheader qh, sqitemincirculation sq
, businessunit bu, plant, address plantaddress
where ih.deltocustomer_link_id = cu.customer_id
and we.customer_id = cu.customer_id
and cu.visitaddress_id = address.address_id
and we.wearer_id = wey.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 = costcenter.costcenter_id
        and costcenter.customer_id = cu.customer_id
and wey.weareremployment_id = wi.weareremployment_id
and wi.product_id = prd.product_id
and wi.sizedefinition_id = sd.sizedefinition_id
and (wi.dateinactive > coalesce(ih.startdate, ih.invoicedate)
    or wi.circinventory <> 0
    or wi.freeofchargeqty <> 0)
and coalesce(ih.splitupcode, costcenter.code) = costcenter.code
         and sq.customer_link_id = ih.deltocustomer_link_id
         and qh.statusquotype = 1
         and qh.year = year(ih.enddate)
         and qh.week = (select max(a.week) from statusquoheader a, sqitemincirculation b where
                       a.statusquoheader_id = b.statusquoheader_id and a.statusquotype = 1
                       and a.year = year(ih.enddate) and a.statusquodate <= ih.enddate )
         and sq.statusquoheader_id = qh.statusquoheader_id
         and sq.totalcircinv > 0
         and sq.weareremployment_link_id = wey.weareremployment_id
         and sq.product_link_id = prd.product_id
         and sq.sizedefinition_link_id = sd.sizedefinition_id
         and sq.distributionpoint_link_id = dp.distributionpoint_id
         and sq.department_link_id = d.department_id
         and wi.finishingmethod_id = sq.finishingmethod_id
and ih.invoicebusinessunit_id = bu.businessunit_id
and bu.plant_id = plant.plant_id
and plant.address_id = plantaddress.address_id

/
create or replace view V_WEARERINVENTORYLIST_SMG
 (LINE, CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, VATNUMBER, CUSTOMERCITY, WEARERNUMBER, WEARERNAME, ADMINNUMBER, EMPLOYMENT, WEARERFUNCTIONCODE, WEARERFUNCTIONDESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, COSTCENTERCODE, COSTCENTERDESCRIPTION, BANK, LOCKER, GARMENTDISPENSERCODE, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDEFINITIONCODE, MODIFICATIONSQTY, STARTDATE, ENDDATE, SEASONDESCRIPTION, EMBLEMTEMPLATEDESC, WEARERACTIVE, DELIVERYPOINTCODE, DELIVERYPOINTDESC, LANGUAGECODE
, INVOICEHEADER_ID, INVOICENUMBER, ACTIVITYREFERENCE, STARTWEEK, ENDWEEK, STARTMONTH, ENDMONTH, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, CITY, ZIPCODE, STREET, CONTACTPERSONNAME, INVOICE_STARTDATE, INVOICE_ENDDATE, DELTOSENDINVOICETO, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESC, WEARERSEARCHNAME, WEARERFIRSTNAME, MAXINVENTORY, CHANGESPERWEEK, CIRCINVENTORY, QTYRENTEDDEPOSITSTOCK, RENTSTOP, CUSTTYPE, PARENTINVOICEHEADER_ID
, BILTOCUSTVATNR, LEGALENTITY_LEGALNAME)
as SELECT --+ RULE
--INDEX(QH, XPKSTATUSQUOHEADER) INDEX(SQ, TIDXSQITEMINCIRCULATION) INDEX(WI, XAK1WEARERINVENTORY) INDEX(DP, XPKDISTRIBUTIONPOINT) INDEX(D, XPKDEPARTMENT) INDEX(CU, XPKCUSTOMER) INDEX(SD, XPKSIZEDEFINITION) INDEX(COSTCENTER, XAK2COSTCENTER) INDEX(WE, XAK1WEARER) INDEX(EMBLEMTEMPLATE, XPKEMBLEMTEMPLATE) INDEX(WEARERFUNCTION, XPKWEARERFUNCTION))
 1 LINE, CU.CUSTOMER_ID,
  CU.CUSTOMERNUMBER, CU.NAME CUSTOMERNAME, CU.VATNUMBER, ADDRESS.CITY CUSTOMERCITY, WE.WEARERNUMBER
, WE.FULLNAME WEARERNAME, WE.CUSTOMEREMPLOYEENUMBER ADMINNUMBER, WEY.SEQUENCENUMBER EMPLOYMENT
, WEARERFUNCTION.CODE WEARERFUNCTIONCODE, WEARERFUNCTION.DESCRIPTION WEARERFUNCTIONDESC
, D.DEPARTMENTNUMBER, D.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
, SD.CODE SIZEDEFINITIONCODE--, WI.MAXINVENTORY, WI.CHANGESPERWEEK, WI.CIRCINVENTORY
, (SELECT COUNT(WM.MODIFICATION_ID) FROM WEARERINVENTORYMODIFICATION WM WHERE WM.WEARERINVENTORY_ID = WI.WEARERINVENTORY_ID) MODIFICATIONSQTY
, WI.DATEACTIVE STARTDATE, WI.DATEINACTIVE ENDDATE
, (SELECT SEASONTYPE_DESC.DESCRIPTION FROM SEASONTYPE_DESC,SEASON WHERE WI.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
, GETDATEDIFF(GETCURRENTDATE(), WE.DATEACTIVE)*GETDATEDIFF(WE.DATEINACTIVE, GETCURRENTDATE()) WEARERACTIVE
, COALESCE((SELECT D1.CODE FROM DELIVERYPOINT D1 WHERE D1.DELIVERYPOINT_ID = WEY.DELIVERYPOINT_ID),
           (SELECT D2.CODE FROM DELIVERYPOINT D2 WHERE D2.DELIVERYPOINT_ID = LOCKER.DELIVERYPOINT_ID),
           (SELECT D3.CODE FROM DELIVERYPOINT D3 WHERE D3.DELIVERYPOINT_ID = GARMENTDISPENSER.DELIVERYPOINT_ID)) DELIVERYPOINTCODE
, COALESCE((SELECT D1.DESCRIPTION FROM DELIVERYPOINT D1 WHERE D1.DELIVERYPOINT_ID = WEY.DELIVERYPOINT_ID),
           (SELECT D2.DESCRIPTION FROM DELIVERYPOINT D2 WHERE D2.DELIVERYPOINT_ID = LOCKER.DELIVERYPOINT_ID),
           (SELECT D3.DESCRIPTION FROM DELIVERYPOINT D3 WHERE D3.DELIVERYPOINT_ID = GARMENTDISPENSER.DELIVERYPOINT_ID)) DELIVERYPOINTDESC
, LANGUAGES.CODE LANGUAGECODE
, IH.INVOICEHEADER_ID
, COALESCE((SELECT IHP.INVOICENUMBER FROM INVOICEHEADER IHP WHERE IHP.INVOICEHEADER_ID = IH.PARENTINVOICEHEADER_ID), IH.INVOICENUMBER) 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.STARTDATE INVOICE_STARTDATE, IH.ENDDATE INVOICE_ENDDATE
, CU.SENDINVOICETO DELTOSENDINVOICETO
, DP.DISTRIBUTIONPOINTNUMBER, DP.DESCRIPTION DISTRIBUTIONPOINTDESC, WE.SEARCHNAME WEARERSEARCHNAME, WE.FIRSTNAME WEARERFIRSTNAME
, SQ.MAXINV MAXINVENTORY, SQ.CHANGESPERWEEK, SQ.QTYRENTEDPERPIECE+SQ.BEYONDLIFETIMECIRC CIRCINVENTORY
, SQ.QTYRENTEDDEPOSITSTOCK, (SQ.QTYRENTSTOP+ SQ.QTYCUSTOMERRENTSTOP) RENTSTOP
, F_GETCUSTTYPE_SMG(IH.INVOICEHEADER_ID) CUSTTYPE
, IH.PARENTINVOICEHEADER_ID
, (select deb.vatnumber from customer deb where deb.customer_id=ih.billtocustomer_link_id) biltocustvatnr
, (select le.legalname from legalentity le, businessunit e where e.businessunit_id = ih.invoicebusinessunit_id and le.legalentity_id = e.legalentity_id) LegalEntity_LegalName
FROM
  CUSTOMER CU
, WEAREREMPLOYMENT WEY
    LEFT OUTER JOIN WEARERFUNCTION ON (WEARERFUNCTION.WEARERFUNCTION_ID = WEY.WEARERFUNCTION_ID)
    LEFT OUTER JOIN LOCKER ON LOCKER.LOCKER_ID = WEY.LOCKER_ID
    LEFT OUTER JOIN GARMENTDISPENSER ON GARMENTDISPENSER.GARMENTDISPENSER_ID = WEY.GARMENTDISPENSER_ID
, WEARER WE, ADDRESS, DISTRIBUTIONPOINT DP, DEPARTMENT D, COSTCENTER
, WEARERINVENTORY WI
  LEFT OUTER JOIN EMBLEMTEMPLATE ON EMBLEMTEMPLATE.EMBLEMTEMPLATE_ID = WI.EMBLEMTEMPLATE_ID
, PRODUCT PRD, SIZEDEFINITION SD, LANGUAGES
, INVOICEHEADER IH
, STATUSQUOHEADER QH, SQITEMINCIRCULATION SQ
WHERE IH.DELTOCUSTOMER_LINK_ID = CU.CUSTOMER_ID
AND WE.CUSTOMER_ID = CU.CUSTOMER_ID
AND CU.VISITADDRESS_ID = ADDRESS.ADDRESS_ID
AND WE.WEARER_ID = WEY.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 = COSTCENTER.COSTCENTER_ID
        AND COSTCENTER.CUSTOMER_ID = CU.CUSTOMER_ID
AND WEY.WEAREREMPLOYMENT_ID = NVL(WI.WEAREREMPLOYMENT_ID, 0)
AND WI.PRODUCT_ID = PRD.PRODUCT_ID
AND WI.SIZEDEFINITION_ID = SD.SIZEDEFINITION_ID
AND COALESCE(IH.SPLITUPCODE, COSTCENTER.CODE) = COSTCENTER.CODE
         AND SQ.CUSTOMER_LINK_ID = IH.DELTOCUSTOMER_LINK_ID
         AND QH.STATUSQUOTYPE = 1
         AND QH.YEAR = castvarcharasnumber(to_char(IH.ENDDATE, 'IYYY'))
         AND QH.WEEK = ( SELECT --    + INDEX(A, XIE3STATUSQUOHEADER) INDEX(B, XIE3STATUSQUOHEADER)
             MAX(A.WEEK) FROM STATUSQUOHEADER A, SQITEMINCIRCULATION B WHERE
             A.STATUSQUOHEADER_ID = B.STATUSQUOHEADER_ID AND B.CUSTOMER_LINK_ID = SQ.CUSTOMER_LINK_ID
             AND A.STATUSQUOTYPE = 1 AND A.YEAR = castvarcharasnumber(to_char(IH.ENDDATE, 'IYYY')) AND A.STATUSQUODATE <= IH.ENDDATE)
         AND SQ.STATUSQUOHEADER_ID = QH.STATUSQUOHEADER_ID
         AND SQ.WEAREREMPLOYMENT_LINK_ID = WEY.WEAREREMPLOYMENT_ID
         AND SQ.PRODUCT_LINK_ID=PRD.PRODUCT_ID
         AND SQ.SIZEDEFINITION_LINK_ID=SD.SIZEDEFINITION_ID
         AND SQ.DISTRIBUTIONPOINT_LINK_ID=DP.DISTRIBUTIONPOINT_ID
         AND SQ.DEPARTMENT_LINK_ID=D.DEPARTMENT_ID
         AND WI.FINISHINGMETHOD_ID=SQ.FINISHINGMETHOD_ID
AND (CU.SPLITINVOICESPERACTIVITY = 'N'
    OR
    (CU.SPLITINVOICESPERACTIVITY = 'Y' AND EXISTS (SELECT 1 FROM ACTIVITYPERINVOICE API, PRODUCTGROUP PG
    WHERE API.INVOICEHEADER_ID = IH.INVOICEHEADER_ID AND API.ACTIVITY_ID = PG.ACTIVITY_ID AND PRD.PRODUCTGROUP_ID = PG.PRODUCTGROUP_ID)))
UNION ALL --INDEX(CC, XAK2COSTCENTER) INDEX(WYL, XPKWEAREREMPLOYMENT_LINK)
SELECT --+ RULE
      2 LINE, CU.CUSTOMER_ID, --WEARER MOVED
  CU.CUSTOMERNUMBER, CU.NAME CUSTOMERNAME, CU.VATNUMBER, ADDRESS.CITY CUSTOMERCITY, WYL.WEARERNUMBER
, WYL.WEARERNAME WEARERNAME, NULL ADMINNUMBER, WYL.SEQUENCENUMBER EMPLOYMENT
, NULL WEARERFUNCTIONCODE, NULL WEARERFUNCTIONDESC
, D.DEPARTMENTNUMBER, D.DESCRIPTION DEPARTMENTDESCRIPTION, CC.CODE COSTCENTERCODE
, CC.DESCRIPTION COSTCENTERDESCRIPTION, NULL BANK, NULL LOCKER
, NULL 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
, SD.CODE SIZEDEFINITIONCODE--, WI.MAXINVENTORY, WI.CHANGESPERWEEK, WI.CIRCINVENTORY
, NULL MODIFICATIONSQTY
, NULL STARTDATE, NULL ENDDATE
, NULL SEASONDESCRIPTION
, NULL EMBLEMTEMPLATEDESC
, NULL WEARERACTIVE
, DLP.CODE DELIVERYPOINTCODE
, DLP.DESCRIPTION DELIVERYPOINTDESC
, LANGUAGES.CODE LANGUAGECODE
, IH.INVOICEHEADER_ID
, COALESCE((SELECT IHP.INVOICENUMBER FROM INVOICEHEADER IHP WHERE IHP.INVOICEHEADER_ID = IH.PARENTINVOICEHEADER_ID), IH.INVOICENUMBER) 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.STARTDATE INVOICE_STARTDATE, IH.ENDDATE INVOICE_ENDDATE
, CU.SENDINVOICETO DELTOSENDINVOICETO
, DP.DISTRIBUTIONPOINTNUMBER, DP.DESCRIPTION DISTRIBUTIONPOINTDESC, WYL.WEARERSEARCHNAME WEARERSEARCHNAME, WYL.WEARERNAME WEARERFIRSTNAME
, SQ.MAXINV MAXINVENTORY, SQ.CHANGESPERWEEK, SQ.QTYRENTEDPERPIECE+SQ.BEYONDLIFETIMECIRC CIRCINVENTORY
, SQ.QTYRENTEDDEPOSITSTOCK, (SQ.QTYRENTSTOP+ SQ.QTYCUSTOMERRENTSTOP) RENTSTOP
, F_GETCUSTTYPE_SMG(IH.INVOICEHEADER_ID) CUSTTYPE
, IH.PARENTINVOICEHEADER_ID
, (select deb.vatnumber from customer deb where deb.customer_id=ih.billtocustomer_link_id) biltocustvatnr
, (select le.legalname from legalentity le, businessunit e where e.businessunit_id = ih.invoicebusinessunit_id
          and le.legalentity_id = e.legalentity_id) LegalEntity_LegalName
FROM STATUSQUOHEADER QH JOIN SQITEMINCIRCULATION SQ ON QH.STATUSQUOHEADER_ID=SQ.STATUSQUOHEADER_ID
JOIN CUSTOMER CU ON SQ.CUSTOMER_LINK_ID=CU.CUSTOMER_ID
JOIN DEPARTMENT D ON D.CUSTOMER_ID=CU.CUSTOMER_ID
JOIN DISTRIBUTIONPOINT DP ON DP.DEPARTMENT_ID=D.DEPARTMENT_ID
LEFT OUTER JOIN DELIVERYPOINT DLP ON DP.DELIVERYPOINT_ID=DLP.DELIVERYPOINT_ID
JOIN WEAREREMPLOYMENT_LINK WYL ON WYL.DISTRIBUTIONPOINT_LINK_ID=DP.DISTRIBUTIONPOINT_ID
JOIN COSTCENTER CC ON CC.CUSTOMER_ID = CU.CUSTOMER_ID
JOIN PRODUCT PRD ON PRD.PRODUCT_ID=SQ.PRODUCT_LINK_ID
JOIN SIZEDEFINITION SD ON SD.SIZEDEFINITION_ID=SQ.SIZEDEFINITION_LINK_ID
JOIN ADDRESS ON CU.VISITADDRESS_ID=ADDRESS.ADDRESS_ID
, INVOICEHEADER IH, LANGUAGES
WHERE  COALESCE(IH.SPLITUPCODE, CC.CODE) = CC.CODE
         AND SQ.CUSTOMER_LINK_ID = IH.DELTOCUSTOMER_LINK_ID
         AND QH.STATUSQUOTYPE = 1
         AND QH.YEAR=castvarcharasnumber(to_char(IH.ENDDATE, 'IYYY'))
         AND QH.WEEK=( SELECT --  + INDEX(A, XIE3STATUSQUOHEADER) INDEX(B, XIE3STATUSQUOHEADER)
             MAX(A.WEEK) FROM STATUSQUOHEADER A, SQITEMINCIRCULATION B WHERE
             A.STATUSQUOHEADER_ID=B.STATUSQUOHEADER_ID AND B.CUSTOMER_LINK_ID = SQ.CUSTOMER_LINK_ID
             AND A.STATUSQUOTYPE = 1 AND A.YEAR=castvarcharasnumber(to_char(IH.ENDDATE, 'IYYY')) AND A.STATUSQUODATE <= IH.ENDDATE)
         AND SQ.TOTALCIRCINV > 0
         AND SQ.WEAREREMPLOYMENT_LINK_ID = WYL.WEAREREMPLOYMENT_LINK_ID
         AND SQ.DISTRIBUTIONPOINT_LINK_ID=DP.DISTRIBUTIONPOINT_ID
         AND SQ.DEPARTMENT_LINK_ID=D.DEPARTMENT_ID
AND (CU.SPLITINVOICESPERACTIVITY = 'N'
    OR
    (CU.SPLITINVOICESPERACTIVITY = 'Y' AND EXISTS (SELECT 1 FROM ACTIVITYPERINVOICE API, PRODUCTGROUP PG
    WHERE API.INVOICEHEADER_ID = IH.INVOICEHEADER_ID AND API.ACTIVITY_ID = PG.ACTIVITY_ID AND PRD.PRODUCTGROUP_ID = PG.PRODUCTGROUP_ID)))
    AND WYL.WEAREREMPLOYMENT_ID IS NULL

/
create or replace view V_WEARERINVENTORYMODIF
 (MODIFICATIONCODE, MODIFICATIONDESCRIPTION, CUSTOMERNUMBER, NAME, WEARERNUMBER, SEARCHNAME, PRODUCTCODE, PRODUCTDESCRIPTION, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE, LOCKER, BANK)
as SELECT  C.CODE MODIFICATIONCODE,
( SELECT DESCRIPTION FROM MODIFICATION_DESC X WHERE X.MODIFICATION_ID = A.MODIFICATION_ID AND X.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) MODIFICATIONDESCRIPTION,
K.CUSTOMERNUMBER, K.NAME, W.WEARERNUMBER, W.SEARCHNAME,
 P.CODE PRODUCTCODE,
 (SELECT DESCRIPTION FROM PRODUCT_DESC Y WHERE Y.PRODUCT_ID = B.PRODUCT_ID AND Y.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) PRODUCTDESCRIPTION,
 A.SYSTEMUSER_ID, A.TIMESTAMP, LANGUAGES.CODE LANGUAGECODE
, lo.locker, lo.bank
FROM WEARERINVENTORYMODIFICATION A, WEARERINVENTORY B, PRODUCT P, MODIFICATION C,WEARER W, WEAREREMPLOYMENT WW
  left outer join locker lo on WW.Locker_Id = lo.locker_id
, CUSTOMER K, LANGUAGES
WHERE A.WEARERINVENTORY_ID = B.WEARERINVENTORY_ID
AND A.MODIFICATION_ID = C.MODIFICATION_ID
AND B.PRODUCT_ID = P.PRODUCT_ID
AND B.WEAREREMPLOYMENT_ID = WW.WEAREREMPLOYMENT_ID
AND WW.WEARER_ID = W.WEARER_ID
AND W.CUSTOMER_ID = K.CUSTOMER_ID

/
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, PRODUCTDESCRIPTION, SIZEDEFINITIONCODE, FINISHINGMETHODCODE, SIZEDESCRIPTION, MAXINVENTORY, CHANGESPERWEEK, CIRCINVENTORY, MODIFICATIONSQTY, STARTDATE, ENDDATE
, SEASONDESCRIPTION, EMBLEMTEMPLATEDESC, CUSTOMERLANGUAGECODE, WEARERACTIVE, RENTPRICE, CHANGESPERWEEKBOOL, BILLINGMETHOD, INVENTORYBILLINGTYPE, PRICEDECIMALS, DELIVERYPOINTCODE, DELIVERYPOINTDESC, COG_QTY, LANGUAGECODE, REPORTPARAM_ID, MAXFREEOFCHARGE)
as select cu.customer_id, sizedefinition.sizedefinition_id, finishingmethod.finishingmethod_id,
  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
, (select sdd.description from sizedefinition_desc sdd where sdd.language_id = languages.language_id
and sdd.sizedefinition_id = sizedefinition.sizedefinition_id) sizeDescription
, 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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) wearerActive
, CASE WHEN rp.string_value = 'true' THEN
   pack_price.Rent_Price(cu.customer_id,
                                prd.product_id,
                                sizedefinition.sizedefinition_id,
                                finishingmethod.finishingmethod_id,
                                GETCURRENTDATE(),
                                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 = sizedefinition.sizedefinition_id)
                                             and plp.dateinactive>TRUNC(SYSDATE)
                                           and plp.finishingmethod_id = finishingmethod.finishingmethod_id ) = 'Y'
                                then wearerinventory.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 = coalesce(sizedefinition.sizedefinition_id ,(select s.sizedefinition_id from sizedefinition s where s.code='*'))
                                           and plp.finishingmethod_id = finishingmethod.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 = coalesce(sizedefinition.sizedefinition_id ,(select s.sizedefinition_id from sizedefinition s where s.code='*'))
          and plp.finishingmethod_id = finishingmethod.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 = coalesce(sizedefinition.sizedefinition_id ,(select s.sizedefinition_id from sizedefinition s where s.code='*'))
           and plp.dateinactive>TRUNC(SYSDATE)
          and plp.finishingmethod_id = finishingmethod.finishingmethod_id ) inventorybillingtype
, currency.decimals pricedecimals
, 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) = distributionpoint.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 = wearerinventory.wearerinventory_id ))COG_QTY
, languages.code languageCode
, rp.reportparam_id, wearerinventory.maxfreeofcharge
from
  customer cu
     --left outer join customercluster on cu.cluster_id = customercluster.cluster_id
, weareremployment wey
    left outer join deliverypoint d1 on wey.deliverypoint_id = d1.deliverypoint_id
    left outer join wearerfunction on (wey.wearerfunction_id = wearerfunction.wearerfunction_id)
    left outer join ( locker join deliverypoint d2 on locker.deliverypoint_id = d2.deliverypoint_id )
    on wey.locker_id = locker.locker_id
    left outer join
    ( garmentdispenser join deliverypoint d3 on d3.deliverypoint_id = garmentdispenser.deliverypoint_id )
    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, currency, 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 cu.currency_id = currency.currency_id
and
(wearerinventory.dateinactive > GETCURRENTDATE()
or wearerinventory.circinventory <> 0
or 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_WEARERINVENTORYREPORT_DFD
 (CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMERCITY, WEARERNUMBER, WEARERNAME, ADMINNUMBER, EMPLOYMENT, WEARERFUNCTIONCODE, WEARERFUNCTIONDESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, COSTCENTERCODE, COSTCENTERDESCRIPTION, BANK, LOCKER, GARMENTDISPENSERCODE, PRODUCTCODE, PRODUCTDESCRIPTION, SIZEDEFINITIONCODE, FINISHINGMETHODCODE, MAXINVENTORY, CHANGESPERWEEK, CIRCINVENTORY, MODIFICATIONSQTY, STARTDATE, ENDDATE, SEASONDESCRIPTION, EMBLEMTEMPLATEDESC, CUSTOMERLANGUAGECODE
, WEARERACTIVE, RENTPRICE, PRICEDECIMALS, DELIVERYPOINTCODE, DELIVERYPOINTDESC, COG_QTY, QTYWOOUTSTANDING, LANGUAGECODE, REPORTPARAM_ID, STARTDATE_WEARER, ENDDATE_WEARER)
as select cu.customer_id,
  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
, (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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) wearerActive
, CASE WHEN rp.string_value = 'true' THEN
   pack_price.Rent_Price(cu.customer_id,
                                prd.product_id,
                                sizedefinition.sizedefinition_id,
                                finishingmethod.finishingmethod_id,
                                GETCURRENTDATE(),
                                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 = sizedefinition.sizedefinition_id
                                           and plp.finishingmethod_id = finishingmethod.finishingmethod_id ) = 'Y'
                                then wearerinventory.changesperweek
                                else 0 end)
  ELSE -1 END
  RENTPRICE
, currency.decimals pricedecimals
--, customercluster.code clusterCode
, coalesce(d1.code, d2.code, d3.code) deliverypointCode, coalesce(d1.description, d2.description, d3.description) deliverypointDesc
, (( select count(*) from uniqueitem uq
          where 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') ) -- In Circulation, Assigned
           and uq.product_id = wearerinventory.product_id
           and uq.sizedefinition_id = wearerinventory.sizedefinition_id
           and uq.finishingmethod_id = wearerinventory.finishingmethod_id
           and coalesce(uq.distributionpoint_id, uq.lastdistributionpoint_link_id) = distributionpoint.distributionpoint_id )
  + (select count(*) 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.product_id = wearerinventory.product_id
           and uq.sizedefinition_id = wearerinventory.sizedefinition_id
           and uq.finishingmethod_id = wearerinventory.finishingmethod_id
           and uq.uniqueitem_id = uqnp.uniqueitem_id
               and uqnp.weareremployment_id = wey.weareremployment_id
               and uqnp.wearerinventory_id = wearerinventory.wearerinventory_id )
  ) COG_qty
, (select sum(wol.quantityordered-wol.quantitycancelled-wol.quantityfilled)
     from workorder wo, workorderline wol
    where wo.workorder_id = wol.workorder_id
          and wo.weareremployment_link_id = wey.weareremployment_id
          and wol.product_link_id = prd.product_id
          and wol.sizedefinition_link_id = sizedefinition.sizedefinition_id
          and wol.finishingmethod_id = finishingmethod.finishingmethod_id) qtywooutstanding
, languages.code languageCode
, rp.reportparam_id, we.dateactive startdate_wearer, we.dateinactive enddate_wearer
from
  customer cu
     --left outer join customercluster on cu.cluster_id = customercluster.cluster_id
, weareremployment wey
    left outer join deliverypoint d1 on wey.deliverypoint_id = d1.deliverypoint_id
    left outer join wearerfunction on (wey.wearerfunction_id = wearerfunction.wearerfunction_id)
    left outer join ( locker join deliverypoint d2 on locker.deliverypoint_id = d2.deliverypoint_id )
    on wey.locker_id = locker.locker_id
    left outer join
    ( garmentdispenser join deliverypoint d3 on d3.deliverypoint_id = garmentdispenser.deliverypoint_id )
    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, currency, 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 cu.currency_id = currency.currency_id
and
(wearerinventory.dateinactive > GETCURRENTDATE()
or wearerinventory.circinventory <> 0
or 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_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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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 > GETCURRENTDATE() --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)
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
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_WEARERINVOICERPT_CBD
 (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, MIN_YEAR_WEEKS, SALESAREA)
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
, cast(to_char(to_date('31' || '12' || 2015, 'DDMMYYYY'), 'IW') as numeric) 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, cast(FSGET_MIN_6_YEARWEEKS(ih.invoiceheader_id, ih.invoicefrequency_id) as varchar2(47)) min_year_weeks
, Cu.Salesarea_Id Salesarea
From PackingNote PN, PackingNoteLine PNL, DeliveryScan DS, WearerInvoiceCategory WIC, weareremployment we, wearer wr--, finishingmethod fm
,InvoiceHeader IH left outer join customer cu on Ih.Deltocustomernumber = Cu.Customernumber
,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
, cast(to_char(to_date('31' || '12' || 2015, 'DDMMYYYY'), 'IW') as numeric) 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, cast(FSGET_MIN_6_YEARWEEKS(ih.invoiceheader_id, ih.invoicefrequency_id) as varchar2(47)) min_year_weeks
, Cu.Salesarea_Id Salesarea
From StatusQuoHeader SQH, sqitemincirculation SQIC, WearerInvoiceCategory WIC, weareremployment we, wearer wr,
wearerinventory wi,InvoiceHeader IH left outer join customer cu on ih.deltocustomernumber = cu.customernumber,
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_WEARERLABELS_DFD
 (WEARERNUMBER, WEARERNAME, CUSTOMERNUMBER, CUSTOMERNAME, DISTRIBUTIONPOINTNUMBER, DISTPOINTDESCRIPTION, BANK, LOCKER)
as select w.wearernumber, w.fullname wearername,
       c.customernumber, c.name customername,
       dp.distributionpointnumber, dp.description distpointdescription,
       lo.bank, lo.locker
from wearer w, customer_link c, distributionpoint dp,
     weareremployment wemp left outer join locker lo on wemp.locker_id = lo.locker_id
where w.customer_id = c.customer_link_id
      and wemp.wearer_id = w.wearer_id
      and wemp.distributionpoint_id = dp.distributionpoint_id
      and w.dateactive <= sysdate
      and w.dateinactive > sysdate

/
create or replace view V_WEARERPRODUCTPRESENTATION
 (CUSTOMERID, WEARERNUMBER, WEARERFULLNAME, PRODUCTSHORTDESCRIPTION, BANK, LOCKER, PRODUCTCODE, SIZEDEFINITIONCODE, FINISHINGMETHODCODE, CIRCINVENTORY, CHANGEPERWEEK, DATEACTIVE, RENTALPRICE, DATELASTINCREASE, DATEINACTIVE, SIZE_DESC, LANGUAGE_CODE)
as select
prdlcu.customer_id customerid, we.wearernumber, we.fullname wearerFullname
, prd.shortdescription productShortDescription
, lo.bank, lo.locker, prd.code  productCode, sizedefinition.code sizedefinitionCode
, finishingmethod.code finishingmethodCode
, wei.circinventory, wei.changesperweek ChangePerWeek, wei.dateactive
, (select wearerinvprice.price from wearerinvprice where wearerinvprice.wearerinventory_id = wei.wearerinventory_id
and wearerinvprice.startdate = (select max(wearerinvprice.startdate)
    from wearerinvprice where wearerinvprice.wearerinventory_id = wei.wearerinventory_id
    and wearerinvprice.startdate <GETCURRENTDATETIME())) rentalPrice
, (select max(wearerinvprice.startdate) from wearerinvprice where wearerinvprice.wearerinventory_id = wei.wearerinventory_id
and wearerinvprice.startdate <GETCURRENTDATETIME())DateLastIncrease
, wei.dateinactive
, (select sd.description from sizedefinition_desc sd where sizedefinition.sizedefinition_id = sd.sizedefinition_id and l.language_id=sd.language_id) Size_desc
, l.code Language_code
from
wearer we
, productlistpercustomer prdlcu
, product prd , wearerinventory wei
, weareremployment left outer join  locker lo on weareremployment.locker_id=lo.locker_id
, sizedefinition, finishingmethod
, languages l
where
    prdlcu.product_id = prd.product_id
-- and prdlcu.sizedefinition_id = sizedefinition.sizedefinition_id
-- and prdlcu.finishingmethod_id = finishingmethod.finishingmethod_id
-- and prdlcu.dateactive < GETCURRENTDATETIME()
and prdlcu.customer_id = we.customer_id
and we.wearer_id = weareremployment.wearer_id
and weareremployment.weareremployment_id = wei.weareremployment_id
and wei.product_id = prd.product_id
and wei.sizedefinition_id = sizedefinition.sizedefinition_id
and wei.finishingmethod_id = finishingmethod.finishingmethod_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(GETCURRENTDATE(), WEARER.dateactive)*GETDATEDIFF(WEARER.dateinactive, GETCURRENTDATE()) 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(GETCURRENTDATE(), WEARER.dateactive)*GETDATEDIFF(WEARER.dateinactive, GETCURRENTDATE()) 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(GETCURRENTDATE(), WEARER.dateactive)*GETDATEDIFF(WEARER.dateinactive, GETCURRENTDATE()) 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_WEBACTIVITIESPERCUSTNEW_BCM
 (WEBUSER_ID, WEBSESSION_ID, CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, DELIVERYDATE, SOILWEIGHT, CLEANWEIGHT, CONTAINERINSCAN, CONTAINEROUTSCAN, LANGUAGECODE)
as select wc.webuser_id, wus.websession_id
, cul.customer_link_id customer_id, cul.customernumber, cul.name customername, wh.weighingdate DeliveryDate
, wh.soilweight
, wh.cleanweight
, 0 ContainerInscan
, 0 ContainerOutscan
, languages.code languagecode
from weighinghistory wh, customer_link cul,
  webusercustomer wc, webusersession wus, languages
where wh.customer_link_id = cul.customer_link_id
      and wc.customer_id = cul.customer_link_id
      and wus.customer_id = cul.customer_link_id
union all
select wc.webuser_id, wus.websession_id
, cul.customer_link_id customer_id, cul.customernumber, cul.name customername, trunc(cs.scantimestamp) DeliveryDate
, 0 SoilWeight
, 0 CleanWeight
, case when cs.transactiontype_id in (510, 511, 512, 513)
  then 1 else 0 end ContainerInscan
, case when cs.transactiontype_id in (540, 541, 542, 543, 544, 545)
  then 1 else 0 end ContainerOutscan
, languages.code languagecode
from containerscan cs, distributionpoint_link dpl, department_link del, customer_link cul,
  webusercustomer wc, webusersession wus, languages
where cs.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 cs.transactiontype_id in (510, 511, 512, 513, 540, 541, 542, 543, 544, 545) --inscan and outscan
      and wc.customer_id = cul.customer_link_id
      and wus.customer_id = cul.customer_link_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_WEBCLIENTDELIVERYNOTELABELS
 (CLIENTDELIVERYNOTE_ID, PRICE, QUANTITY)
as select p.clientdeliverynote_id, p.price, p.quantity
from printqueueresidentialitem p
where p.chargeable = 'Y'

/
create or replace view V_WEBCLIENTDELIVERYNOTESCHARGE
 (CLIENTDELIVERINOTE_ID, LANGUAGECODE, CODE, DESCRIPTION, QUANTITY, PRICE, PRICEONDELNOTE)
as select 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
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, GETDATEONLY(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 GETDATEONLY(cds.outscantimestamp) = GETDATEONLY(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, DEPARTMENT_ID, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, CC_CODE, CC_DESCR, COSTCENTER_ID, DISTRIBUTIONPOINT_ID, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, DELIVERYPOINT_ID, DELIVERYPOINTCODE, DELIVERYPOINTDESC, PRODUCTGROUP_ID, PRODUCTGROUPCODE, PRODUCTGROUPDESCRIPTION, PRODUCT_ID, PRODUCTCODE, PRODUCTDESCRIPTION, PARENTPRODUCTCODE, PARENTPRODUCTDESCRIPTION, PACKINDICATION
, PACKCODE, PACKDESCRIPTION, ACTIVITYCODE, ACTIVITY_ID, THEORETICALWEIGHT, TYPEOFMERCHANDISE, MODEL, PRODSIZE_THEORETICALWEIGHT, SIZECODE, SIZEDESCRIPTION, FINISHINGMETHODCODE, FINISHINGMETHODDESCRIPTION, DELIVERYDATE, YEARWEEK, WEEK, YEAR, REALMONTH, REALYEAR, DAYNUMBER, AMOUNTORDERED, AMOUNTDELIVERED, AMOUNTSHORTAGE, INTERNALPRICE, DISCOUNT, PARENTPACKPRODUCT_LINK_ID, PARENTPRODUCT_LINK_ID, TAXABLE, SYSTEMUSER_ID, TIMESTAMP, CUSTOMERLANGUAGECODE, LANGUAGECODE
, PRICEWITHDISCOUNT, DISCOUNTPERCENTAGE, Q, W, E, R, T, Y, U)
as SELECT RP.REPORTPARAM_ID,wus.websession_id, wc.webuser_id,
       CUSTOMER_LINK.CUSTOMERNUMBER, CUSTOMER_LINK.NAME customername, CUSTOMER_LINK.CUSTOMER_LINK_ID,
       DEPARTMENT_LINK.DEPARTMENT_LINK_ID Department_Id,
       DEPARTMENT_LINK.DEPARTMENTNUMBER, DEPARTMENT_LINK.DESCRIPTION departmentdescription,
       CC.CODE CC_CODE, CC.DESCRIPTION CC_DESCR, CC.COSTCENTER_ID,
       DISTRIBUTIONPOINT_LINK.DISTRIBUTIONPOINT_LINK_ID Distributionpoint_Id,
       DISTRIBUTIONPOINT_LINK.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT_LINK.DESCRIPTION distributionpointdescription,
       DELIVERYPOINT_LINK.DELIVERYPOINT_ID, DELIVERYPOINT_LINK.Code deliverypointcode,
       DELIVERYPOINT_LINK.Description deliverypointdesc,
       PRODUCTGROUP.PRODUCTGROUP_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.Product_Link_Id product_id, 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,
       parentproduct.CODE parentproductcode,
       (SELECT E.DESCRIPTION FROM PRODUCT_LINK_DESC E WHERE E.PRODUCT_LINK_ID = DELIVERYHISTORY.PARENTPRODUCT_LINK_ID AND E.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) parentproductdescription,
       DELIVERYHISTORY.PACKINDICATION,
       pack.CODE packcode,
       (SELECT F.DESCRIPTION FROM PRODUCT_LINK_DESC F WHERE F.PRODUCT_LINK_ID = DELIVERYHISTORY.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,
       PRODUCTGROUP.ACTIVITY_ID,
       PRODUCT.THEORETICALWEIGHT, PRODUCT.typeofmerchandise, PRODUCT.MODEL,
       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,
       FINISHINGMETHOD.CODE finishingmethodcode,
       (SELECT D.DESCRIPTION FROM FINISHINGMETHOD_DESC D WHERE D.FINISHINGMETHOD_ID = DELIVERYHISTORY.FINISHINGMETHOD_ID AND D.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) FINISHINGMETHODdescription,
       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.PARENTPACKPRODUCT_LINK_ID, DELIVERYHISTORY.PARENTPRODUCT_LINK_ID,
       cu.taxable,
       DELIVERYHISTORY.SYSTEMUSER_ID, DELIVERYHISTORY.TIMESTAMP,
       CUSTOMER_LINK.LANGUAGECODE CUSTOMERLANGUAGECODE, LANGUAGES.CODE LANGUAGECODE,
       F_GETDELPRODPRICEWITHDISC(cu.customer_id, product.product_id, SIZEDEFINITION_LINK.SIZEDEFINITION_ID,
         FINISHINGMETHOD.FINISHINGMETHOD_ID, deliveryhistory.deliverydate, product.typeofmerchandise) PRICEWITHDISCOUNT,
       pack_price.Wash_Discount(cu.customer_id, product.product_id, SIZEDEFINITION_LINK.SIZEDEFINITION_ID,
         FINISHINGMETHOD.FINISHINGMETHOD_ID,deliveryhistory.deliverydate) DISCOUNTPERCENTAGE
         , rp.number_value q , cu.customer_id  w, product.product_id e, SIZEDEFINITION_LINK.SIZEDEFINITION_ID r,
         FINISHINGMETHOD.FINISHINGMETHOD_ID t, deliveryhistory.deliverydate y ,product.typeofmerchandise u
 FROM DELIVERYHISTORY,
      PRODUCTSIZE,
      CUSTOMER_LINK
        left outer join customer cu          --left join country ctr on cu.country_id = ctr.country_id)
        on cu.customer_id = CUSTOMER_LINK.CUSTOMER_ID,
      DEPARTMENT_LINK,
      DISTRIBUTIONPOINT_LINK
        left outer join distributionpoint dp on DISTRIBUTIONPOINT_LINK.DISTRIBUTIONPOINT_ID = DP.DISTRIBUTIONPOINT_ID
      , DELIVERYPOINT_LINK,
      COSTCENTER CC,
      SIZEDEFINITION_LINK
        LEFT OUTER JOIN SIZEDEFINITION ON (SIZEDEFINITION_LINK.SIZEDEFINITION_ID = SIZEDEFINITION.SIZEDEFINITION_ID),
      FINISHINGMETHOD, LANGUAGES,
      PRODUCT_LINK parentproduct, PRODUCT_LINK pack,
      PRODUCT_LINK LEFT OUTER JOIN PRODUCT INNER JOIN PRODUCTGROUP ON (PRODUCT.Productgroup_Id = PRODUCTGROUP.PRODUCTGROUP_ID)
             ON (PRODUCT_LINK.PRODUCT_ID = PRODUCT.PRODUCT_ID),
      REPORTPARAM RP--, currency cur, Businessunit BU, plant pl
      , webusersession wus, webuser wu, webusercustomer wc
 WHERE 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_LINK.CUSTOMER_LINK_ID
  AND COALESCE(DP.COSTCENTER_ID,(select d.costcenter_id from department d where d.department_id = DEPARTMENT_LINK.DEPARTMENT_LINK_ID))=CC.COSTCENTER_ID
  AND DELIVERYPOINT_LINK.DELIVERYPOINT_LINK_ID = DP.Deliverypoint_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 FINISHINGMETHOD.FINISHINGMETHOD_ID = DELIVERYHISTORY.FINISHINGMETHOD_ID
  AND PRODUCT.PRODUCT_ID = PRODUCTSIZE.PRODUCT_ID
  AND SIZEDEFINITION.SIZEDEFINITION_ID = PRODUCTSIZE.SIZEDEFINITION_ID
  AND wc.customer_id = CUSTOMER_LINK.CUSTOMER_LINK_ID
  AND wc.webuser_id = wu.webuser_id
  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 = CUSTOMER_LINK.CUSTOMER_LINK_ID)
       OR
       EXISTS (SELECT 1 FROM WEBUSERDEPARTMENT WDEP, WEBUSERCUSTOMER WCUST
               WHERE WDEP.DEPARTMENT_ID = DEPARTMENT_LINK.DEPARTMENT_LINK_ID
                     AND WCUST.WEBUSER_ID = WU.WEBUSER_ID
                     AND WCUST.CUSTOMER_ID = DEPARTMENT_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, --pnl.price, pnl.deliveredcogqty, cy.code CurrencyCode, cy.description CurrencyDesc,
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, 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 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)
       )
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, FINMETHOD, INVOICEAMOUNTDECIMALS, RESIDUALVALUE, FLAGCODE, STAY, STAYNR, STATUS, ADMINNUMBER, COSTCENTERCODE, COSTCENTERDESC, DEPARTMENTNUMBER, DEPARTMENTDESC, CUSTOMER_ID, 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, wus.websession_id, wc.webuser_id,DE.DEPARTMENT_ID--WD.DEPARTMENT_ID WEBUSERDEPARTMENT_ID,
, cast(RIGHTPAD(F_GETPRODUCTCODE(prd.code, cu.customer_id, h.product_id, h.sizedefinition_id, h.finishingmethod_id),12,' ') 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
GETDATEONLY(uf.startdate)<=GETCURRENTDATE()--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
, GETDATEONLY(h.lastscandate) lastscandate, GETDATEONLY(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.customer_id
, cu.customernumber, cu.name customername, cu.defaultbusinessunit_id, address.city
, we.wearernumber, we.fullname wearername, we.searchname wearersearchname
, GETDATEDIFF(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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),
  webusersession wus, 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 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 = DE.DEPARTMENT_ID
                                   AND WCUST.WEBUSER_ID = WU.WEBUSER_ID
                                   AND WCUST.CUSTOMER_ID = DE.CUSTOMER_ID
                                   AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_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, wus.websession_id, wc.webuser_id,DE.DEPARTMENT_ID--WD.DEPARTMENT_ID WEBUSERDEPARTMENT_ID,
, cast(RIGHTPAD(F_GETPRODUCTCODE(prd0.code, we.customer_id, g0.product_id, g0.sizedefinition_id, g0.finishingmethod_id),12,' ') 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.customer_id
, cu.customernumber, cu.name customername, cu.defaultbusinessunit_id, address.city
, we.wearernumber, we.fullname wearername, we.searchname wearersearchname
, GETDATEDIFF(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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
  webusersession wus, 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 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 = DE.DEPARTMENT_ID
                                   AND WCUST.WEBUSER_ID = WU.WEBUSER_ID
                                   AND WCUST.CUSTOMER_ID = DE.CUSTOMER_ID
                                   AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_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_WEBGARMENTSPERWEARER_FLAG
 (UNIQUEITEM_ID, CODE, FLAG_DESC, LANGUAGE_ID)
as select 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, flag fg, languages l
WHERE uf.flag_id=fg.flag_id
  and fg.useinwebapplication='Y'
  and GETDATEONLY(uf.startdate)<=GETCURRENTDATE()
-- WebGarmentsPerWearer.rpt
-- WebGarmentsPerWearer.RSV.rpt

/
create or replace view V_WEBGARMENTSPERWEARER_RSV
 (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
, FLAG, 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)
as select wu.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(RIGHTPAD(F_GETPRODUCTCODE(prd.code, cu.customer_id, h.product_id, h.sizedefinition_id, h.finishingmethod_id),12,' ') 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)
GETDATEONLY(uf.startdate)<=GETCURRENTDATE()--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
, GETDATEONLY(h.lastscandate) lastscandate, GETDATEONLY(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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) weareractive
, we.dateactive WearerDateActive, we.dateinactive WearerDateInactive
, languages.code languagecode, languages.language_id, cu.language_id customerlanguage_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 g.freeextragarment <> 'Y' --specific RSV (501519)
  and wc.webuser_id = wu.webuser_id
Union all
select wu.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(RIGHTPAD(F_GETPRODUCTCODE(prd0.code, we.customer_id, g0.product_id, g0.sizedefinition_id, g0.finishingmethod_id),12,' ') 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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) weareractive
, we.dateactive WearerDateActive, we.dateinactive WearerDateInactive
, languages.code languagecode, languages.language_id, cu.language_id customerlanguage_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.RSV.rpt

/
create or replace view V_WEBGARMENTSPERWEARER_SMG
 (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, FINMETHOD, INVOICEAMOUNTDECIMALS, RESIDUALVALUE, FLAGCODE, STAY, STAYNR, STATUS, ADMINNUMBER, COSTCENTERCODE, COSTCENTERDESC, DEPARTMENTNUMBER, DEPARTMENTDESC, CUSTOMER_ID, 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, DELIVPOINT_CODE, DELIVPOINT_DESC, DISTRIBUTIONPOINTNO, DISTRIBUTIONPOINTDESCRIPTION)
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, wus.websession_id, wc.webuser_id,DE.DEPARTMENT_ID--WD.DEPARTMENT_ID WEBUSERDEPARTMENT_ID,
, cast(RIGHTPAD(F_GETPRODUCTCODE(prd.code, cu.customer_id, h.product_id, h.sizedefinition_id, h.finishingmethod_id),12,' ') 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
GETDATEONLY(uf.startdate)<=GETCURRENTDATE()--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
, GETDATEONLY(h.lastscandate) lastscandate, GETDATEONLY(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.customer_id
, cu.customernumber, cu.name customername, cu.defaultbusinessunit_id, address.city
, we.wearernumber, we.fullname wearername, we.searchname wearersearchname
, GETDATEDIFF(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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
, dpo.code delivpoint_code, dpo.description delivpoint_desc, dip.distributionpointnumber distributionpointno, dip.description distributionpointdescription
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, deliverypoint dpo,
  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),
  webusersession wus, 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 dpo.customer_id=cu.customer_id
  and coalesce(lk.deliverypoint_id,gd.deliverypoint_id,wey.deliverypoint_id)=dpo.deliverypoint_id
  and wc.customer_id = CU.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 = 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 = DE.CUSTOMER_ID
                                   AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_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, wus.websession_id, wc.webuser_id,DE.DEPARTMENT_ID--WD.DEPARTMENT_ID WEBUSERDEPARTMENT_ID,
, cast(RIGHTPAD(F_GETPRODUCTCODE(prd0.code, we.customer_id, g0.product_id, g0.sizedefinition_id, g0.finishingmethod_id),12,' ') 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.customer_id
, cu.customernumber, cu.name customername, cu.defaultbusinessunit_id, address.city
, we.wearernumber, we.fullname wearername, we.searchname wearersearchname
, GETDATEDIFF(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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
, dpo.code delivpoint_code, dpo.description delivpoint_desc, dip.distributionpointnumber distributionpointno, dip.description distributionpointdescription
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, deliverypoint dpo,
  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
  webusersession wus, 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 dpo.customer_id=cu.customer_id
  and coalesce(lk0.deliverypoint_id,gd0.deliverypoint_id,wey0.deliverypoint_id)=dpo.deliverypoint_id
  and wc.customer_id = CU.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 = 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 = DE.CUSTOMER_ID
                                   AND WDEP.WEBUSERCUSTOMER_ID = WCUST.WEBUSERCUSTOMER_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_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
GETDATEONLY(uf.startdate)<=GETCURRENTDATE()--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
, GETDATEONLY(h.lastscandate) lastscandate, GETDATEONLY(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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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_WEBLINENASSQTYPERWEEK_SMG
 (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, --standard */
       (select coalesce(sum(amount),0) amount from normstockamount nsa
        where nsa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id
        and nsa.day_id in (
	           select max(sdd.day_id)  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 <= getdaynumber(current_date)
             group by sdd.stockcountschedule_id
               union
             select max(sdd.day_id) 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 <= getdaynumber(current_date)
             group by sdd.stockcountschedule_id)) nsa_amount, --ABS-56228
       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_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
wc.webuser_id, cu.customer_id, dsp.distributionpoint_id,
       WD.DEPARTMENT_ID WEBUSERDEPARTMENT_ID,CUM.YEAR ,CUM.MONTH,--CUM.YEAR * 100 + CUM.MONTH yearmonth, rp.date_value1,
       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 deliveryhistory dh join customer cu on dh.customer_link_id=cu.customer_id
join currency cur on cur.currency_id=cu.currency_id
join department dpl on ( dh.department_link_id=dpl.department_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 distributionpoint dsp on (dsp.department_id=dpl.department_id )
join costcenter cc on (dsp.costcenter_id=cc.costcenter_id and dpl.costcenter_id=cc.costcenter_id )
join customermonth cum on (cum.customer_id=cu.customer_id)
cross join reportparam rp --on rp.number_value=cc.costcenter_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 dh.distributionpoint_link_id=dsp.distributionpoint_id
and dh.deliverydate>= cum.startdate
and dh.deliverydate<= cum.enddate
   and cc.costcenter_id = rp.number_value
   and dh.customer_link_id=wus.customer_id
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_WEBMONTHLYUSAGENEWANG
 (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, 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,
  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,
  (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, 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, 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,
  wus.websession_id, 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
/
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, PERIOD, PATIENTDAYS, PATIENTS, WEBUSER_ID, LANGUAGECODE)
as select 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,
        (case when pd.week = 53 then 13
        else (pd.week-1)/4+1
          END) period, pd.patientdays, pd.patients, wcust.webuser_id, languages.code languagecode
from patientday pd, costcenter cc, distributionpoint dp, department d, customer c, webusercustomer wcust, languages
where pd.distributionpoint_link_id = dp.distributionpoint_id
      and dp.department_id = d.department_id
      and d.costcenter_id = cc.costcenter_id
      and d.customer_id = c.customer_id
      and wcust.customer_id = c.customer_id
      and 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,
        (case when pd.week = 53 then 13
        else (pd.week-1)/4+1
          END) period,
        pd.patientdays, pd.patients, wcust.webuser_id, languages.code languagecode
from patientday pd, customer c, webusercustomer wcust, languages
where pd.customer_link_id = c.customer_id
      and wcust.customer_id = c.customer_id
      and pd.distributionpoint_link_id is null

/
create or replace view V_WEBPERFORMANCENEW_BCM
 (WEBUSER_ID, WEBSESSION_ID, CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENT_ID, DEPARTMENTNUMBER, DEPARTMENTDESC, DELIVERYPOINT_ID, DELIVERYPOINTCODE, DELIVERYPOINTDESC, DELIVERYDATE, ACTIVITY_ID, ACTIVITY_CODE, PRODUCTGROUP_ID, PRODUCTGROUP_CODE, PRODUCT_ID, PRODUCT_CODE, PRODUCT_DESC, PRODUCTGROUP_DESC, ACTIVITY_DESC, STANDARDAMOUNT, VARIATIONAMOUNT, DELIVEREDAMOUNT, RQA_QUANTITY, WASH_PRICE, LANGUAGECODE, LANGUAGE_ID, REPORTPARAM_ID)
as select wc.webuser_id, wus.websession_id
, cu.customer_id, cu.customernumber, cu.name customername
, de.department_id, de.departmentnumber, de.description departmentdesc
, delp.deliverypoint_id, delp.code deliverypointcode, delp.description deliverypointdesc
, pn.deliverydate, ac.activity_id, ac.code activity_code
, pg.productgroup_id, pg.code productgroup_code, pr.product_id, pr.code product_code
, (select prd.description from product_desc prd where prd.product_id = pr.product_id and prd.language_id = languages.language_id) product_desc
, (select pgd.description from productgroup_desc pgd where pgd.productgroup_id = pg.productgroup_id and pgd.language_id = languages.language_id) productgroup_desc
, (select acd.description from activity_desc acd where acd.activity_id = pg.activity_id and acd.language_id = languages.language_id) activity_desc
, pnl.standardamount, pnl.variationamount, pnl.deliveredamount--, rqa.adjustmentdate
, coalesce((select sum(rqa.quantity) from rentalqtyadjustment RQA, productlistperdistribpoint plpd
  where rqa.productlistperdistribpoint_id = plpd.productlistperdistribpoint_id and plpd.distributionpoint_id = dp.distributionpoint_id
      and plpd.product_id = pr.product_id and plpd.sizedefinition_id = pnl.sizedefinition_id and plpd.finishingmethod_id = pnl.finishingmethod_id), 0) rqa_quantity
, Pack_Price.Wash_Price(cu.customer_id, pr.product_id, pnl.sizedefinition_id, pnl.finishingmethod_id, rp.date_value2) Wash_Price
, languages.code languagecode, languages.language_id, rp.reportparam_id
from PackingNote PN, status st, PackingNoteLine PNL, deliverypoint delp,
     distributionpoint dp, department de, customer cu,
     product pr, productgroup pg, activity ac,
     webusercustomer wc, webusersession wus, languages, reportparam rp
where PN.PackingNote_ID = PNL.PackingNote_ID And PN.Status_ID = st.status_id and st.Code = '30' and st.statustype = 'PN'
      and pn.deliverypoint_id = delp.deliverypoint_id
      and pn.distributionpoint_id = dp.distributionpoint_id and dp.department_id = de.department_id and de.customer_id = cu.customer_id
      and pnl.product_id = pr.product_id and pr.productgroup_id = pg.productgroup_id and pg.activity_id = ac.activity_id
      and pn.deliverydate >= rp.date_value1 and pn.deliverydate <= rp.date_value2
      and wc.customer_id = cu.customer_id
      and wus.customer_id = cu.customer_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, GETCURRENTDATE() 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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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, GETCURRENTDATE() 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,
  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 = 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,
  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 = languages.language_id
    and fd.flag_id = urif.flag_id) flagdesc,
  uri.lastinscandate, uri.lastoutscandate, uri.remark, urip.assigndate,
  languages.code languagecode,
  wd.department_id webuserdepartment_id,
  wus.websession_id websession_id,
  wc.webuser_id webuser_id
from client 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,
  uniqueresidentialitemproduct urip,
  uniqueresidentialitem uri
  left outer join uniqueresidentialitemflag urif
       on uri.uniqueresidentialitem_id = urif.uniqueresidentialitem_id,
  product pr, sizedefinition sz, finishingmethod fm,
  status st, stay sy,
  languages,
  webusercustomer wc
    left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  webusersession wus
where cl.client_id = uri.client_id
  and uri.uniqueresidentialitem_id = urip.uniqueresidentialitem_id
  and urip.product_id = pr.product_id
  and urip.sizedefinition_id = sz.sizedefinition_id
  and urip.finishingmethod_id = fm.finishingmethod_id
  and uri.status_id = st.status_id
  and uri.stay_id = sy.stay_id
  and wc.customer_id = cl.customer_id
  and wus.customer_id = wc.customer_id
union all
select cl.customer_id, st.code statuscode,
  sy.stay_id,
  uri.statuschangedate, uri.laststaydate, GETCURRENTDATE() 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 = 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,
  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 = languages.language_id
    and fd.flag_id = urif.flag_id) flagdesc,
  uri.lastinscandate, uri.lastoutscandate, uri.remark, null assigndate,
  languages.code languagecode,
  wd.department_id webuserdepartment_id,
  wus.websession_id websession_id,
  wc.webuser_id webuser_id
from client 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,
  uniqueresidentialitem uri
  left outer join uniqueresidentialitemflag urif
       on uri.uniqueresidentialitem_id = urif.uniqueresidentialitem_id,
  status st, stay sy,
  languages,
  webusercustomer wc
    left outer join webuserdepartment wd on (wc.webusercustomer_id = wd.webusercustomer_id),
  webusersession wus
where cl.client_id = uri.client_id
  and uri.status_id = st.status_id
  and uri.stay_id = sy.stay_id
  and not exists (select * from uniqueresidentialitemproduct urip2
    where urip2.uniqueresidentialitem_id = uri.uniqueresidentialitem_id)
  and wc.customer_id = cl.customer_id
  and wus.customer_id = wc.customer_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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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(GETCURRENTDATE(), we.dateactive)*GETDATEDIFF(we.dateinactive, GETCURRENTDATE()) 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(GETCURRENTDATE(), WEARER.dateactive)*GETDATEDIFF(WEARER.dateinactive, GETCURRENTDATE()) 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(GETCURRENTDATE(), WEARER.dateactive)*GETDATEDIFF(WEARER.dateinactive, GETCURRENTDATE()) 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_WEBWORKORDERLINE_CBD
 (WORKORDER_ID, PRODNR, PRODDESCRIPTION, FINMETHCODE, SIZECODE, UNIQUEYN, QUALITYGRADE, REASONCODE_ID, REASONCODE, QORDER, QDONE, QOPEN, MODIFICATIONCODE, INSTRUCTIONS, LANGUAGECODE, CONFIRMEDDATE)
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
, poh.confirmeddate
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
     left outer join (purchaseorderline pol left outer join PURCHASEORDERHEADER poh on pol.purchaseorderheader_id = poh.purchaseorderheader_id)
     on pol.purchaseorderline_id = wokli.PURCHASEORDERLINE_ID
, languages
where wo.workorder_id = wokli.workorder_id

/
create or replace view V_WEBWORKORDERLINE_SMG
 (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_WEBWORKORDER_SMG
 (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, CONSPOINTNO, WEARERFUNCTION, WEARERREMARK, ROUTENUMBER, ROUTEDESCRIPTION, NOTLAUNDRYOWNED, STATUSCODE, STATUSDESC
, REASONCODE, SHOWGARMENTGRADE, PRODUCTDESCRIPTIONONLY, DELIVERYPOINT_ID, REASONCODE_ID, COSTCENTER_ID, WEARER_ID, CUSTOMERNAME, COSTCENTERCODE)
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, distributionpoint.distributionpointnumber ConsPointNo, wearerfunction.description wearerfunction
, w.remark WearerRemark, route.routenumber, route.description RouteDescription
, wok.customerowned NotLaundryOwned, status.code StatusCode, status.factorydescription Statusdesc
, rc.code ReasonCode, wu.showgarmentgrade, wu.productdescriptiononly
, we.deliverypoint_id
, rc.reasoncode_id
, distributionpoint.costcenter_id
, we.wearer_id,cu.name customername, cc.code costcentercode
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, costcenter cc,
  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 distributionpoint.costcenter_id=cc.costcenter_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_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 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') 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
--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

/
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_WEIGHINGDETAILS_LTS
 (INVOICEHEADER_ID, INVOICENUMBER, INVOICEDATE, INVOICEYEAR, INVOICEWEEK, DELTOCUSTOMERNUMBER, DELTOCUSTOMERNAME, BILLTOCUSTOMERNUMBER, BILLTOCUSTOMERNAME, WEIGHINGDATE, WEIGHINGYEAR, WEIGHINGWEEK, TICKETNUMBER, WEIGHINGCATEGORY_CODE, WEIGHINGCATEGORY_DESC, DAYDESCRIPTION, DAYNUMBER, TAREWEIGHT, GROSSWEIGHT, WEIGHTDECIMALS, NETWEIGHT, LANGUAGESCODE, DELTOLANGUAGESCODE, STREET, STREET2, ZIPCODE, CITY, STATE, EXTRANAME1, EXTRANAME2, DELTOSTREET, DELTOSTREET2, DELTOZIPCODE, DELTOCITY
, DELTOSTATE, BILLTOCOUNTRYDESCRIPTION, INVOICELAYOUTCODE, ACTIVITYCODE, ACTIVITYDESC, NEXTPERIODSTARTDATE, NEXTPERIODENDDATE, NEXTPERIODNOWEEKS, STARTWEEK, ENDWEEK, NEXTPERIODSTARTWEEK, NEXTPERIODENDWEEK, BU_DESC, PLANTNAME, PLANT_STREET, PLANT_ZIP, PLANT_CITY, PLANT_PHONE, PLANT_FAX, PLANT_EMAIL, PLANT_WEB, INVOICEFREQUENCYNUMBER, STARTMONTH, ENDMONTH)
as select ih.invoiceheader_id, ih.invoicenumber, ih.invoicedate, ih.invoiceyear, ih.invoiceweek,
       ih.deltocustomernumber, ih.deltocustomername, ih.billtocustomernumber, ih.billtocustomername,
       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
, (select clan.code from languages clan, customer del where ih.deltocustomer_link_id = del.customer_id and clan.language_id = del.language_id) DelToLanguagesCode
, ih.street, ih.street2, ih.zipcode, ih.city, ih.state, ih.extraname1, ih.extraname2
, ih.deltostreet, ih.deltostreet2, ih.deltozipcode, ih.deltocity, ih.deltostate
, ihextr.billtocountrydescription billtocountrydescription
, ihextr.formlayoutcode invoicelayoutcode
, ac.code ActivityCode
, (select acd.description from activity_desc acd where ac.activity_id = acd.activity_id and acd.language_id = lan.language_id) ActivityDesc
, ih.nextperiodstartdate, ih.nextperiodenddate, ih.nextperiodnoweeks
, ih.startweek, ih.endweek, ih.nextperiodstartweek, ih.nextperiodendweek
, bu.description bu_desc
, p.name plantname
, ad.street plant_street
, ad.zipcode plant_zip, ad.city plant_city
, p.phoneno plant_phone, p.faxno plant_fax
, p.email plant_email, p.website plant_web
, ih.invoicefrequency_id invoicefrequencynumber
, ih.startmonth, ih.endmonth
from invoiceheader ih, invoiceheaderextrainfo ihextr, weighingticket wt, weighingticketline wtl, weighingcategory wc,
     activity ac, languages lan, plant p, businessunit bu, address ad
where ih.invoiceheader_id = wtl.invoiceheader_id
      and wt.weighingticket_id = wtl.weighingticket_id
      and wtl.weighingcategory_id = wc.weighingcategory_id
      and wc.activity_id = ac.activity_id
      and ih.invoiceheader_id = ihextr.invoiceheader_id
      and ih.invoicebusinessunit_id = bu.businessunit_id
      and p.code = '07'
      and p.address_id = ad.address_id

/
create or replace view V_WEIGHINGHISTORY
 (PROCESSBUSINESSUNIT_ID, CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, WEIGHINGCATEGORYCODE, WEIGHINGCATEGORYDESCRIPTION, WEIGHINGDATE, YEAR, WEEK, DAYNUMBER, YEARWEEK, REALMONTH, REALYEAR, SOILWEIGHT, CLEANWEIGHT, PROCESSBUSINESSUNITNR, PROCESSBUSINESSUNITNAME, INVOICEBUSINESSUNITNR, INVOICEBUSINESSUNITNAME, SYSTEMUSER_ID, TIMESTAMP, CUSTOMERLANGUAGECODE, LANGUAGECODE, WEIGHTDECIMALSMANUALINPUT
, WEIGHINGUSE, WEIGHTUNIT)
as SELECT WEIGHINGHISTORY.PROCESSBUSINESSUNIT_ID, CUSTOMER_LINK.CUSTOMER_ID,
  CUSTOMER_LINK.CUSTOMERNUMBER, CUSTOMER_LINK.NAME customername,
  DEPARTMENT_LINK.DEPARTMENTNUMBER departmentnumber, DEPARTMENT_LINK.DESCRIPTION departmentdescription,
  DISTRIBUTIONPOINT_LINK.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT_LINK.DESCRIPTION distributionpointdescription,
  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
  ) weighingcategorydescription,
   WEIGHINGHISTORY.WEIGHINGDATE, WEIGHINGHISTORY.YEAR, WEIGHINGHISTORY.WEEK, WEIGHINGHISTORY.DAYNUMBER,
  WEIGHINGHISTORY.year*100 + WEIGHINGHISTORY.week YEARWEEK,
  month(WEIGHINGHISTORY.WEIGHINGDATE) realmonth,
  year(WEIGHINGHISTORY.WEIGHINGDATE) realyear,
  WEIGHINGHISTORY.SOILWEIGHT, WEIGHINGHISTORY.CLEANWEIGHT,
  PROCESSBUSINESSUNIT.CODE processbusinessunitnr, PROCESSBUSINESSUNIT.DESCRIPTION processbusinessunitname,
  INVOICEBUSINESSUNIT.CODE invoicebusinessunitnr, INVOICEBUSINESSUNIT.DESCRIPTION invoicebusinessunitname,
  WEIGHINGHISTORY.SYSTEMUSER_ID, WEIGHINGHISTORY.TIMESTAMP, CUSTOMER_LINK.LANGUAGECODE CUSTOMERLANGUAGECODE, 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,
     CUSTOMER_LINK, DEPARTMENT_LINK, DISTRIBUTIONPOINT_LINK,
  BUSINESSUNIT PROCESSBUSINESSUNIT, BUSINESSUNIT INVOICEBUSINESSUNIT, LANGUAGES
  , SYSTEMSETTING SS
WHERE WEIGHINGHISTORY.CUSTOMER_LINK_ID = CUSTOMER_LINK.CUSTOMER_LINK_ID
AND WEIGHINGHISTORY.DEPARTMENT_LINK_ID = DEPARTMENT_LINK.DEPARTMENT_LINK_ID
AND WEIGHINGHISTORY.DISTRIBUTIONPOINT_LINK_ID = DISTRIBUTIONPOINT_LINK.DISTRIBUTIONPOINT_LINK_ID
AND WEIGHINGHISTORY.WEIGHINGCATEGORY_LINK_ID = WEIGHINGCATEGORY_LINK.WEIGHINGCATEGORY_LINK_ID
AND WEIGHINGHISTORY.PROCESSBUSINESSUNIT_ID = PROCESSBUSINESSUNIT.BUSINESSUNIT_ID
AND WEIGHINGHISTORY.INVOICEBUSINESSUNIT_ID = INVOICEBUSINESSUNIT.BUSINESSUNIT_ID
AND PROCESSBUSINESSUNIT.PLANT_ID = SS.PLANT_ID
AND 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, WEIGHINGCATEGORYDESCRIPTION, AMOUNT, PRICE, RNDAMOUNTPRICE, VATRATE, DECIMALS, INVOICEAMOUNTDECIMALS, PROCESSBUSINESSUNITNR, PROCESSBUSINESSUNITNAME, INVOICEBUSINESSUNITNR, INVOICEBUSINESSUNITNAME, CUSTOMERLANGUAGECODE, LANGUAGECODE, WEIGHTDECIMALSMANUALINPUT)
as SELECT rp.reportparam_id, CUSTOMER_LINK.CUSTOMER_ID,
  CUSTOMER_LINK.CUSTOMERNUMBER, CUSTOMER_LINK.NAME customername,
  (select DEPARTMENTNUMBER from department dl where dl.department_id = WEIGHINGHISTORY.DEPARTMENT_LINK_ID) departmentnumber,
  (select DESCRIPTION from department dl where dl.department_id = WEIGHINGHISTORY.DEPARTMENT_LINK_ID) departmentdescription,
  DISTRIBUTIONPOINT_LINK.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT_LINK.DESCRIPTION distributionpointdescription,
  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
  ) weighingcategorydescription,
  case
    when (rp.string_value = 'Y') then
      sum(WEIGHINGHISTORY.SOILWEIGHT)
    else
      sum(WEIGHINGHISTORY.CLEANWEIGHT)
  end amount,
  F_GETRECWEIGHTPRICE(rp.number_value, cs.customer_id, WEIGHINGHISTORY.WEIGHINGCATEGORY_LINK_ID,
    rp.string_value, rp.date_value1) price,
  round(case
    when (rp.string_value = 'Y') then
      sum(WEIGHINGHISTORY.SOILWEIGHT)
    else
      sum(WEIGHINGHISTORY.CLEANWEIGHT)
  end * F_GETRECWEIGHTPRICE(rp.number_value, cs.customer_id, WEIGHINGHISTORY.WEIGHINGCATEGORY_LINK_ID,
    rp.string_value, rp.date_value1)
    , (select cr.invoiceamountdecimals from currency cr where cr.currency_id = cs.currency_id)) rndamountprice,
  F_GETWEIGHTVAT(rp.number_value, cs.customer_id, WEIGHINGHISTORY.WEIGHINGCATEGORY_LINK_ID,
    rp.number_value1, (select ctr.country_id from country ctr where ctr.country_id = cs.country_id), rp.date_value1) vatrate,
  (select cr.decimals from currency cr where cr.currency_id = cs.currency_id) decimals,
  (select cr.invoiceamountdecimals from currency cr where cr.currency_id = cs.currency_id) invoiceamountdecimals,
  PROCESSBUSINESSUNIT.CODE processbusinessunitnr, PROCESSBUSINESSUNIT.DESCRIPTION processbusinessunitname,
  INVOICEBUSINESSUNIT.CODE invoicebusinessunitnr, INVOICEBUSINESSUNIT.DESCRIPTION invoicebusinessunitname,
  CUSTOMER_LINK.LANGUAGECODE CUSTOMERLANGUAGECODE,
  LANGUAGES.CODE LANGUAGECODE
, CASTVARCHARASNUMBER(SS.VALUE) WEIGHTDECIMALSMANUALINPUT
FROM WEIGHINGHISTORY, WEIGHINGCATEGORY_LINK,
  CUSTOMER_LINK
    left outer join customer cs
    on cs.customer_id = CUSTOMER_LINK.CUSTOMER_ID,
  DISTRIBUTIONPOINT_LINK,
  BUSINESSUNIT PROCESSBUSINESSUNIT, BUSINESSUNIT INVOICEBUSINESSUNIT
  , LANGUAGES, reportparam rp
  , SYSTEMSETTING SS
WHERE WEIGHINGHISTORY.CUSTOMER_LINK_ID = CUSTOMER_LINK.CUSTOMER_LINK_ID
AND WEIGHINGHISTORY.DISTRIBUTIONPOINT_LINK_ID = DISTRIBUTIONPOINT_LINK.DISTRIBUTIONPOINT_LINK_ID
AND WEIGHINGHISTORY.WEIGHINGCATEGORY_LINK_ID = WEIGHINGCATEGORY_LINK.WEIGHINGCATEGORY_LINK_ID
AND WEIGHINGHISTORY.PROCESSBUSINESSUNIT_ID = PROCESSBUSINESSUNIT.BUSINESSUNIT_ID
AND WEIGHINGHISTORY.INVOICEBUSINESSUNIT_ID = INVOICEBUSINESSUNIT.BUSINESSUNIT_ID
AND PROCESSBUSINESSUNIT.PLANT_ID = SS.PLANT_ID
AND SS.NAME = 'WEIGHTDECIMALSMANUALINPUT'
and CUSTOMER_LINK.Customernumber between rp.number_value2 and rp.number_value3
and WEIGHINGCATEGORY_LINK.CODE >= rp.string_value1
and WEIGHINGCATEGORY_LINK.CODE <= rp.string_value2
and WEIGHINGHISTORY.WEIGHINGDATE >= rp.date_value1
and WEIGHINGHISTORY.WEIGHINGDATE <= rp.date_value2
group by WEIGHINGCATEGORY_LINK.CODE,
         DISTRIBUTIONPOINT_LINK.DISTRIBUTIONPOINTNUMBER,
         WEIGHINGHISTORY.DEPARTMENT_LINK_ID,
         CUSTOMER_LINK.CUSTOMERNUMBER,
         rp.reportparam_id,
         CUSTOMER_LINK.CUSTOMER_ID,
         rp.string_value,
         CUSTOMER_LINK.NAME,
         DISTRIBUTIONPOINT_LINK.DESCRIPTION,
         WEIGHINGHISTORY.WEIGHINGCATEGORY_LINK_ID,
         LANGUAGES.LANGUAGE_ID,
         rp.number_value,
         cs.customer_id,
         WEIGHINGHISTORY.WEIGHINGCATEGORY_LINK_ID,
         rp.date_value1,
         rp.number_value1,
         cs.country_id,
         cs.currency_id,
         PROCESSBUSINESSUNIT.CODE,
         PROCESSBUSINESSUNIT.DESCRIPTION,
         INVOICEBUSINESSUNIT.CODE,
         INVOICEBUSINESSUNIT.DESCRIPTION,
         CUSTOMER_LINK.LANGUAGECODE,
         LANGUAGES.CODE,
         SS.VALUE

/
create or replace view V_WEIGHINGHISTORYPRICE_BCH
 (REPORTPARAM_ID, CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, WEIGHINGCATEGORYCODE, WEIGHINGCATEGORYDESCRIPTION, AMOUNT, PRICE, RNDAMOUNTPRICE, VATRATE, DECIMALS, INVOICEAMOUNTDECIMALS, PROCESSBUSINESSUNITNR, PROCESSBUSINESSUNITNAME, INVOICEBUSINESSUNITNR, INVOICEBUSINESSUNITNAME, CUSTOMERLANGUAGECODE, LANGUAGECODE, WEIGHTDECIMALSMANUALINPUT)
as SELECT /*+index (WEIGHINGHISTORY XIE5WEIGHINGHISTORY)*/
rp.reportparam_id, CUSTOMER_LINK.CUSTOMER_ID,
  CUSTOMER_LINK.CUSTOMERNUMBER, CUSTOMER_LINK.NAME customername,
  (select DEPARTMENTNUMBER from department_link dl where dl.department_link_id = WEIGHINGHISTORY.DEPARTMENT_LINK_ID) departmentnumber,
  (select DESCRIPTION from department_link dl where dl.department_link_id = WEIGHINGHISTORY.DEPARTMENT_LINK_ID) departmentdescription,
	DISTRIBUTIONPOINT_LINK.DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINT_LINK.DESCRIPTION distributionpointdescription,
	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
  ) weighingcategorydescription,
	case
		when (rp.string_value = 'Y') then
			sum(WEIGHINGHISTORY.SOILWEIGHT)
		else
			sum(WEIGHINGHISTORY.CLEANWEIGHT)
  end amount,
  F_GETRECWEIGHTPRICE(rp.number_value, cs.customer_id, WEIGHINGHISTORY.WEIGHINGCATEGORY_LINK_ID,
    rp.string_value, rp.date_value1) price,
	round(case
		when (rp.string_value = 'Y') then
			sum(WEIGHINGHISTORY.SOILWEIGHT)
		else
			sum(WEIGHINGHISTORY.CLEANWEIGHT)
  end * F_GETRECWEIGHTPRICE(rp.number_value, cs.customer_id, WEIGHINGHISTORY.WEIGHINGCATEGORY_LINK_ID,
    rp.string_value, rp.date_value1)
	  , (select cr.invoiceamountdecimals from currency cr where cr.currency_id = cs.currency_id)) rndamountprice,
  F_GETWEIGHTVAT(rp.number_value, cs.customer_id, WEIGHINGHISTORY.WEIGHINGCATEGORY_LINK_ID,
    rp.number_value1, (select ctr.country_id from country ctr where ctr.country_id = cs.country_id), rp.date_value1) vatrate,
  (select cr.decimals from currency cr where cr.currency_id = cs.currency_id) decimals,
  (select cr.invoiceamountdecimals from currency cr where cr.currency_id = cs.currency_id) invoiceamountdecimals,
	PROCESSBUSINESSUNIT.CODE processbusinessunitnr, PROCESSBUSINESSUNIT.DESCRIPTION processbusinessunitname,
  INVOICEBUSINESSUNIT.CODE invoicebusinessunitnr, INVOICEBUSINESSUNIT.DESCRIPTION invoicebusinessunitname,
	CUSTOMER_LINK.LANGUAGECODE CUSTOMERLANGUAGECODE,
  LANGUAGES.CODE LANGUAGECODE
, CASTVARCHARASNUMBER(SS.VALUE) WEIGHTDECIMALSMANUALINPUT
FROM WEIGHINGHISTORY, WEIGHINGCATEGORY_LINK,
  CUSTOMER_LINK
    left outer join customer cs
    on cs.customer_id = CUSTOMER_LINK.CUSTOMER_ID,
  DISTRIBUTIONPOINT_LINK,
	BUSINESSUNIT PROCESSBUSINESSUNIT, BUSINESSUNIT INVOICEBUSINESSUNIT
  , LANGUAGES, reportparam rp
  , SYSTEMSETTING SS
WHERE WEIGHINGHISTORY.CUSTOMER_LINK_ID = CUSTOMER_LINK.CUSTOMER_LINK_ID
AND WEIGHINGHISTORY.DISTRIBUTIONPOINT_LINK_ID = DISTRIBUTIONPOINT_LINK.DISTRIBUTIONPOINT_LINK_ID
AND WEIGHINGHISTORY.WEIGHINGCATEGORY_LINK_ID = WEIGHINGCATEGORY_LINK.WEIGHINGCATEGORY_LINK_ID
AND WEIGHINGHISTORY.PROCESSBUSINESSUNIT_ID = PROCESSBUSINESSUNIT.BUSINESSUNIT_ID
AND WEIGHINGHISTORY.INVOICEBUSINESSUNIT_ID = INVOICEBUSINESSUNIT.BUSINESSUNIT_ID
AND PROCESSBUSINESSUNIT.PLANT_ID = SS.PLANT_ID
AND SS.NAME = 'WEIGHTDECIMALSMANUALINPUT'
and CUSTOMER_LINK.Customernumber between rp.number_value2 and rp.number_value3
and WEIGHINGCATEGORY_LINK.CODE >= rp.string_value1
and WEIGHINGCATEGORY_LINK.CODE <= rp.string_value2
and WEIGHINGHISTORY.WEIGHINGDATE >= rp.date_value1
and WEIGHINGHISTORY.WEIGHINGDATE <= rp.date_value2
group by WEIGHINGCATEGORY_LINK.CODE,
         DISTRIBUTIONPOINT_LINK.DISTRIBUTIONPOINTNUMBER,
         WEIGHINGHISTORY.DEPARTMENT_LINK_ID,
				 CUSTOMER_LINK.CUSTOMERNUMBER,
				 rp.reportparam_id,
         CUSTOMER_LINK.CUSTOMER_ID,
         rp.string_value,
         CUSTOMER_LINK.NAME,
         DISTRIBUTIONPOINT_LINK.DESCRIPTION,
         WEIGHINGHISTORY.WEIGHINGCATEGORY_LINK_ID,
         LANGUAGES.LANGUAGE_ID,
         rp.number_value,
         cs.customer_id,
         WEIGHINGHISTORY.WEIGHINGCATEGORY_LINK_ID,
         rp.date_value1,
         rp.number_value1,
         cs.country_id,
         cs.currency_id,
         PROCESSBUSINESSUNIT.CODE,
         PROCESSBUSINESSUNIT.DESCRIPTION,
         INVOICEBUSINESSUNIT.CODE,
         INVOICEBUSINESSUNIT.DESCRIPTION,
         CUSTOMER_LINK.LANGUAGECODE,
         LANGUAGES.CODE,
         SS.VALUE

/
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, CORRECTEDNOTENUMBER, DELIVERYDATE, WEIGHINGYEAR, WEIGHINGWEEK, WEIGHTUNIT, CONTAINERRECORDINGACTIVE, USER_NAME, ORIGIN)
as SELECT WEIGHINGTICKET.SOILTICKET, WEIGHINGTICKET.TICKETNUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME customername, customer.customer_id,
  ADDRESS.STREET customervisitaddress_street, ADDRESS.ZIPCODE customervisitaddresszipcode,
  ADDRESS.CITY customervisitaddresscity, WEIGHINGTICKET.WEIGHINGDATE, STATUS.CODE statuscode,
  (SELECT DESCRIPTION FROM STATUS_DESC S
     WHERE S.STATUS_ID = WEIGHINGTICKET.STATUS_ID AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) STATUSDESCRIPTION,
  EMPLOYEE.EMPLOYEENUMBER, EMPLOYEE.NAME employeename, PROCESSBUSINESSUNIT.CODE processbusinessunitnr,
  PROCESSBUSINESSUNIT.DESCRIPTION processbusinessunitname, INVOICEBUSINESSUNIT.CODE invoicebusinessunitnr,
  INVOICEBUSINESSUNIT.DESCRIPTION invoicebusinessunitname, CONSIGNMENTNOTE.CONSIGNMENTNOTENUMBER,
  weighingticket.systemuser_id username, WEIGHINGTICKET.TIMESTAMP,
  PROCESSBUSINESSUNIT.PLANT_ID processbusinessunitplant_id, WEIGHINGTICKET.WEIGHINGTICKET_ID, WEIGHINGTICKET.DAYNUMBER,
  (SELECT DESCRIPTION FROM DAY_DESC
    WHERE DAY_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID AND DAY_DESC.DAY_ID = WEIGHINGTICKET.DAYNUMBER) DAYDESCRIPTION,
 	LANGUAGES.CODE LANGUAGECODE, customerlanguage.code customerlanguagecode,
  WEIGHINGTICKET.REMARK, WEIGHINGTICKET.CORRECTEDNOTENUMBER, WEIGHINGTICKET.DELIVERYDATE,
	WEIGHINGTICKET.WEIGHINGYEAR, WEIGHINGTICKET.WEIGHINGWEEK,
  SS.VALUE WEIGHTUNIT, SS1.VALUE CONTAINERRECORDINGACTIVE,(select su.username from systemuser su where weighingticket.systemuser_id = su.systemuser_id) user_name,
  WEIGHINGTICKET.Origin
FROM  CUSTOMER, ADDRESS, STATUS,
  BUSINESSUNIT PROCESSBUSINESSUNIT
    LEFT OUTER JOIN (PLANT PL left OUTER JOIN SYSTEMSETTING SS ON PL.PLANT_ID = SS.PLANT_ID AND SS.NAME = 'WEIGHTUNIT')
      ON PROCESSBUSINESSUNIT.PLANT_ID = PL.PLANT_ID
    LEFT OUTER JOIN (PLANT PL1 left OUTER JOIN SYSTEMSETTING SS1 ON PL1.PLANT_ID = SS1.PLANT_ID AND SS1.NAME = 'CONTAINERRECORDINGACTIVE')
      ON PROCESSBUSINESSUNIT.PLANT_ID = PL1.PLANT_ID,
  BUSINESSUNIT INVOICEBUSINESSUNIT,
--    LEFT OUTER JOIN (PLANT PL left OUTER JOIN SYSTEMSETTING SS ON PL.PLANT_ID = SS.PLANT_ID AND SS.NAME = 'WEIGHTUNIT')
--      ON INVOICEBUSINESSUNIT.PLANT_ID = PL.PLANT_ID
--    LEFT OUTER JOIN (PLANT PL1 left OUTER JOIN SYSTEMSETTING SS1 ON PL1.PLANT_ID = SS1.PLANT_ID AND SS1.NAME = 'CONTAINERRECORDINGACTIVE')
--      ON INVOICEBUSINESSUNIT.PLANT_ID = PL1.PLANT_ID,
  WEIGHINGTICKET
    LEFT OUTER JOIN EMPLOYEE ON (WEIGHINGTICKET.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
    LEFT OUTER JOIN CONSIGNMENTNOTE ON (WEIGHINGTICKET.CONSIGNMENTNOTE_ID = CONSIGNMENTNOTE.CONSIGNMENTNOTE_ID),
  LANGUAGES customerlanguage, languages --systemuser su
WHERE WEIGHINGTICKET.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND CUSTOMER.VISITADDRESS_ID = ADDRESS.ADDRESS_ID
  AND WEIGHINGTICKET.STATUS_ID = STATUS.STATUS_ID
  AND WEIGHINGTICKET.PROCESSBUSINESSUNIT_ID = PROCESSBUSINESSUNIT.BUSINESSUNIT_ID
  AND WEIGHINGTICKET.INVOICEBUSINESSUNIT_ID = INVOICEBUSINESSUNIT.BUSINESSUNIT_ID
  and customer.language_id = customerlanguage.language_id
  --and weighingticket.systemuser_id = su.systemuser_id

/
create or replace view V_WEIGHINGTICKETLINE
 (TICKETNUMBER, SEQUENCENUMBER, CONTAINERTYPECODE, CONTAINERTYPE_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, WEIGHINGCATEGORY_CODE, WEIGHINGCATEGORY_DESC, TAREWEIGHT, GROSSWEIGHT, WEIGHTDECIMALS, NETWEIGHT, SYSTEMUSER_ID, TIMESTAMP, WEIGHINGSEQUENCENR, CONTAINER_PRIMARYID, SOILPORTION, OLD_WEIGHT, DISTRIBUTIONPOINT_DESC, DISTRIBUTIONPOINTNUMBER, LANGUAGECODE, REPORTPARAM_ID)
as SELECT WEIGHINGTICKET.TICKETNUMBER, max(WEIGHINGTICKETLINE.SEQUENCENUMBER)SEQUENCENUMBER,
       (SELECT C.CODE FROM CONTAINERTYPE C WHERE C.CONTAINERTYPE_ID = WEIGHINGTICKETLINE.CONTAINERTYPE_ID) CONTAINERTYPECODE,
       (SELECT A.DESCRIPTION FROM CONTAINERTYPE_DESC A WHERE A.CONTAINERTYPE_ID = WEIGHINGTICKETLINE.CONTAINERTYPE_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) CONTAINERTYPE_DESC,
       DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION DEPARTMENTDESCRIPTION,
       WEIGHINGCATEGORY.CODE WEIGHINGCATEGORY_CODE,
       (SELECT description FROM WEIGHINGCATEGORY_DESC B WHERE B.WEIGHINGCATEGORY_ID = WEIGHINGTICKETLINE.WEIGHINGCATEGORY_ID AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) WEIGHINGCATEGORY_desc,
       WEIGHINGTICKETLINE.TAREWEIGHT, WEIGHINGTICKETLINE.GROSSWEIGHT, WEIGHINGTICKETLINE.WEIGHTDECIMALS,
       (WEIGHINGTICKETLINE.GROSSWEIGHT - WEIGHINGTICKETLINE.TAREWEIGHT) NETWEIGHT,
       WEIGHINGTICKETLINE.SYSTEMUSER_ID, WEIGHINGTICKETLINE.TIMESTAMP, WEIGHINGTICKETLINE.WEIGHINGSEQUENCENR,
       CONTAINER.PRIMARYID container_primaryID,
       WEIGHINGTICKETLINE.SOILPORTION,
       F_GETOLDWEIGHT(rp.number_value1, WEIGHINGTICKET.Correctednotenumber, WEIGHINGTICKETLINE.Weighingcategory_Id) old_weight,
       dp.description distributionpoint_desc, dp.distributionpointnumber,
       languages.code LANGUAGECODE, rp.reportparam_id
FROM WEIGHINGTICKET,
     WEIGHINGTICKETLINE
       left outer join CONTAINER ON CONTAINER.CONTAINER_ID = WEIGHINGTICKETLINE.CONTAINER_ID
       left outer join distributionpoint dp on dp.distributionpoint_id = WEIGHINGTICKETLINE.Distributionpoint_Id,
     WEIGHINGCATEGORY, DEPARTMENT, LANGUAGES, reportparam rp
  WHERE WEIGHINGTICKETLINE.WEIGHINGTICKET_ID = WEIGHINGTICKET.WEIGHINGTICKET_ID
  AND WEIGHINGTICKETLINE.DEPARTMENT_ID = DEPARTMENT.DEPARTMENT_ID
  AND WEIGHINGTICKETLINE.WEIGHINGCATEGORY_ID = WEIGHINGCATEGORY.WEIGHINGCATEGORY_ID
 and WEIGHINGTICKET.Ticketnumber=rp.number_value
group by WEIGHINGTICKET.TICKETNUMBER, --WEIGHINGTICKETLINE.SEQUENCENUMBER,
       WEIGHINGTICKETLINE.CONTAINERTYPE_ID,WEIGHINGTICKETLINE.Weighingticketline_Id,
       LANGUAGES.LANGUAGE_ID,
       DEPARTMENT.DEPARTMENTNUMBER, DEPARTMENT.DESCRIPTION,
       WEIGHINGCATEGORY.CODE,
       WEIGHINGTICKETLINE.WEIGHINGCATEGORY_ID,
       WEIGHINGTICKETLINE.TAREWEIGHT, WEIGHINGTICKETLINE.GROSSWEIGHT, WEIGHINGTICKETLINE.WEIGHTDECIMALS,
       WEIGHINGTICKETLINE.SYSTEMUSER_ID, WEIGHINGTICKETLINE.TIMESTAMP, WEIGHINGTICKETLINE.WEIGHINGSEQUENCENR,
       CONTAINER.PRIMARYID,
       WEIGHINGTICKETLINE.SOILPORTION,
       F_GETOLDWEIGHT(rp.number_value1, WEIGHINGTICKET.Correctednotenumber, WEIGHINGTICKETLINE.Weighingcategory_Id),
       dp.description, dp.distributionpointnumber,
       languages.code, rp.reportparam_id

/
create or replace view V_WEIGHINGTICKETLINE_SMG
 (TICKETNUMBER, SEQUENCENUMBER, CONTAINERTYPECODE, CONTAINERTYPE_DESC, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, WEIGHINGCATEGORY_CODE, WEIGHINGCATEGORY_DESC, TAREWEIGHT, GROSSWEIGHT, WEIGHTDECIMALS, NETWEIGHT, SYSTEMUSER_ID, TIMESTAMP, WEIGHINGSEQUENCENR, CONTAINER_PRIMARYID, SOILPORTION, OLD_WEIGHT, DISTRIBUTIONPOINT_DESC, DISTRIBUTIONPOINTNUMBER, COSTCENTER_CODE, COSTCENTER_DESC, DELPOINT_CODE, DELPOINT_DESC, STREET, ZIPCODE, CITY, NOTENUMBER, DELIVERYDATE, ROUTENUMBER
, ROUTE_DESC, LANGUAGECODE, REPORTPARAM_ID)
as SELECT WEIGHINGTICKET.TICKETNUMBER, max(WEIGHINGTICKETLINE.SEQUENCENUMBER)SEQUENCENUMBER,
       (SELECT C.CODE FROM CONTAINERTYPE C WHERE C.CONTAINERTYPE_ID = WEIGHINGTICKETLINE.CONTAINERTYPE_ID) CONTAINERTYPECODE,
       (SELECT A.DESCRIPTION FROM CONTAINERTYPE_DESC A WHERE A.CONTAINERTYPE_ID = WEIGHINGTICKETLINE.CONTAINERTYPE_ID AND A.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) CONTAINERTYPE_DESC,
       dep.DEPARTMENTNUMBER, dep.DESCRIPTION DEPARTMENTDESCRIPTION,
       WEIGHINGCATEGORY.CODE WEIGHINGCATEGORY_CODE,
       (SELECT description FROM WEIGHINGCATEGORY_DESC B WHERE B.WEIGHINGCATEGORY_ID = WEIGHINGTICKETLINE.WEIGHINGCATEGORY_ID AND B.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID) WEIGHINGCATEGORY_desc,
       WEIGHINGTICKETLINE.TAREWEIGHT, WEIGHINGTICKETLINE.GROSSWEIGHT, WEIGHINGTICKETLINE.WEIGHTDECIMALS,
       (WEIGHINGTICKETLINE.GROSSWEIGHT - WEIGHINGTICKETLINE.TAREWEIGHT) NETWEIGHT,
       WEIGHINGTICKETLINE.SYSTEMUSER_ID, WEIGHINGTICKETLINE.TIMESTAMP, WEIGHINGTICKETLINE.WEIGHINGSEQUENCENR,
       CONTAINER.PRIMARYID container_primaryID,
       WEIGHINGTICKETLINE.SOILPORTION,
       F_GETOLDWEIGHT(rp.number_value1, WEIGHINGTICKET.Correctednotenumber, WEIGHINGTICKETLINE.Weighingcategory_Id) old_weight,
       dp.description distributionpoint_desc, dp.distributionpointnumber,
       cc.code CostCenter_Code, cc.description CostCenter_Desc, delp.code DelPoint_Code, delp.description DelPoint_Desc,
       adr.street, adr.zipcode, adr.city, pn.notenumber, pn.deliverydate, ro.routenumber, ro.description Route_Desc,
       languages.code LANGUAGECODE, rp.reportparam_id
FROM WEIGHINGTICKET,
     WEIGHINGTICKETLINE
       left outer join CONTAINER ON CONTAINER.CONTAINER_ID = WEIGHINGTICKETLINE.CONTAINER_ID
       left outer join packingnotecontainer pnc
            inner join packingnote pn
                  left outer join route ro on ro.route_id = pn.route_id
                  inner join distributionpoint dp
                        inner join costcenter cc on cc.costcenter_id = dp.costcenter_id
                        inner join deliverypoint delp
                              inner join address adr on adr.address_id = delp.deliveryaddress_id
                        on delp.deliverypoint_id = dp.deliverypoint_id
                   on dp.distributionpoint_id = pn.Distributionpoint_Id
            on pn.packingnote_id = pnc.packingnote_id
       on pnc.weighingticketline_id = WEIGHINGTICKETLINE.Weighingticketline_Id,
     WEIGHINGCATEGORY, DEPARTMENT dep, LANGUAGES, reportparam rp
  WHERE WEIGHINGTICKETLINE.WEIGHINGTICKET_ID = WEIGHINGTICKET.WEIGHINGTICKET_ID
  AND WEIGHINGTICKETLINE.DEPARTMENT_ID = dep.DEPARTMENT_ID
  AND WEIGHINGTICKETLINE.WEIGHINGCATEGORY_ID = WEIGHINGCATEGORY.WEIGHINGCATEGORY_ID
 and WEIGHINGTICKET.Ticketnumber=rp.number_value
group by WEIGHINGTICKET.TICKETNUMBER, --WEIGHINGTICKETLINE.SEQUENCENUMBER,
       WEIGHINGTICKETLINE.CONTAINERTYPE_ID,WEIGHINGTICKETLINE.Weighingticketline_Id,
       LANGUAGES.LANGUAGE_ID,
       dep.DEPARTMENTNUMBER, dep.DESCRIPTION,
       WEIGHINGCATEGORY.CODE,
       WEIGHINGTICKETLINE.WEIGHINGCATEGORY_ID,
       WEIGHINGTICKETLINE.TAREWEIGHT, WEIGHINGTICKETLINE.GROSSWEIGHT, WEIGHINGTICKETLINE.WEIGHTDECIMALS,
       WEIGHINGTICKETLINE.SYSTEMUSER_ID, WEIGHINGTICKETLINE.TIMESTAMP, WEIGHINGTICKETLINE.WEIGHINGSEQUENCENR,
       CONTAINER.PRIMARYID,
       WEIGHINGTICKETLINE.SOILPORTION,
       F_GETOLDWEIGHT(rp.number_value1, WEIGHINGTICKET.Correctednotenumber, WEIGHINGTICKETLINE.Weighingcategory_Id),
       dp.description, dp.distributionpointnumber,
       languages.code, rp.reportparam_id, cc.code, cc.description, delp.code, delp.description, adr.street, adr.zipcode, adr.city,
       pn.notenumber, pn.deliverydate, ro.routenumber, ro.description

/
create or replace view V_WEIGHINGTICKET_CBD
 (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, CORRECTEDNOTENUMBER, DELIVERYDATE, WEIGHINGYEAR, WEIGHINGWEEK, WEIGHTUNIT, CONTAINERRECORDINGACTIVE, USER_NAME, ORIGIN, ROUTENUMBER, ROUTEDESC, STOPNUMBER, LOADINGDOCK, EMPLOYEEPHONE, EMPLOYEEMAIL, DEBTOR_NUMBER)
as SELECT WEIGHINGTICKET.SOILTICKET, WEIGHINGTICKET.TICKETNUMBER, CUSTOMER.CUSTOMERNUMBER, CUSTOMER.NAME customername, customer.customer_id,
  ADDRESS.STREET customervisitaddress_street, ADDRESS.ZIPCODE customervisitaddresszipcode,
  ADDRESS.CITY customervisitaddresscity, WEIGHINGTICKET.WEIGHINGDATE, STATUS.CODE statuscode,
  (SELECT DESCRIPTION FROM STATUS_DESC S
     WHERE S.STATUS_ID = WEIGHINGTICKET.STATUS_ID AND S.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID ) STATUSDESCRIPTION,
  EMPLOYEE.EMPLOYEENUMBER, EMPLOYEE.NAME employeename, PROCESSBUSINESSUNIT.CODE processbusinessunitnr,
  PROCESSBUSINESSUNIT.DESCRIPTION processbusinessunitname, INVOICEBUSINESSUNIT.CODE invoicebusinessunitnr,
  INVOICEBUSINESSUNIT.DESCRIPTION invoicebusinessunitname, CONSIGNMENTNOTE.CONSIGNMENTNOTENUMBER,
  weighingticket.systemuser_id username, WEIGHINGTICKET.TIMESTAMP,
  PROCESSBUSINESSUNIT.PLANT_ID processbusinessunitplant_id, WEIGHINGTICKET.WEIGHINGTICKET_ID, WEIGHINGTICKET.DAYNUMBER,
  (SELECT DESCRIPTION FROM DAY_DESC
    WHERE DAY_DESC.LANGUAGE_ID = LANGUAGES.LANGUAGE_ID AND DAY_DESC.DAY_ID = WEIGHINGTICKET.DAYNUMBER) DAYDESCRIPTION,
 	LANGUAGES.CODE LANGUAGECODE, customerlanguage.code customerlanguagecode,
  WEIGHINGTICKET.REMARK, WEIGHINGTICKET.CORRECTEDNOTENUMBER, WEIGHINGTICKET.DELIVERYDATE,
	WEIGHINGTICKET.WEIGHINGYEAR, WEIGHINGTICKET.WEIGHINGWEEK,
  SS.VALUE WEIGHTUNIT, SS1.VALUE CONTAINERRECORDINGACTIVE, su.username user_name,
  WEIGHINGTICKET.Origin,
  r.routenumber, r.description, rs.stopnumber, r.loadingdock,
  EMPLOYEE.phoneno  EMPLOYEEPHONE, EMPLOYEE.email EMPLOYEEMAIL,
  (select deb.customernumber from customer deb where deb.customer_id = customer.debtor_id) debtor_number
FROM  CUSTOMER
    LEFT OUTER JOIN EMPLOYEE ON (CUSTOMER.serviceemployee_id = EMPLOYEE.EMPLOYEE_ID),
  ADDRESS, STATUS,
  BUSINESSUNIT PROCESSBUSINESSUNIT
    LEFT OUTER JOIN (PLANT PL left OUTER JOIN SYSTEMSETTING SS ON PL.PLANT_ID = SS.PLANT_ID AND SS.NAME = 'WEIGHTUNIT')
      ON PROCESSBUSINESSUNIT.PLANT_ID = PL.PLANT_ID
    LEFT OUTER JOIN (PLANT PL1 left OUTER JOIN SYSTEMSETTING SS1 ON PL1.PLANT_ID = SS1.PLANT_ID AND SS1.NAME = 'CONTAINERRECORDINGACTIVE')
      ON PROCESSBUSINESSUNIT.PLANT_ID = PL1.PLANT_ID,
  BUSINESSUNIT INVOICEBUSINESSUNIT,
--    LEFT OUTER JOIN (PLANT PL left OUTER JOIN SYSTEMSETTING SS ON PL.PLANT_ID = SS.PLANT_ID AND SS.NAME = 'WEIGHTUNIT')
--      ON INVOICEBUSINESSUNIT.PLANT_ID = PL.PLANT_ID
--    LEFT OUTER JOIN (PLANT PL1 left OUTER JOIN SYSTEMSETTING SS1 ON PL1.PLANT_ID = SS1.PLANT_ID AND SS1.NAME = 'CONTAINERRECORDINGACTIVE')
--      ON INVOICEBUSINESSUNIT.PLANT_ID = PL1.PLANT_ID,
  WEIGHINGTICKET
    --LEFT OUTER JOIN EMPLOYEE ON (WEIGHINGTICKET.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID)
    LEFT OUTER JOIN CONSIGNMENTNOTE ON (WEIGHINGTICKET.CONSIGNMENTNOTE_ID = CONSIGNMENTNOTE.CONSIGNMENTNOTE_ID),
  LANGUAGES customerlanguage, languages, systemuser su,
  route r, routestop rs, routecontrol rc, deliveryschemesperstop ds
WHERE WEIGHINGTICKET.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID
  AND CUSTOMER.VISITADDRESS_ID = ADDRESS.ADDRESS_ID
  AND WEIGHINGTICKET.STATUS_ID = STATUS.STATUS_ID
  AND WEIGHINGTICKET.PROCESSBUSINESSUNIT_ID = PROCESSBUSINESSUNIT.BUSINESSUNIT_ID
  AND WEIGHINGTICKET.INVOICEBUSINESSUNIT_ID = INVOICEBUSINESSUNIT.BUSINESSUNIT_ID
  and customer.language_id = customerlanguage.language_id
  and weighingticket.systemuser_id = su.systemuser_id
  and customer.customer_id = rs.customer_id
  and r.route_id = rs.route_id
  and WEIGHINGTICKET.weighingdate = rc.drivingdate
  and rc.route_id = r.route_id
  and rc.route_id = rs.route_id
  and CUSTOMER.customer_id = ds.customer_id
  and ds.deliveryscheme_id = 1                  -- wöchentlich 01W01
  and rs.routestop_id = ds.routestop_id
  and rs.dateinactive = to_date('31.12.2099', 'dd-mm-yyyy')

/
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
  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
, ROUND(weighinghistory.soilweight, 1) soilweight
, ROUND(weighinghistory.cleanweight, 1) 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 '' 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_WEIGHTSPERWEEK_LTS
 (LINETYPE, DAYNUMBER, WEIGHINGDATE, WEIGHINGDATEDAY, WEEK, YEAR, CUSTOMERNUMBER, CUSTOMERNAME, CUSTOMER_ID, WEIGHINGCATEGORYCODE, WEIGHINGCATEGORYDESCRIPTION, GROSSWEIGHT, TAREWEIGHT, NETWEIGHT, TICKETNUMBER, WEIGHINGTICKETLINE_ID, LANGUAGECODE, CONTAINERTYPECODE, CONTAINERTYPEDESC, PROCESSBUSINESSUNIT_ID, DEPARTMENTNUMBER, DEPARTMENTDESCRIPTION, DISTRIBUTIONPOINTNUMBER, DISTRIBUTIONPOINTDESCRIPTION, YEARWEEK, REALMONTH, REALYEAR, SOILWEIGHT, CLEANWEIGHT, PROCESSBUSINESSUNITNR
, PROCESSBUSINESSUNITNAME, SYSTEMUSER_ID, TIMESTAMP, CUSTOMERLANGUAGECODE, WEIGHTDECIMALSMANUALINPUT)
as select 1 linetype, 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 week,
       weit.weighingyear year,
       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) weighingcategorydescription,
       weitli.grossweight,
       weitli.tareweight,
       (weitli.grossweight - weitli.tareweight) NetWeight,
       weit.ticketnumber,
       weitli.weighingticketline_id,
       languages.code languageCode,
       c.code containertypecode,
       (select ctd.description from containertype_desc ctd where ctd.containertype_id = c.containertype_id and ctd.language_id = languages.language_id) containertypedesc,
       weit.processbusinessunit_id,
       dl.departmentnumber departmentnumber,
       dl.description departmentdescription,
       (select max(dpl.distributionpointnumber) from distributionpoint_link dpl where dpl.department_link_id = dl.department_link_id) distributionpointnumber,
       (select max(dpl.description)  from distributionpoint_link dpl where dpl.department_link_id = dl.department_link_id) distributionpointdescription,
       weit.weighingyear * 100 + weit.weighingweek yearweek,
       month(weit.weighingdate) realmonth,
       year(weit.weighingdate) realyear,
       --weighinghistory.soilweight,--
       --weighinghistory.cleanweight,-- dsdasdfas
       case when weit.soilticket = 'Y' then 1 else 0 end soilweight,
       case when weit.soilticket = 'N' then 1 else 0 end cleanweight,
       processBU.code processbusinessunitnr,
       processBU.description processbusinessunitname,
       weitli.systemuser_id,
       weitli.timestamp,
       cu.languagecode customerlanguagecode,
       castvarcharasnumber(ss.value) weightdecimalsmanualinpUT
  from weighingticket weit, department_link dl
       , weighingticketline weitli
           left outer join containertype c on weitli.containertype_id = c.containertype_id
           --left outer join distributionpoint_link dpl on weitli.distributionpoint_id = dpl.distributionpoint_id
       , weighingcategory
 weicat, customer_link cu, businessunit processBU, systemsetting ss,
 languages
 where weit.weighingticket_id = weitli.weighingticket_id
   and weitli.department_id = dl.department_id
   and weitli.weighingcategory_id = weicat.weighingcategory_id
   and weit.customer_id = cu.customer_id
   and weit.processbusinessunit_id = processBU.Businessunit_Id
   and processBU.plant_id = ss.plant_id
   and ss.name = 'WEIGHTDECIMALSMANUALINPUT'
union all
select 2 linetype, 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 week,
       weit.weighingyear year,
       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) weighingcategorydescription,
       weitli.grossweight,
       weitli.tareweight,
       (weitli.grossweight - weitli.tareweight) NetWeight,
       weit.ticketnumber,
       weitli.weighingticketline_id,
       languages.code languageCode,
       c.code containertypecode,
       (select ctd.description from containertype_desc ctd where ctd.containertype_id = c.containertype_id and ctd.language_id = languages.language_id) containertypedesc,
       weit.processbusinessunit_id,
       dl.departmentnumber departmentnumber,
       dl.description departmentdescription,
       (select max(dpl.distributionpointnumber) from distributionpoint_link dpl where dpl.department_link_id = dl.department_link_id) distributionpointnumber,
       (select max(dpl.description) from distributionpoint_link dpl where dpl.department_link_id = dl.department_link_id) distributionpointdescription,
       weit.weighingyear * 100 + weit.weighingweek yearweek,
       month(weit.weighingdate) realmonth,
       year(weit.weighingdate) realyear,
       --weighinghistory.soilweight,--
       --weighinghistory.cleanweight,-- dsdasdfas
       case when weit.soilticket = 'Y' then 1 else 0 end soilweight,
       case when weit.soilticket = 'N' then 1 else 0 end cleanweight,
       processBU.code processbusinessunitnr,
       processBU.description processbusinessunitname,
       weitli.systemuser_id,
       weitli.timestamp,
       cu.languagecode customerlanguagecode,
       castvarcharasnumber(ss.value) weightdecimalsmanualinpUT
  from weighingticket weit, department_link dl
       , weighingticketline weitli
           left outer join containertype c on weitli.containertype_id = c.containertype_id
           left outer join distributionpoint_link dpl on weitli.distributionpoint_id = dpl.distributionpoint_id
       , weighingcategory
 weicat, customer_link cu, businessunit processBU, systemsetting ss,
 languages
 where weit.weighingticket_id = weitli.weighingticket_id
   and weitli.department_id = dl.department_id
   and weitli.weighingcategory_id = weicat.weighingcategory_id
   and weit.customer_id = cu.customer_id
   and weit.processbusinessunit_id = processBU.Businessunit_Id
   and processBU.plant_id = ss.plant_id
   and ss.name = 'WEIGHTDECIMALSMANUALINPUT'

/
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_WORKORDERCONVP_SMG
 (WORKORDERLINE_ID, DESTPRODCODE, PRODDESC, FMCODE, DESTSIZECODE, QCODE, QUANTITYPHASEIN, LANCODE)
as select  wol.workorderline_id,  (select destprod.code from product destprod where destprod.product_id=wphasein.product_id) destprodcode,
( select pd.description from product_desc pd where pd.product_id=wphasein.product_id and pd.language_id=lan.language_id )  proddesc,
( select fm.code from finishingmethod fm where wphasein.finishingmethod_id=fm.finishingmethod_id)fmcode,
 destsize.code destsizecode,qq.code qcode,wol.quantityphasein, lan.code lancode
from  workorder wo, workorderline wol, wearerinventory wi, wearerinventory wphasein,
  PhaseOutWearerInventory pco, productconversion pc,
  sizedefinition destsize, qualitygrade qq, languages lan
where wo.workorder_id=wol.workorder_id
      and wo.weareremployment_link_id= wi.weareremployment_id
      and wi.wearerinventory_id=pco.phaseoutwearerinventory_id
      and pco.phaseinwearerinventory_id=wphasein.wearerinventory_id
      and wo.weareremployment_link_id=wphasein.weareremployment_id
      and wphasein.product_id=pc.destinationproduct_id
      and wphasein.sizedefinition_id=destsize.sizedefinition_id
      and pc.sourceproduct_id=wol.product_link_id
      and wi.product_id = pc.sourceproduct_id
      and wi.sizedefinition_id=wol.sizedefinition_link_id
      and wi.product_id=wol.product_link_id
      and wo.customer_link_id=pc.customer_link_id
      and pc.status=1
      and pc.startdate > wo.neededdate
      and wol.requestedgrade_id=qq.qualitygrade_id

/
create or replace view V_WORKORDEREMBLEM_AUJ
 (LINETYPE, WORKORDER_ID, WORKORDERLINE_ID, QTYREQUESTED, EMBLEMTEMPLATELINE_ID, EMBLEMTYPE, EMBLCODE, EMBLTEMPLATE_DESC, PLACEMENTCODE, PLACEMENTDESC, PRODCODE, PRODDESC, LANGUAGECODE)
as select 1 linetype, wol.workorder_id, wole.workorderline_id, wole.qtyrequested,
       wole.emblemtemplateline_id,
       castNumberAsVarchar(etl.emblemtype) emblemtype,
       (select et.code from emblemtemplate et where etl.emblemtemplate_id = et.emblemtemplate_id) emblcode,
       etl.description embltemplate_desc,
       (select p.code from placement p where p.placement_id = wole.placement_id) placementcode,
       (select pld.description from placement_desc pld where pld.placement_id = wole.placement_id and pld.language_id = lan.language_id) placementdesc,
       (select pr.code from product_link pr where pr.product_link_id = wol.product_link_id) prodcode,
       (select prd.description from product_link_desc prd where prd.product_link_id = wol.product_link_id and prd.language_id = lan.language_id) proddesc,
       lan.code languagecode
from workorderline wol, workorderlineemblem wole, emblemtemplateline etl, languages lan
where wol.workorderline_id = wole.workorderline_id
      and wole.emblemtemplateline_id = etl.emblemtemplateline_id
union all
select 2 linetype, wol.workorder_id, wole.workorderline_id, wole.qtyrequested,
       p.product_id emblemtemplateline_id,
       'Other' emblemtype,
       p.code emblcode,
       (select pd.description from product_desc pd where pd.product_id = p.product_id and pd.language_id = lan.language_id) embltemplate_desc,
       (select p.code from placement p where p.placement_id = wole.placement_id) placementcode,
       (select pld.description from placement_desc pld where pld.placement_id = wole.placement_id and pld.language_id = lan.language_id) placementdesc,
       (select pr.code from product_link pr where pr.product_link_id = wol.product_link_id) prodcode,
       (select prd.description from product_link_desc prd where prd.product_link_id = wol.product_link_id and prd.language_id = lan.language_id) proddesc,
       lan.code languagecode
from workorderline wol, workorderlineemblem wole, product p, languages lan
where wol.workorderline_id = wole.workorderline_id
      and wole.product_id = p.product_id

/
create or replace view V_WORKORDEREMBLEM_EMBCOL_NAF
 (EMBLEMTEMPLATELINE_ID, EMBROIDERYCOLOR_ID, SEQUENCENUMBER, COLOR_ID, COLOR_CODE, COLOR_RALCODE, COLOR_USEDFOREMBLEM, COLOR_DESCRIPTION, SYSTEMUSER_ID, TIMESTAMP, LANGUAGECODE)
as SELECT ec.emblemtemplateline_id, ec.embroiderycolor_id, ec.sequencenumber,
       ec.color_id, color.code color_code, color.ralcode color_ralcode, color.usedforemblem color_usedforemblem,
       (SELECT cd.description FROM color_desc cd WHERE cd.color_id = color.color_id AND cd.language_id = lang.language_id) color_description,
       ec.systemuser_id, ec.timestamp,
       lang.code LANGUAGECODE
FROM embroiderycolor ec, color, emblemtemplateline et, languages lang
WHERE ec.emblemtemplateline_id = et.emblemtemplateline_id
      AND ec.color_id = color.color_id

/
create or replace view V_WORKORDEREMBLEM_NAF
 (WORKORDER_ID, WORKORDERLINE_ID, LANGUAGECODE, EMBLEMNR, EMBLEMDESCRIPTION, EMBLEMLDESCRIPTION, EMBLEMTYPE, SIZESHAPE, BACKGROUND, BORDER, TEXT, QUANTITY, PLACEMENT, PLACEMENTDESC, PUTEMBLEMON, WORKORDERLINEEMBLEM_ID, FABRIC, EMBLEM_FONT, PRODUCT_ID, SIZEDEFINITION_ID, ATTACHMENT_BY, EMBROYDERYFILEPATHPRODUCTION, FONTSIZE, COLORPALETTE, EMBLEMTEMPLATELINE_ID, EMBLEMTEMPLATELINE_DESC, ROWLOCATION)
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
, (select product_desc.longdescription from product_desc where product_desc.product_id = p.product_id
  and product_desc.language_id = languages.language_id) EmblemLDescription
, EmblemType, sizedefinition.code SizeShape, color.code Background, c.code Border, txt.code Text
, wokem.qtyrequested Quantity , placement.code Placement
, (select placedesc.description from
   placement_desc placedesc where placement.placement_id = placedesc.placement_id
                            AND placedesc.language_id = languages.language_id) PlacementDesc
, product_link.code PutEmblemOn
, wokem.workorderlineemblem_id
, fabric.code fabric, null emblem_font
, wokem.product_id, wokem.sizedefinition_id
, -1 attachment_by
, null embroyderyfilepathproduction, null fontsize, null colorpalette
, null emblemtemplateline_id
, null emblemtemplateline_desc
, cast ((select case when srl.rowcode is null
                then srl.locationcode else srl.rowcode || '#' || srl.locationcode end rowloc
         from stockroomlocation srl where srl.stockroomlocation_id =
         f_getfirstrowlocationid_naf(workorderline.product_link_id,workorderline.sizedefinition_link_id,workorderline.requestedgrade_id,workorderline.codeuniquely, wok.processingstockroom_id))
  as varchar2(60)) rowlocation
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 inner join workorder wok ON workorderline.workorder_id = wok.workorder_id
, product p, fabric
, product_link
 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
, (select product_desc.longdescription from product_desc where product_desc.product_id = p.product_id
  and product_desc.language_id = languages.language_id)
, emblemtemplateline.emblemtype EmblemType, sizedefinition.code SizeShape, color.code Background
, c.code Border, txt.code Text, wokem.qtyrequested Quantity , placement.code Placement
, (select placedesc.description from
   placement_desc placedesc where placement.placement_id = placedesc.placement_id
                            AND placedesc.language_id = languages.language_id) PlacementDesc
, 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
, cast ((select case when srl.rowcode is null
                then srl.locationcode else srl.rowcode || '#' || srl.locationcode end rowloc
         from stockroomlocation srl where srl.stockroomlocation_id =
         f_getfirstrowlocationid_naf(workorderline.product_link_id,workorderline.sizedefinition_link_id,workorderline.requestedgrade_id,workorderline.codeuniquely, wok.processingstockroom_id))
  as varchar2(60)) rowlocation
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 inner join workorder wok ON workorderline.workorder_id = wok.workorder_id
, fabric
, product_link
, 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
, (select product_desc.longdescription from product_desc where product_desc.product_id = product_link.product_id
  and product_desc.language_id = languages.language_id)
, emblemtemplateline.emblemtype EmblemType, sizedefinition.code SizeShape, color.code Background
, c.code Border, txt.code Text, wokem.qtyrequested Quantity ,placement.code Placement
, (select placedesc.description from
   placement_desc placedesc where placement.placement_id = placedesc.placement_id
                            AND placedesc.language_id = languages.language_id) PlacementDesc
, 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
, cast ((select case when srl.rowcode is null
                then srl.locationcode else srl.rowcode || '#' || srl.locationcode end rowloc
         from stockroomlocation srl where srl.stockroomlocation_id =
         f_getfirstrowlocationid_naf(workorderline.product_link_id,workorderline.sizedefinition_link_id,workorderline.requestedgrade_id,workorderline.codeuniquely, wok.processingstockroom_id))
  as varchar2(60)) rowlocation
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 inner join workorder wok ON workorderline.workorder_id = wok.workorder_id
, fabric
, product_link
, 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_WORKORDEREMBLEM_POS
 (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)
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
, (select cd.description from color_desc cd where p.color_id = cd.color_id and languages.language_id = cd.language_id) Background
, (select c.description from color_desc c where e.bordercolor_id = c.color_id and languages.language_id = c.language_id) Border
, (select txt.description from color_desc txt where e.textcolor_id = txt.color_id and languages.language_id = txt.language_id) Text
, wokem.qtyrequested Quantity , placement.code Placement, product_link.code PutEmblemOn
, wokem.workorderlineemblem_id
, fabric.code fabric, null emblem_font
, wokem.product_id, wokem.sizedefinition_id
, -1 attachment_by
, null embroyderyfilepathproduction, null fontsize, null colorpalette
, null emblemtemplateline_id
from
  workorderlineemblem wokem
          left outer join sizedefinition on  sizedefinition.sizedefinition_id = wokem.sizedefinition_id
          left outer join emblemproduct e
                                --left outer join color_desc txt on e.textcolor_id = txt.color_id
                                --left outer join color_desc 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, workorderline , product p, fabric--, color
, 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
, (select cd.description from color_desc cd where p.color_id = cd.color_id and languages.language_id = cd.language_id) Background
, (select c.description from color_desc c where e.bordercolor_id = c.color_id and languages.language_id = c.language_id) Border
, (select txt.description from color_desc txt where e.textcolor_id = txt.color_id and languages.language_id = txt.language_id) 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
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
  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
, (select cd.description from color_desc cd where emblemtemplateline.bkgcolor_id = cd.color_id and languages.language_id = cd.language_id) Background
, (select c.description from color_desc c where emblemtemplateline.bordercolor_id = c.color_id and languages.language_id = c.language_id) Border
, (select txtd.description from color_desc txtd where emblemtemplateline.textcolor_id = txtd.color_id and languages.language_id = txtd.language_id) 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
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_WORKORDEREMBLEM_SMG
 (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)
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
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
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
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
union all --phase in products
select
 wol.workorder_id, wol.workorderline_id,lan.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 = lan.language_id)
  , etl.description) EmblemDescription
, etl.emblemtype EmblemType,
( select sdte.code from sizedefinition sdte  where sdte.sizedefinition_id=etl.sizedefinition_id) SizeShape, color.code Background
, c.code Border, txt.code Text, -1 Quantity ,
( select ap.code from placement ap where ap.placement_id=etl.placement_id) Placement
, destprod.code PutEmblemOn
, -1 workorderlineemblem_id
, fabric.code fabric, ef.description emblem_font
, etl.product_id, etl.sizedefinition_id
, etl.attachmentby attachment_by
, etl.embroideryfilepathproduction embroyderyfilepathproduction, etl.fontsize, etl.colorpalette
, etl.emblemtemplateline_id emblemtemplateline_id
, etl.description emblemtemplateline_desc
, etl.embroiderylettering embroiderylettering
, etl.embroideryletteringline1 embroideryletteringline1
, etl.embroideryletteringline2 embroideryletteringline2
, etl.embroideryletteringline3 embroideryletteringline3
  from
 workorder wo, workorderline wol, wearerinventory wi, wearerinventory wphasein,emblemtemplate et,emblemtemplateline etl
 left outer join emblemfont ef on etl.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  etl.product_id = e.product_id,
 PhaseOutWearerInventory pco,productconversionsize pcs, productconversion pc,
 product destprod, sizedefinition destsize, qualitygrade qq, languages lan,fabric
 , product p left outer join color  on  p.color_id = color.color_id
where wo.workorder_id=wol.workorder_id
      and  wo.weareremployment_link_id= wi.weareremployment_id
      and wi.wearerinventory_id=pco.phaseoutwearerinventory_id
      and pco.phaseinwearerinventory_id=wphasein.wearerinventory_id
      and wphasein.weareremployment_id=wo.weareremployment_link_id
      and wphasein.product_id=destprod.product_id
      and wphasein.sizedefinition_id=destsize.sizedefinition_id
      and pc.sourceproduct_id=wol.product_link_id
      and wo.customer_link_id=pc.customer_link_id
      and pc.destinationproduct_id=destprod.product_id
      and pc.status=1
      and pc.startdate > wo.neededdate
      and pc.productconversion_id=pcs.productconversion_id
      and wol.sizedefinition_link_id=pcs.sourcesizedefinition_id
      and ((pcs.productconversionsize_id = pco.productconversionsize_id)or pco.Productconversionsize_Id is null)
      and wol.requestedgrade_id=qq.qualitygrade_id
      and wphasein.emblemtemplate_id=et.emblemtemplate_id
      and et.emblemtemplate_id=etl.emblemtemplate_id
      and etl.product_id=p.product_id
      and etl.fabric_id=fabric.fabric_id
 union all
 select
  wol.workorder_id, wol.workorderline_id,lan.code LanguageCode
, et.code EmblemNr
, etl.description EmblemDescription
, etl.emblemtype EmblemType,
( select sdte.code from sizedefinition sdte  where sdte.sizedefinition_id=etl.sizedefinition_id) SizeShape, '' Background
, '' Border, '' Text, -1 Quantity ,
( select ap.code from placement ap where ap.placement_id=etl.placement_id) Placement
, destprod.code PutEmblemOn
, -1 workorderlineemblem_id
, ( select f.code from fabric f where f.fabric_id=etl.fabric_id) fabric
, (select ef.description from emblemfont ef where ef.emblemfont_id=etl.emblemfont_id) emblem_font
, etl.product_id, etl.sizedefinition_id
, etl.attachmentby attachment_by
, etl.embroideryfilepathproduction embroyderyfilepathproduction, etl.fontsize, etl.colorpalette
, etl.emblemtemplateline_id emblemtemplateline_id
, etl.description emblemtemplateline_desc
, etl.embroiderylettering embroiderylettering
, etl.embroideryletteringline1 embroideryletteringline1
, etl.embroideryletteringline2 embroideryletteringline2
, etl.embroideryletteringline3 embroideryletteringline3
  from
 workorder wo, workorderline wol, wearerinventory wi, wearerinventory wphasein,emblemtemplate et,emblemtemplateline etl,
  PhaseOutWearerInventory pco,productconversionsize pcs, productconversion pc,
 product destprod, sizedefinition destsize, qualitygrade qq, languages lan
 where wo.workorder_id=wol.workorder_id
      and  wo.weareremployment_link_id= wi.weareremployment_id
      and wi.wearerinventory_id=pco.phaseoutwearerinventory_id
      and pco.phaseinwearerinventory_id=wphasein.wearerinventory_id
      and wphasein.weareremployment_id=wo.weareremployment_link_id
      and wphasein.product_id=destprod.product_id
      and wphasein.sizedefinition_id=destsize.sizedefinition_id
      and pc.sourceproduct_id=wol.product_link_id
      and wo.customer_link_id=pc.customer_link_id
      and pc.destinationproduct_id=destprod.product_id
      and pc.status=1
      and pc.startdate > wo.neededdate
      and pc.productconversion_id=pcs.productconversion_id
      and wol.sizedefinition_link_id=pcs.sourcesizedefinition_id
      and ((pcs.productconversionsize_id = pco.productconversionsize_id)or pco.Productconversionsize_Id is null)
      and wol.requestedgrade_id=qq.qualitygrade_id
      and wphasein.emblemtemplate_id=et.emblemtemplate_id
      and et.emblemtemplate_id=etl.emblemtemplate_id
      and etl.product_id is null

/
create or replace view V_WORKORDEREMBLEM_VEN
 (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, ROWLOCATION, STOCKROOM_CODE
, STOCKROOM_NAME)
as select /*+index(wokem XAK1WORKORDERLINEEMBLEM)*/
  wokli.workorder_id, wokli.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
, cast ((select case when srl.rowcode is null
then srl.locationcode else srl.rowcode || '#' || srl.locationcode end rowloc
from stockroomlocation srl where srl.stockroomlocation_id =
f_getfirstrowlocationid_ven(wokli.product_link_id,wokli.sizedefinition_link_id,wokli.requestedgrade_id,wokli.codeuniquely, wok.processingstockroom_id))
as varchar2(60)) rowlocation
, stk.code stockroom_code, stk.name stockroom_name
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 wokli
INNER JOIN workorder wok
      LEFT   OUTER JOIN stockroom stk ON stk.stockroom_id = wok.processingstockroom_id
ON wokli.workorder_id = wok.workorder_id
, 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 wokli.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 wokli.product_link_id = product_link.product_link_id
UNION ALL
select /*+index(wokem XAK1WORKORDERLINEEMBLEM)*/
  wokli.workorder_id, wokli.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
, cast ((select case when srl.rowcode is null
then srl.locationcode else srl.rowcode || '#' || srl.locationcode end rowloc
from stockroomlocation srl where srl.stockroomlocation_id =
f_getfirstrowlocationid_ven(wokli.product_link_id,wokli.sizedefinition_link_id,wokli.requestedgrade_id,wokli.codeuniquely, wok.processingstockroom_id))
as varchar2(60)) rowlocation
, stk.code stockroom_code, stk.name stockroom_name
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 wokli
INNER JOIN workorder wok
      LEFT   OUTER JOIN stockroom stk ON stk.stockroom_id = wok.processingstockroom_id
ON wokli.workorder_id = wok.workorder_id
, 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 wokli.product_link_id = product_link.product_link_id
and wokli.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)*/
  wokli.workorder_id, wokli.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
, cast ((select case when srl.rowcode is null
then srl.locationcode else srl.rowcode || '#' || srl.locationcode end rowloc
from stockroomlocation srl where srl.stockroomlocation_id =
f_getfirstrowlocationid_ven(wokli.product_link_id,wokli.sizedefinition_link_id,wokli.requestedgrade_id,wokli.codeuniquely, wok.processingstockroom_id))
as varchar2(60)) rowlocation
, stk.code stockroom_code, stk.name stockroom_name
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 wokli
INNER JOIN workorder wok
      LEFT   OUTER JOIN stockroom stk ON stk.stockroom_id = wok.processingstockroom_id
ON wokli.workorder_id = wok.workorder_id
, 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 wokli.product_link_id = product_link.product_link_id
and wokli.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_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_WORKORDEREMBL_CFC_NAF
 (WORKORDER_ID, WORKORDERLINE_ID, LANGUAGECODE, EMBLEMNR, EMBLEMDESCRIPTION, EMBLEMTYPE, SIZESHAPE, BACKGROUND, BORDER, TEXT, QUANTITY, PLACEMENT, PLACEMENTDESC, PUTEMBLEMON, WORKORDERLINEEMBLEM_ID, FABRIC, EMBLEM_FONT, PRODUCT_ID, SIZEDEFINITION_ID, ATTACHMENT_BY, EMBROYDERYFILEPATHPRODUCTION, FONTSIZE, COLORPALETTE, EMBLEMTEMPLATELINE_ID, EMBLEMTEMPLATELINE_DESC, EMBROIDERYLETTERING, EMBROIDERYLETTERINGLINE1, EMBROIDERYLETTERINGLINE2, EMBROIDERYLETTERINGLINE3, PONUMBER
, ROWLOCATION)
as select /*+index(wokem XAK1WORKORDERLINEEMBLEM)*/
  wokli.workorder_id, wokli.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
, (select pd.description from placement_desc pd
   where pd.placement_id = placement.placement_id and pd.language_id = languages.language_id ) placementdesc
, 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
, cast ((select case when srl.rowcode is null
                then srl.locationcode else srl.rowcode || '#' || srl.locationcode end rowloc
         from stockroomlocation srl where srl.stockroomlocation_id =
         f_getfirstrowlocation_embl_naf(wokem.product_id,wokem.sizedefinition_id, wok.processingstockroom_id))
  as varchar2(60)) rowlocation
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 wokli INNER JOIN workorder wok ON wokli.workorder_id = wok.workorder_id
, product p, fabric
, product_link
 where
     wokem.product_id is not null
and wokem.emblemtemplateline_id is null
and wokli.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 wokli.product_link_id = product_link.product_link_id
UNION ALL
select /*+index(wokem XAK1WORKORDERLINEEMBLEM)*/
  wokli.workorder_id, wokli.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
, (select pd.description from placement_desc pd
   where pd.placement_id = placement.placement_id and pd.language_id = languages.language_id ) placementdesc
, 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
, cast ((select case when srl.rowcode is null
                then srl.locationcode else srl.rowcode || '#' || srl.locationcode end rowloc
         from stockroomlocation srl where srl.stockroomlocation_id =
         f_getfirstrowlocation_embl_naf(emblemtemplateline.product_id, emblemtemplateline.sizedefinition_id, wok.processingstockroom_id))
  as varchar2(60)) rowlocation
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 wokli INNER JOIN workorder wok ON wokli.workorder_id = wok.workorder_id
, fabric
, product_link
, 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 wokli.product_link_id = product_link.product_link_id
and wokli.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)*/
  wokli.workorder_id, wokli.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
, (select pd.description from placement_desc pd
   where pd.placement_id = placement.placement_id and pd.language_id = languages.language_id ) placementdesc
, 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,
         ' ' rowlocation
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 wokli INNER JOIN workorder wok ON wokli.workorder_id = wok.workorder_id
, fabric
, product_link
, emblemtemplate, sizedefinition, languages
where
    wokem.emblemtemplateline_id is not null
and wokem.product_id is null
and emblemtemplateline.product_id is null
and wokli.product_link_id = product_link.product_link_id
and wokli.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, 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
, 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
, lan.code languagecode, lan.language_id
from workorder wo, workorderline wol, workorderstocktransaction wost,  languages lan
where wo.workorder_id=wol.workorder_id
      and wol.workorderline_id=wost.workorderline_id
      and wo.origin in (8,9)
group by wo.workorder_id, wol.workorderline_id, trunc(wost.timestamp), wol.product_link_id, wol.sizedefinition_link_id, lan.language_id, lan.code

/
create or replace view V_WORKORDERLINE_AMM
 (WORKORDERLINE_ID, WORKORDER_ID, PRODNR, PRODDESCRIPTION, PRODLONGDESCRIPTION, FINMETHCODE, SIZECODE, UNIQUEYN, QUALITYGRADE, QUANTITYORDERED, QUANTITYCANCELLED, QUANTITYPICKED, QORDER, QDONE, QOPEN, MODIFICATIONGROUPCODE, MODIFICATIONCODE, MODIFICATIONDESC, INSTRUCTIONS, LANGUAGECODE, QUALITYGRADE_CODE, PURCHASEORDERHEADER_ID, PICKINGSEQUENCE)
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.quantitypicked
, ( 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
, (select pol.purchaseorderheader_id from purchaseorderline pol
where wokli.purchaseorderline_id = pol.purchaseorderline_id
or pol.purchaseorderline_id in (select wolpol.purchaseorderline_id from workorderlinepurchordline wolpol where wolpol.workorderline_id=wokli.workorderline_id)) purchaseorderheader_id
, (select min(sl.pickingsequence) from workorderlinereservation wor, stockquantity sq, stockroomlocation sl
where wor.workorderline_id = wokli.workorderline_id and wor.stockreservationpergrade_id = sq.stockreservationpergrade_id
      and sq.stockroomlocation_id = sl.stockroomlocation_id ) pickingsequence
from
  workorderline wokli
    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_link prdlk on wokli.product_link_id = prdlk.product_link_id
    left outer join ( workorderlinemodification
                 join modification
                 on workorderlinemodification.modification_id = modification.modification_id )
        on wokli.workorderline_id = workorderlinemodification.workorderline_id
, languages

/
create or replace view V_WORKORDERLINE_ANG
 (WORKORDERLINE_ID, WORKORDER_ID, PRODNR, PRODDESCRIPTION, PRODLONGDESCRIPTION, FINMETHCODE, SIZECODE, UNIQUEYN, QUALITYGRADE, QUANTITYORDERED, QUANTITYCANCELLED, QORDER, QDONE, QOPEN, MODIFICATIONGROUPCODE, MODIFICATIONCODE, MODIFICATIONDESC, INSTRUCTIONS, LANGUAGECODE, SALESEMPLOYEE1NUMBER, SALESEMPLOYEE1NAME, SALESEMPLOYEE2NUMBER, SALESEMPLOYEE2NAME, QUALITYGRADE_CODE, REASONCODE_ID, RENTALQTYADJUSTMENT_ID, SIZEDESC)
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,
       e.employeenumber salesemployee1number,
       e.NAME salesemployee1name,
       ee.employeenumber salesemployee2number,
       ee.NAME salesemployee2name,
       qualitygrade.code qualitygrade_code,
			 wokli.reasoncode_id, wokli.rentalqtyadjustment_id,
       (SELECT sdld.description
        FROM   sizedefinition_link_desc sdld
        WHERE  wokli.sizedefinition_link_id = sdld.sizedefinition_link_id
               AND sdld.language_id = languages.language_id) SizeDesc
FROM   workorderline wokli
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_link prdlk ON wokli.product_link_id = prdlk.product_link_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 employee e ON wokli.salesemployee1_id = e.employee_id
LEFT   OUTER JOIN employee ee ON wokli.salesemployee2_id = e.employee_id
 , languages

/
create or replace view V_WORKORDERLINE_AUJ
 (WORKORDERLINE_ID, WORKORDER_ID, PRODNR, PRODRANKING, PRODDESCRIPTION, FINMETHCODE, FM_DESC, SIZECODE, UNIQUEYN, REQUESTQUALGRADECODE, REQUESTQUALGRADEDESC, QUANTITYORDERED, QUANTITYCANCELLED, QORDER, RESERVEDQTY, RESERVEDNEWGARM, QDONE, QOPEN, LANGUAGECODE, RESERVEDSIZECODE, ROWCODE, LOCATIONCODE, WI_REMARK, WI_MODIF1, WI_MODIF2, WI_MODIF3, TOTSTOCKQTY)
as select wokli.workorderline_id,
       wokli.workorder_id,
       prdlk.code prodnr,
       (select pr.ranking
        from product p, productranking pr
        where p.product_id = prdlk.product_id
              and p.productranking_id=pr.productranking_id) prodranking,
       (select product_desc.description
          from product_desc
         where prdlk.product_id = product_desc.product_id
           and product_desc.language_id = languages.language_id) proddescription,
       finishingmethod.code finmethcode,
       (select fd.description from finishingmethod_desc fd where fd.finishingmethod_id = finishingmethod.finishingmethod_id and fd.language_id = languages.language_id) fm_desc,
       szlk.code sizecode,
       wokli.codeuniquely uniqueyn,
       reqg.code requestqualgradecode,
       (select qualitygrade_desc.description
          from qualitygrade_desc
         where qualitygrade_desc.qualitygrade_id =
               reqg.qualitygrade_id
           and qualitygrade_desc.language_id = languages.language_id) requestqualgradedesc,
       wokli.quantityordered,
       wokli.quantitycancelled,
       (wokli.quantityordered - wokli.quantitycancelled) qorder,
       sum(wolr.quantity) reservedqty,
       (select resqg.newgarment
        from qualitygrade resqg
        where srg.qualitygrade_id=resqg.qualitygrade_id) reservednewgarm,
       wokli.quantityfilled qdone,
       (wokli.quantityordered - wokli.quantityfilled - wokli.quantitycancelled) qopen,
       languages.code languagecode,
       (select sd.code from stockdefinitionperitem sdi, sizedefinition sd
        where sdi.stockdefinitionperitem_id=srg.stockdefinitionperitem_id and sdi.sizedefinition_id = sd.sizedefinition_id) reservedsizecode,
       F_GETROWLOCATION(srg.stockreservationpergrade_id, wokli.codeuniquely) rowcode,
       F_GETLOCATIONCODE(srg.stockreservationpergrade_id, wokli.codeuniquely) locationcode
       , wokli.instructions  wi_remark--added for instruction select ssb 01-02-12
       , coalesce((select md.description
          from wearerinventory wi, workorder wo, wearerinventorymodification wim, modification m, modification_desc md
          where wi.weareremployment_id = wo.weareremployment_link_id
                and wo.workorder_id = wokli.workorder_id
                and wi.product_id = prdlk.product_id
                and wi.sizedefinition_id = szlk.sizedefinition_link_id
                and wi.finishingmethod_id = finishingmethod.finishingmethod_id
                and wim.wearerinventory_id = wi.wearerinventory_id
                and wim.sequencenumber = 1
                and m.modification_id = wim.modification_id
                and m.modification_id = md.modification_id
                and md.language_id = languages.language_id),
                (select md.description
                from modification_desc md, workorderlinemodification wlm
                where wlm.workorderline_id = wokli.workorderline_id
                and wlm.sequencenumber = 1
                and md.modification_id = wlm.modification_id
                and md.language_id = languages.language_id)) wi_modif1
       , coalesce((select md.description
          from wearerinventory wi, workorder wo, wearerinventorymodification wim, modification m, modification_desc md
          where wi.weareremployment_id = wo.weareremployment_link_id
                and wo.workorder_id = wokli.workorder_id
                and wi.product_id = prdlk.product_id
                and wi.sizedefinition_id = szlk.sizedefinition_link_id
                and wi.finishingmethod_id = finishingmethod.finishingmethod_id
                and wim.wearerinventory_id = wi.wearerinventory_id
                and wim.sequencenumber = 2
                and m.modification_id = wim.modification_id
                and m.modification_id = md.modification_id
                and md.language_id = languages.language_id),
                (select md.description
                from modification_desc md, workorderlinemodification wlm
                where wlm.workorderline_id = wokli.workorderline_id
                and wlm.sequencenumber = 2
                and md.modification_id = wlm.modification_id
                and md.language_id = languages.language_id)) wi_modif2
       , coalesce((select md.description
          from wearerinventory wi, workorder wo, wearerinventorymodification wim, modification m, modification_desc md
          where wi.weareremployment_id = wo.weareremployment_link_id
                and wo.workorder_id = wokli.workorder_id
                and wi.product_id = prdlk.product_id
                and wi.sizedefinition_id = szlk.sizedefinition_link_id
                and wi.finishingmethod_id = finishingmethod.finishingmethod_id
                and wim.wearerinventory_id = wi.wearerinventory_id
                and wim.sequencenumber = 3
                and m.modification_id = wim.modification_id
                and m.modification_id = md.modification_id
                and md.language_id = languages.language_id),
                (select md.description
                from modification_desc md, workorderlinemodification wlm
                where wlm.workorderline_id = wokli.workorderline_id
                and wlm.sequencenumber = 3
                and md.modification_id = wlm.modification_id
                and md.language_id = languages.language_id)) wi_modif3
        ,  (select sum(sq.qtyunique+sq.qtynonunique) from stockquantity sq, stockroomlocation sl
        where sl.stockroomlocation_id = sq.stockroomlocation_id and sl.locationtype_id <> 11
              and sq.stockreservationpergrade_id = srg.stockreservationpergrade_id ) totstockqty
from workorderline wokli
       left outer join qualitygrade reqg on wokli.requestedgrade_id = reqg.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_link prdlk on wokli.product_link_id = prdlk.product_link_id
       left outer join (workorderlinereservation wolr
                          join stockreservationpergrade srg
                               on wolr.stockreservationpergrade_id = srg.stockreservationpergrade_id)
            on wokli.workorderline_id = wolr.workorderline_id
       , languages
group by wokli.workorder_id, wokli.workorderline_id, wolr.stockreservationpergrade_id, srg.stockreservationpergrade_id, srg.stockdefinitionperitem_id, prdlk.code, prdlk.product_id,
        finishingmethod.code, finishingmethod.finishingmethod_id, szlk.code, reqg.code, reqg.qualitygrade_id,
        wokli.quantityordered, wokli.quantitycancelled,srg.qualitygrade_id,wokli.quantityfilled,
        wokli.codeuniquely, languages.code, languages.language_id, szlk.sizedefinition_link_id
        ,wokli.instructions

/
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_WORKORDERLINE_CFC_NAF
 (WORKORDERLINE_ID, WORKORDER_ID, PRODNR, PRODDESCRIPTION, PRODLONGDESCRIPTION, FINMETHCODE, SIZECODE, UNIQUEYN, QUALITYGRADE, QUANTITYORDERED, QUANTITYCANCELLED, QORDER, QDONE, QOPEN, 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 LISTAGG(modification_desc.description,  ';'||chr(10) ) WITHIN GROUP (ORDER BY modification_desc.description)
        FROM   modification_desc, modification, workorderlinemodification wolm
        WHERE  modification_desc.modification_id =
               modification.modification_id
               and wolm.modification_id = modification.modification_id
               and wolm.workorderline_id = wokli.workorderline_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 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_WORKORDERLINE_CUS
 (WORKORDERLINE_ID, WORKORDER_ID, PRODNR, PRODDESCRIPTION, PRODLONGDESCRIPTION, FINMETHCODE, SIZECODE, SIZEDESCRIPTION, UNIQUEYN, QUALITYGRADE, QUANTITYORDERED, QUANTITYCANCELLED, QORDER, QDONE, QOPEN, PURCHASEORDERLINE_ID, QTYPURCHASED, PURCHASESIZEDESC, QTYRECEIVED, MODIFICATIONGROUPCODE, MODIFICATIONCODE, MODIFICATIONDESC, INSTRUCTIONS, LANGUAGECODE, SALESEMPLOYEE1NUMBER, SALESEMPLOYEE1NAME, SALESEMPLOYEE2NUMBER, SALESEMPLOYEE2NAME, QUALITYGRADE_CODE, REASONCODE_ID, RENTALQTYADJUSTMENT_ID
, EXECUTEDBY)
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,
       (SELECT sizedefinition_desc.description
        FROM   sizedefinition_desc
        WHERE  szlk.sizedefinition_id = sizedefinition_desc.sizedefinition_id
               AND sizedefinition_desc.language_id = languages.language_id) SizeDescription,
       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,
       wokli.purchaseorderline_id,
       (select pol.quantityordered - pol.quantitycancelled
        from purchaseorderline pol
        where pol.purchaseorderline_id = wokli.purchaseorderline_id) qtyPurchased,
       (SELECT sizedefinition_desc.description
        FROM   sizedefinition_desc, purchaseorderline pol
        WHERE  pol.purchaseorderline_id = wokli.purchaseorderline_id
               and pol.sizedefinition_link_id = sizedefinition_desc.sizedefinition_id
               AND sizedefinition_desc.language_id = languages.language_id) purchaseSizeDesc,
       (select pol.quantityreceived
        from purchaseorderline pol
        where pol.purchaseorderline_id = wokli.purchaseorderline_id) qtyReceived,
       (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,
       e.employeenumber salesemployee1number,
       e.NAME salesemployee1name,
       ee.employeenumber salesemployee2number,
       ee.NAME salesemployee2name,
       qualitygrade.code qualitygrade_code,
       wokli.reasoncode_id, wokli.rentalqtyadjustment_id, wokli.executedby
FROM   workorderline wokli
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_link prdlk ON wokli.product_link_id = prdlk.product_link_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 employee e ON wokli.salesemployee1_id = e.employee_id
LEFT   OUTER JOIN employee ee ON wokli.salesemployee2_id = e.employee_id
 , languages

/
create or replace view V_WORKORDERLINE_NAF
 (WORKORDERLINE_ID, WORKORDER_ID, PRODNR, PRODDESCRIPTION, PRODLONGDESCRIPTION, COLORDESC, FINMETHCODE, FINMETHDESC, SIZECODE, SIZEDESC, UNIQUEYN, QUALITYGRADE, QUANTITYORDERED, QUANTITYCANCELLED, QORDER, QDONE, QOPEN, MODIFICATIONGROUPCODE, MODIFICATIONCODE, MODIFICATIONDESC, INSTRUCTIONS, LANGUAGECODE, QUALITYGRADE_CODE, STOCKTRANSDATE, STOCKTRANSQTY, MAXSTOCKTRANSDATE)
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
, (select cold.description from color_desc cold where cold.color_id = p.color_id and cold.language_id = languages.language_id) COLORDESC
, finishingmethod.code FinMethCode
, (select fmd.description from finishingmethod_desc fmd
                                           where fmd.finishingmethod_id = wokli.finishingmethod_id
                                           and   fmd.language_id = languages.language_id) FinMethDesc
, szlk.code SizeCode, (select szlkd.description from sizedefinition_link_desc szlkd
                       where szlkd.sizedefinition_link_id = wokli.sizedefinition_link_id
                       and szlkd.language_id = languages.language_id) SizeDesc
, 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
, TO_CHAR(st.transactiondate, 'dd.mm.yyyy') stocktransdate, st.quantity stocktransqty
, (case when wo.processingstockroom_id = 141 then
  (select TO_NUMBER(TO_CHAR(max(st2.transactiondate),'yyyymmdd')) from stocktransaction st2
   where wostt.stocktransaction_id = st2.stocktransaction_id)
  else 20991231 end) MAXSTOCKTRANSDATE
from
  workorderline wokli
    inner join workorder wo on (wokli.workorder_id = wo.workorder_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_link prdlk
         inner join product p on (prdlk.product_id = p.product_id)
    on wokli.product_link_id = prdlk.product_link_id
    left outer join workorderstocktransaction wostt
         left outer join stocktransaction st on (st.stocktransaction_id = wostt.stocktransaction_id)
    on (wokli.workorderline_id = wostt.workorderline_id)
    left outer join ( workorderlinemodification
                 join modification
                 on workorderlinemodification.modification_id = modification.modification_id )
        on wokli.workorderline_id = workorderlinemodification.workorderline_id
, languages

/
create or replace view V_WORKORDERLINE_NIW
 (WORKORDERLINE_ID, WORKORDER_ID, PRODNR, PRODDESCRIPTION, PRODLONGDESCRIPTION, FINMETHCODE, SIZECODE, UNIQUEYN, QUALITYGRADE, QUANTITYORDERED, QUANTITYCANCELLED, QORDER, QDONE, QOPEN, MODIFICATIONGROUPCODE, MODIFICATIONCODE, MODIFICATIONDESC, INSTRUCTIONS, LANGUAGECODE, SALESEMPLOYEE1NUMBER, SALESEMPLOYEE1NAME, SALESEMPLOYEE2NUMBER, SALESEMPLOYEE2NAME, QUALITYGRADE_CODE, EMBLEMTEMPLATE_ID, NEWROWLOCATION, USEDROWLOCATION, NEWQOH, USEDQOH)
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,
    e.employeenumber salesemployee1number,
    e.NAME salesemployee1name,
    ee.employeenumber salesemployee2number,
    ee.NAME salesemployee2name,
    qualitygrade.code qualitygrade_code,
    wokli.emblemtemplate_id ,
    (SELECT MIN(CONCATENATE3(rpad(l.rowcode, 3), '-', rpad(l.locationcode, 3)))
    FROM standardlocationperproduct v,
      product p,
      stockroomlocation l,
      standardlocationpersize ls,
      sizedefinition sd
    WHERE v.product_id                   = p.product_id
    AND v.stockroomlocation_id           = l.stockroomlocation_id
    AND ls.standardlocationperproduct_id = v.standardlocationperproduct_id
    AND ls.sizedefinition_id             = sd.sizedefinition_id
    AND p.code                           = prdlk.code
    AND sd.code                          = szlk.code
    AND v.allowedgrade                   = 'N'
    ) NewRowLocation,
    (SELECT MIN(CONCATENATE3(rpad(l.rowcode, 3), '-', rpad(l.locationcode, 3)))
    FROM standardlocationperproduct v,
      product p,
      stockroomlocation l,
      standardlocationpersize ls,
      sizedefinition sd
    WHERE v.product_id                   = p.product_id
    AND v.stockroomlocation_id           = l.stockroomlocation_id
    AND ls.standardlocationperproduct_id = v.standardlocationperproduct_id
    AND ls.sizedefinition_id             = sd.sizedefinition_id
    AND p.code                           = prdlk.code
    AND sd.code                          = szlk.code
    AND v.allowedgrade                   = 'U'
    ) UsedRowLocation,
    (select sum((skq.QtyUnique + skq.qtyuniquewithmodifications
- skresg.QtyNonUniqueReserved - skresg.QtyUniqueReserved - skresg.qtyuniquewiithmodifreserved))
  from stockroom sk, STOCKroomLOCATION skl, stockdefinitionperitem ski
 , stockreservationpergrade skresg, stockquantity skq, qualitygrade qg
 where sk.stockroom_id = skl.stockroom_id and
     sk.stockroom_id = ski.stockroom_id
    and ski.product_id = prdlk.product_id
    and ski.sizedefinition_id = szlk.sizedefinition_id
    and ski.stockdefinitionperitem_id = skresg.stockdefinitionperitem_id and skresg.qualitygrade_id=qg.qualitygrade_id
    and skresg.stockreservationpergrade_id = skq.stockreservationpergrade_id and skl.stockroomlocation_id = skq.stockroomlocation_id
    and qg.code ='N' and skl.pickingsequence <> 0) NewQOH,
    (select sum((skq.QtyNonUnique + skq.QtyUnique + skq.qtyuniquewithmodifications
- skresg.QtyNonUniqueReserved - skresg.QtyUniqueReserved - skresg.qtyuniquewiithmodifreserved))
  from stockroom sk, STOCKroomLOCATION skl, stockdefinitionperitem ski
 , stockreservationpergrade skresg, stockquantity skq, qualitygrade qg
 where sk.stockroom_id = skl.stockroom_id and
     sk.stockroom_id = ski.stockroom_id
    and ski.product_id = prdlk.product_id
    and ski.sizedefinition_id = szlk.sizedefinition_id
    and ski.stockdefinitionperitem_id = skresg.stockdefinitionperitem_id and skresg.qualitygrade_id=qg.qualitygrade_id
    and skresg.stockreservationpergrade_id = skq.stockreservationpergrade_id and skl.stockroomlocation_id = skq.stockroomlocation_id
    and qg.code ='U' and skl.pickingsequence <> 0) UsedQOH
  FROM workorderline wokli
  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_link prdlk ON wokli.product_link_id = prdlk.product_link_id
  LEFT OUTER JOIN ( workorderlinemodification
       JOIN modification ON workorderlinemodification.modification_id = modification.modification_id)
  ON wokli.workorderline_id = workorderlinemodification.workorderline_id
  LEFT OUTER JOIN employee e ON wokli.salesemployee1_id = e.employee_id
  LEFT OUTER JOIN employee ee ON wokli.salesemployee2_id = e.employee_id ,
    languages

/
create or replace view V_WORKORDERLINE_POS
 (WORKORDERLINE_ID, WORKORDER_ID, PRODNR, PRODDESCRIPTION, PRODLONGDESCRIPTION, FINMETHCODE, SIZECODE, UNIQUEYN, QUALITYGRADE, QUANTITYORDERED, QUANTITYCANCELLED, QORDER, QDONE, QOPEN, MODIFICATIONGROUPCODE, MODIFICATIONCODE, MODIFICATIONDESC, INSTRUCTIONS, LANGUAGECODE, SALESEMPLOYEE1NUMBER, SALESEMPLOYEE1NAME, SALESEMPLOYEE2NUMBER, SALESEMPLOYEE2NAME, QUALITYGRADE_CODE, REASONCODE_ID, RENTALQTYADJUSTMENT_ID, SUPPLIERPRODUCTCODE, SUPPLIERNUMBER)
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,
       e.employeenumber salesemployee1number,
       e.NAME salesemployee1name,
       ee.employeenumber salesemployee2number,
       ee.NAME salesemployee2name,
       qualitygrade.code qualitygrade_code,
       wokli.reasoncode_id, wokli.rentalqtyadjustment_id,
       (select sp.supplierproductcode from supplierproduct sp where sp.supplierproduct_id=(select max(a.supplierproduct_id) from supplierproduct a,productsizepersupproduct b
               where a.supplier_id=sdi.defaultsupplier_id  and a.supplierproduct_id=b.supplierproduct_id
               and b.product_id=wokli.product_link_id  and b.sizedefinition_id=wokli.sizedefinition_link_id ))supplierproductcode,
       sup.suppliernumber
FROM   workorderline wokli join workorder wo on wo.workorder_id = wokli.workorder_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_link prdlk ON wokli.product_link_id = prdlk.product_link_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 employee e ON wokli.salesemployee1_id = e.employee_id
LEFT   OUTER JOIN employee ee ON wokli.salesemployee2_id = e.employee_id
left outer join stockdefinitionperitem sdi on ( wokli.product_link_id=sdi.product_id
and wokli.sizedefinition_link_id=sdi.sizedefinition_id and wo.processingstockroom_id = sdi.stockroom_id and SDI.CustomerOwned = 'N' and SDI.Customer_ID is null)
left outer join supplier sup on sdi.defaultsupplier_id=sup.supplier_id
 , languages

/
create or replace view V_WORKORDERLINE_SMG
 (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, OOSPRODUCT, DESTPRODCODE, PRODDESC, FMCODE, DESTSIZECODE, QCODE, QUANTITYPHASEIN, OOSPHASEINPRODUCT)
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 - wokli.quantityphasein 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,
       (select coalesce( oosp.status,0)
                from workorder wo,  stockdefinitionperitem sdi,stockreservationpergrade srg
                left outer join outofserviceproduct oosp on srg.stockreservationpergrade_id=oosp.stockreservationpergrade_id
                where wo.workorder_id=wokli.workorder_id
                and srg.stockdefinitionperitem_id=sdi.stockdefinitionperitem_id
                and sdi.stockroom_id=wo.processingstockroom_id
                and sdi.product_id=wokli.product_link_id
                and sdi.customer_id is null
                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,
       (select destprod.code from product destprod where destprod.product_id=x.phaseinprod_id ) destprodcode,
       ( select pd.description from product_desc pd where pd.product_id=x.phaseinprod_id and pd.language_id=languages.language_id )  proddesc,
       ( select fm.code from finishingmethod fm where fm.finishingmethod_id=x.wphinfmid)fmcode,
       x.destsizecode,x.qcode, x.quantityphasein, x.OOSPhaseinProduct
FROM  workorderline wokli
left outer join (select  wol.workorderline_id, wphasein.product_id phaseinprod_id,wphasein.finishingmethod_id wphinfmid,
               destsize.code destsizecode,qq.code qcode,wol.quantityphasein,
               (select coalesce( oosp.status,0)
                from  stockdefinitionperitem sdi,stockreservationpergrade srg
                left outer join outofserviceproduct oosp on srg.stockreservationpergrade_id=oosp.stockreservationpergrade_id
                where  srg.stockdefinitionperitem_id=sdi.stockdefinitionperitem_id
                and sdi.stockroom_id=wo.processingstockroom_id
                and sdi.product_id=wphasein.product_id
                and sdi.sizedefinition_id=wphasein.sizedefinition_id
               and srg.qualitygrade_id=qq.qualitygrade_id
                and (oosp.sequencenumber is null or oosp.sequencenumber=( select max(oosp1.sequencenumber) from outofserviceproduct oosp1
                where oosp1.stockreservationpergrade_id=srg.stockreservationpergrade_id)))OOSPhaseinProduct
              from  workorder wo,workorderline wol, wearerinventory wi, wearerinventory wphasein,
                PhaseOutWearerInventory pco, productconversion pc,
                sizedefinition destsize, qualitygrade qq
              where wo.workorder_id=wol.workorder_id
                    and wo.weareremployment_link_id= wi.weareremployment_id
                    and wi.wearerinventory_id=pco.phaseoutwearerinventory_id
                    and pco.phaseinwearerinventory_id=wphasein.wearerinventory_id
                    and wo.weareremployment_link_id=wphasein.weareremployment_id
                    and wphasein.product_id=pc.destinationproduct_id
                    and wphasein.sizedefinition_id=destsize.sizedefinition_id
                    and wol.requestedgrade_id=qq.qualitygrade_id
                    and pc.sourceproduct_id=wol.product_link_id
                    and wi.product_id = pc.sourceproduct_id
                    and wi.sizedefinition_id=wol.sizedefinition_link_id
                    and wi.product_id=wol.product_link_id
                    and wo.customer_link_id=pc.customer_link_id
                    and pc.status=1) x on wokli.workorderline_id=x.workorderline_id --and x.lancode=languages.code
LEFT   OUTER JOIN(workorderlinemodification
      INNER JOIN   modification ON workorderlinemodification.modification_id = modification.modification_id)
ON wokli.workorderline_id = workorderlinemodification.workorderline_id
, qualitygrade , finishingmethod,sizedefinition_link szlk, product_link prdlk ,languages
WHERE wokli.requestedgrade_id = qualitygrade.qualitygrade_id
and wokli.finishingmethod_id = finishingmethod.finishingmethod_id
      and wokli.sizedefinition_link_id = szlk.sizedefinition_link_id
      and wokli.product_link_id = prdlk.product_link_id

/
create or replace view V_WORKORDERLINE_VEN
 (WORKORDERLINE_ID, WORKORDER_ID, PRODNR, PRODDESCRIPTION, PRODLONGDESCRIPTION, FINMETHCODE, SIZECODE, UNIQUEYN, QUALITYGRADE, QUANTITYORDERED, QUANTITYCANCELLED, QORDER, QDONE, QOPEN, MODIFICATIONGROUPCODE, MODIFICATIONCODE, MODIFICATIONDESC, INSTRUCTIONS, LANGUAGECODE, SALESEMPLOYEE1NUMBER, SALESEMPLOYEE1NAME, SALESEMPLOYEE2NUMBER, SALESEMPLOYEE2NAME, QUALITYGRADE_CODE, REASONCODE_ID, RENTALQTYADJUSTMENT_ID, EXECUTEDBY, ROWLOCATION, STOCKROOM_CODE, STOCKROOM_NAME)
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,
       e.employeenumber salesemployee1number,
       e.NAME salesemployee1name,
       ee.employeenumber salesemployee2number,
       ee.NAME salesemployee2name,
       qualitygrade.code qualitygrade_code,
       wokli.reasoncode_id, wokli.rentalqtyadjustment_id, wokli.executedby
, cast ((select case when srl.rowcode is null
then srl.locationcode else srl.rowcode || '#' || srl.locationcode end rowloc
from stockroomlocation srl where srl.stockroomlocation_id =
f_getfirstrowlocationid_ven(wokli.product_link_id,wokli.sizedefinition_link_id,wokli.requestedgrade_id,wokli.codeuniquely, wok.processingstockroom_id))
as varchar2(60)) rowlocation
, stk.code stockroom_code, stk.name stockroom_name
FROM   workorderline wokli
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_link prdlk ON wokli.product_link_id = prdlk.product_link_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 employee e ON wokli.salesemployee1_id = e.employee_id
LEFT   OUTER JOIN employee ee ON wokli.salesemployee2_id = e.employee_id
INNER JOIN workorder wok
      LEFT   OUTER JOIN stockroom stk ON stk.stockroom_id = wok.processingstockroom_id
ON wokli.workorder_id = wok.workorder_id
 , languages

/
create or replace view V_WORKORDERPERPURCHASEORDER
 (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
--, (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sd.sizedefinition_id and sdd.language_id = lan.language_id) SizeDesc
, poh.purchaseordernumber, wol.quantityordered WOLOrdered, pol.quantityordered POLOrdered
, su.suppliernumber, su.name SuppName
, lan.code Lan_code
FROM workorder wo, workorderline wol, weareremployment we, wearer w, customer cu
, product prd, sizedefinition sd--, finishingmethod fm
, purchaseorderline pol, purchaseorderheader poh
, productsizepersupproduct ps, supplierproduct sp, 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.product_link_id = prd.product_id and wol.sizedefinition_link_id = sd.sizedefinition_id --and wol.finishingmethod_id = fm.finishingmethod_id
and wol.purchaseorderline_id = pol.purchaseorderline_id and pol.purchaseorderheader_id = poh.purchaseorderheader_id
and ps.product_id = wol.product_link_id and ps.sizedefinition_id = wol.sizedefinition_link_id
and sp.supplierproduct_id = ps.supplierproduct_id and sp.supplier_id = su.supplier_id

/
create or replace view V_WORKORDERPICKED
 (WORKORDERLINE_ID, WORKORDER_ID, PRODCODE, PRODDESC, SIZECODE, FMCODE, CODEUNIQUELY, PICKERGRADE, ORDEREDGRADE, QUANTITYORDERED, QUANTITYFILLED, QUANTITYCANCELLED, QOPEN, OOSPRODUCT, PICKLISTLINE_ID, STOCKTYPE, QTYPICKED, INSTRUCTIONS, LANGUAGE_CODE)
as select wokli.workorderline_id, wokli.workorder_id,p.code prodcode,
(select pd.description from   product_desc pd
         where  p.product_id = pd.product_id and pd.language_id = lan.language_id) proddesc,
sd.code sizecode, fm.code fmcode,
wokli.codeuniquely codeuniquely,
(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,
wokli.quantityordered quantityordered, wokli.quantityfilled quantityfilled,  wokli.quantitycancelled,
( wokli.quantityordered-wokli.quantityfilled-wokli.quantitycancelled) qOpen,
(select coalesce( oosp.status,0)
                from workorder wo,  stockdefinitionperitem sdi, outofserviceproduct oosp
                where wo.workorder_id=wokli.workorder_id
                and sdi.stockdefinitionperitem_id=srg.stockdefinitionperitem_id
                and sdi.stockroom_id=wo.processingstockroom_id
                and sdi.product_id=wokli.product_link_id
                and sdi.sizedefinition_id=wokli.sizedefinition_link_id
                and srg.stockreservationpergrade_id=oosp.stockreservationpergrade_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,
plo.picklistline_id, pl.stocktype,  plo.qtypicked,wokli.instructions, lan.code Language_code
from workorderline wokli
left outer join picklistlineorigin plo on plo.baselinetable_link_id=wokli.workorderline_id and plo.baselinetable='WORKORDERLINE'
and plo.baselinetype in (8,9)
left outer join picklistline pl on plo.picklistline_id=pl.picklistline_id
left outer join stockreservationpergrade srg on pl.stockreservationpergrade_id=srg.stockreservationpergrade_id
left outer join  qualitygrade qg on srg.qualitygrade_id=qg.qualitygrade_id,
product p, sizedefinition sd, finishingmethod fm, qualitygrade qOrdered,languages lan
where  wokli.product_link_id=p.product_id
and wokli.sizedefinition_link_id=sd.sizedefinition_id
and wokli.finishingmethod_id=fm.finishingmethod_id
and wokli.requestedgrade_id=qOrdered.Qualitygrade_Id

/
create or replace view V_WORKORDERPICKED_TEK
 (WORKORDERLINE_ID, WORKORDER_ID, PRODCODE, PRODDESC, SIZECODE, FMCODE, CODEUNIQUELY, PICKERGRADE, ORDEREDGRADE, QUANTITYORDERED, QUANTITYFILLED, QUANTITYCANCELLED, QOPEN, PICKLISTLINE_ID, STOCKTYPE, QTYPICKED, INSTRUCTIONS, LANGUAGE_CODE, LONGPRODDESC)
as select wokli.workorderline_id
,      wokli.workorder_id
,      p.code prodcode
,      ( select pd.description
         from   product_desc pd
         where  p.product_id = pd.product_id and pd.language_id = lan.language_id) proddesc
,      sd.code sizecode
,      fm.code fmcode
,      wokli.codeuniquely codeuniquely
,      ( 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
,      wokli.quantityordered quantityordered
,      wokli.quantityfilled quantityfilled
,       wokli.quantitycancelled
,      (wokli.quantityordered-wokli.quantityfilled-wokli.quantitycancelled) qOpen
,      plo.picklistline_id
,      pl.stocktype
,      plo.qtypicked
,      wokli.instructions
,      lan.code Language_code
,      ( select pd.longdescription
         from   product_desc pd
         where  p.product_id = pd.product_id and pd.language_id = lan.language_id) longproddesc
from   workorderline wokli
          left outer join picklistlineorigin plo on plo.baselinetable_link_id=wokli.workorderline_id
                                                and plo.baselinetable='WORKORDERLINE'
                                                and plo.baselinetype in (8,9)
          left outer join picklistline pl on plo.picklistline_id=pl.picklistline_id
          left outer join stockreservationpergrade srg on pl.stockreservationpergrade_id=srg.stockreservationpergrade_id
          left outer join qualitygrade qg on srg.qualitygrade_id=qg.qualitygrade_id
,      product p
,      sizedefinition sd
,      finishingmethod fm
,      qualitygrade qOrdered
,      languages lan
where  wokli.product_link_id=p.product_id
   and wokli.sizedefinition_link_id=sd.sizedefinition_id
   and wokli.finishingmethod_id=fm.finishingmethod_id
   and wokli.requestedgrade_id=qOrdered.Qualitygrade_Id

/
create or replace view V_WORKORDERPLPC_NAF
 (WORKORDERLINE_ID, WORKORDER_ID, SUPPLIERNUMBER, SUPLIERNAME, LOGOFILEPATHORIGINAL, LOGOFILEPATHPRODUCTION, BACKING, BORDERWIDTH, BORDERMATERIAL, THICKNESS, ACTUALWIDTH, ACTUALLENGTH, SHAPE, DIRECTION, MATCOLORTYPE, SEQUENCENUMBER, BG_CODE, BG_DESC, LOGO_CODE, LOGO_DESC, LANGUAGE_CODE)
as select 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
, (select c.code from color c where c.color_id=mc.color_id and mc.matcolortype=2) Bg_code
, (select cd.description from color c, color_desc cd where c.color_id=mc.color_id and mc.matcolortype=2 and cd.color_id=c.color_id and cd.language_id=lan.language_id) Bg_desc
, (select c.code from color c where c.color_id=mc.color_id and mc.matcolortype=1) Logo_code
, (select cd.description from color c, color_desc cd where c.color_id=mc.color_id and mc.matcolortype=1 and cd.color_id=c.color_id and cd.language_id=lan.language_id) Logo_desc
, lan.code Language_code
from workorderline wokli, workorder wo, productlistpercustomer plpc
left outer join matcolor mc on mc.productlistpercustomer_id=plpc.productlistpercustomer_id
, matorderinginfo moi, supplier sup, languages lan
where wokli.workorder_id=wo.workorder_id
and wo.customer_link_id=plpc.customer_id
and plpc.product_id=wokli.product_link_id
and plpc.finishingmethod_id=wokli.finishingmethod_id
and plpc.sizedefinition_id=wokli.sizedefinition_link_id
and wo.entrydate >= plpc.dateactive
and wo.entrydate <= plpc.dateinactive
and plpc.productlistpercustomer_id=moi.productlistpercustomer_id
and moi.supplier_id=sup.supplier_id

/
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 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, UniqueItemNonPool uinp, Product pr, Sizedefinition sd, UniqueItemFlag uif,
     workorder wo, workorderline wol,
     Languages lan
where ui.uniqueitem_id=uinp.uniqueitem_id
      and ui.product_id = pr.product_id
      and ui.sizedefinition_id = sd.sizedefinition_id
      and uif.uniqueitem_id = ui.uniqueitem_id
      and uinp.replacementworkorderline_id = wol.workorderline_id
      and wol.workorder_id = wo.workorder_id
      and exists (select * from AutomaticFlag af
                 where uif.Flag_ID = af.Flag_ID and af.event = 'Replacement requested using replacement button')
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, Wearerinventory wi, Product pr, Sizedefinition sd,
     workorder wo, workorderline wol,
     Languages lan
where nui.wearerinventory_id = wi.wearerinventory_id
      and wi.product_id = pr.product_id
      and wi.sizedefinition_id = sd.sizedefinition_id
      and nui.replacementworkorderline_id = wol.workorderline_id
      and wol.workorder_id = wo.workorder_id
      and exists (select * from AutomaticFlag af
                 where nui.flag_id = af.Flag_ID
                       and af.event = 'Replacement requested using replacement button')
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, Product pr, Sizedefinition sd, UniqueItemFlag uif,
     workorder wo, workorderline wol,
     Languages lan
where sui.product_id = pr.product_id
      and sui.sizedefinition_id = sd.sizedefinition_id
      and uif.uniqueitem_id = sui.uniqueitem_id
      and sui.substituteworkorderline_id = wol.workorderline_id
      and wol.workorder_id = wo.workorder_id
      and exists (select * from AutomaticFlag af
                 where uif.Flag_ID = af.Flag_ID and af.event = 'Substitute garment')
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, Product pr, Sizedefinition sd,
     workorder wo, workorderline wol,
     Languages lan
where nsui.substituteforproduct_id = pr.product_id
      and nsui.substituteforsizedefinition_id = sd.sizedefinition_id
      and nsui.substituteworkorderline_id = wol.workorderline_id
      and wol.workorder_id = wo.workorder_id
      and exists (select * from AutomaticFlag af
                 where nsui.Flag_ID = af.Flag_ID
                       and af.event = 'Substitute garment')

/
create or replace view V_WORKORDERREPLACEMENT_POS
 (REPLACEMENTWORKORDER_ID, PRIMARYID, RESIDUALVALUE, WASHESTOTAL, SECONDARYID, RAGTIMESTAMP, RAGREASON_CODE, LANGUAGE_CODE, LANGUAGE_ID, RAGREASON_DESC, NEWPRIMARYID)
as select ri.replacementworkorder_id, ri.primaryid, ri.residualvalue, ri.washestotal, ri.secondaryid
, ri.ragtimestamp, rr.code ragreason_code, lan.code language_code, lan.language_id
, (select rd.description from ragreason_desc rd where rd.language_id=lan.language_id and rr.ragreason_id = rd.ragreason_id) ragreason_desc
, (select max(ui.primaryid) from uniqueitemfixedinfo uif, uniqueitem ui
where uif.issuedbyworkorder_id = ri.replacementworkorder_id and uif.uniqueitem_id = ui.uniqueitem_id) Newprimaryid
from raggeditem ri, ragreason rr, languages lan
where ri.ragreason_id = rr.ragreason_id

/
create or replace view V_WORKORDERSPERPO_REP_AUJ
 (WORKORDER_ID, WORKORDERNUMBER, REQUESTDATE, NEEDEDDATE, CUSTOMER_ID, CUSTOMERNUMBER, CUSTOMERNAME, PURCHASEORDERNUMBER, SUPPLIERNUMBER, SUPPNAME, LAN_CODE)
as SELECT wo.workorder_id, wo.workordernumber, wo.requestdate, wo.neededdate
, cu.customer_id, cu.customernumber, cu.name CustomerName
, poh.purchaseordernumber
, su.suppliernumber, su.name SuppName
, lan.code Lan_code
FROM workorder wo, workorderline wol
, customer cu
, product prd, sizedefinition sd
, purchaseorderline pol, purchaseorderheader poh
, productsizepersupproduct ps, supplierproduct sp, supplier su
, languages lan
WHERE wo.workorder_id = wol.workorder_id
and wo.customer_link_id=cu.customer_id
and wol.product_link_id = prd.product_id and wol.sizedefinition_link_id = sd.sizedefinition_id
and wol.purchaseorderline_id = pol.purchaseorderline_id and pol.purchaseorderheader_id = poh.purchaseorderheader_id
and ps.product_id = wol.product_link_id and ps.sizedefinition_id = wol.sizedefinition_link_id
and sp.supplierproduct_id = ps.supplierproduct_id and sp.supplier_id = su.supplier_id
and poh.supplier_id=su.supplier_id
and lan.language_id=2
and wo.status_id<>23
and wol.quantityfilled<>wol.quantityordered
group by
wo.workorder_id, wo.workordernumber, wo.requestdate, wo.neededdate
, cu.customer_id, cu.customernumber, cu.name
, poh.purchaseordernumber
, su.suppliernumber, su.name
, lan.code

/
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
--, (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sd.sizedefinition_id and sdd.language_id = lan.language_id) SizeDesc
, poh.purchaseordernumber, wol.quantityordered WOLOrdered, pol.quantityordered POLOrdered
, su.suppliernumber, su.name SuppName
, lan.code Lan_code
FROM workorder wo, workorderline wol, weareremployment we, wearer w, customer cu
, product prd, sizedefinition sd--, finishingmethod fm
, purchaseorderline pol, purchaseorderheader poh
, productsizepersupproduct ps, supplierproduct sp, 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.product_link_id = prd.product_id and wol.sizedefinition_link_id = sd.sizedefinition_id --and wol.finishingmethod_id = fm.finishingmethod_id
and wol.purchaseorderline_id = pol.purchaseorderline_id and pol.purchaseorderheader_id = poh.purchaseorderheader_id
and ps.product_id = wol.product_link_id and ps.sizedefinition_id = wol.sizedefinition_link_id
and sp.supplierproduct_id = ps.supplierproduct_id and sp.supplier_id = su.supplier_id
and poh.supplier_id=su.supplier_id
union
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
--, (select sdd.description from sizedefinition_desc sdd where sdd.sizedefinition_id = sd.sizedefinition_id and sdd.language_id = lan.language_id) SizeDesc
, poh.purchaseordernumber, wol.quantityordered WOLOrdered, pol.quantityordered POLOrdered
, su.suppliernumber, su.name SuppName
, lan.code Lan_code
FROM workorder wo, workorderline wol, weareremployment we, wearer w, customer cu
, product prd, sizedefinition sd--, finishingmethod fm
, purchaseorderline pol, purchaseorderheader poh
, productsizepersupproduct ps, supplierproduct sp, supplier su
, languages lan
, workorderlinepurchordline wolpol
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.product_link_id = prd.product_id and wol.sizedefinition_link_id = sd.sizedefinition_id --and wol.finishingmethod_id = fm.finishingmethod_id
and pol.purchaseorderline_id=wolpol.workorderlinepurchordline_id and wol.workorderline_id=wolpol.workorderline_id
and pol.purchaseorderheader_id = poh.purchaseorderheader_id
and ps.product_id = wol.product_link_id and ps.sizedefinition_id = wol.sizedefinition_link_id
and sp.supplierproduct_id = ps.supplierproduct_id and sp.supplier_id = su.supplier_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_WORKORDERSTOCKDELIVERY_ANF
 (WORKORDERLINE_ID, WORKORDER_ID, PRODCODE, PRODDESC, SIZECODE, CODEUNIQUELY, FMCODE, ORDEREDGRADE, QUANTITYORDERED, QUANTITYFILLED, QUANTITYCANCELLED, QOPEN, PURCHASEORDERHEADER_ID, PURCHASEORDERNUMBER, WORKORDERNUMBER, CUSTOMERNUMBER, CUSTOMERNAME, STREET, STREET2, ZIPCODE, CITY, STATE, COUNTY, HOUSENUMBER, HOUSENUMBEREXT, SUPPLIER, POL_TIMESTAMP, POL_QTYORDERED, POL_REMARK, PREWASHBYSUPPLIER, PREWASHTEXT, POL_SIZECODE, POL_SIZESEQ, STKSC61, ENCDE, STKCHIFF, LANGUAGE_CODE, PRODUCT_ID, SIZEDEFINITION_ID
, SIZEDEFINITION_LINK_ID, QUALITYGRADE_ID, CUSTOMER_LINK_ID, CUSTOMEROWNED)
as select wokli.workorderline_id, wokli.workorder_id, p.code prodcode,
(select pd.description from product_desc pd
         where  p.product_id = pd.product_id and pd.language_id = lan.language_id) proddesc,
sd.code sizecode, wokli.codeuniquely codeuniquely,
(select fm.code from finishingmethod fm where fm.finishingmethod_id = wokli.finishingmethod_id) fmcode,
(select qdesc.description from qualitygrade_desc qdesc
         where  qdesc.qualitygrade_id = qOrdered.qualitygrade_id and qdesc.language_id = lan.language_id) OrderedGrade,
wokli.quantityordered quantityordered, wokli.quantityfilled quantityfilled,  wokli.quantitycancelled,
(wokli.quantityordered - wokli.quantityfilled - wokli.quantitycancelled) qOpen,
poh.purchaseorderheader_id, poh.purchaseordernumber, wok.workordernumber
, coalesce(castnumberasvarchar(cu.customernumber), sk.code) customernumber, coalesce(cu.name, sk.name) customername,
ad.street, ad.street2, ad.zipcode, ad.city, ad.state, ad.county, ad.housenumber, ad.housenumberext,
coalesce(
(select max(sup1.name) from stockdefinitionperitem sdi, supplier sup1, supplychainrules scr1 where sup1.supplier_id = coalesce(scr1.preferredexternalsupplier_id, scr1.preferredinternalsupplier_id)
and sdi.stockdefinitionperitem_id = scr1.stockdefinitionperitem_id ),
(select max(supp.name) from supplychainrules scr, supplier supp
where scr.stockroom_id = wok.processingstockroom_id and coalesce(scr.preferredexternalsupplier_id, scr.preferredinternalsupplier_id) = supp.supplier_id)) Supplier,
trunc(pol.timestamp) pol_timestamp, (pold.quantityordered-pold.quantitycancelled) pol_qtyordered, pol.remark pol_remark,
pol.prewashbysupplier, case when pol.prewashbysupplier = 1 then 'Y' else 'N' end PrewashText,
(select polsd.code from sizedefinition polsd where polsd.sizedefinition_id = pol.sizedefinition_link_id) pol_sizecode,
(select psz.sequencenumber from productsize psz where psz.product_id=pol.product_link_id and psz.sizedefinition_id = pol.sizedefinition_link_id ) pol_SizeSeq,
coalesce((select sum(sq.qtynonunique + sq.qtyunique + sq.qtyuniquewithmodifications - coalesce(boa.quantityallocated, 0))
from stockquantity sq, stockdefinitionperitem sdi, stockroom stk, stockroomlocation sl, stockreservationpergrade srg
     left outer join backorderallocationwol boa on boa.stockreservationpergrade_id = srg.stockreservationpergrade_id
where srg.stockreservationpergrade_id = sq.stockreservationpergrade_id and srg.stockdefinitionperitem_id = sdi.stockdefinitionperitem_id and
sdi.stockroom_id = stk.stockroom_id and stk.code = 'SC-61' and srg.qualitygrade_id = qOrdered.Qualitygrade_Id and sl.stockroom_id = stk.stockroom_id and
sdi.product_id = p.product_id and sdi.sizedefinition_id = pol.sizedefinition_link_id and
coalesce(pold.customer_link_id, -1) = coalesce(sdi.customer_id, pold.customer_link_id, -1) and
pold.customerowned = sdi.customerowned and sq.stockroomlocation_id = sl.stockroomlocation_id and sl.locationtype_id <> 11 /*BLOCKED*/), 0)
-
coalesce((select sum(sq.qtynonunique + sq.qtyunique + sq.qtyuniquewithmodifications)
from stockquantity sq, stockdefinitionperitem sdi, stockroom stk, stockroomlocation sl, stockreservationpergrade srg
where srg.stockreservationpergrade_id = sq.stockreservationpergrade_id and srg.stockdefinitionperitem_id = sdi.stockdefinitionperitem_id and
sdi.stockroom_id = stk.stockroom_id and stk.code = 'SC-61' and srg.qualitygrade_id = qOrdered.Qualitygrade_Id and sl.stockroom_id = stk.stockroom_id and
sdi.product_id = p.product_id and sdi.sizedefinition_id = pol.sizedefinition_link_id and
coalesce(pold.customer_link_id, -1) = coalesce(sdi.customer_id, pold.customer_link_id, -1) and
pold.customerowned = sdi.customerowned and sq.stockroomlocation_id = sl.stockroomlocation_id and sl.locationtype_id = 11 /*BLOCKED*/), 0) StkSC61,
coalesce((select sum(wol1.quantityordered - wol1.quantityfilled - wol1.quantitycancelled)
from workorder wo1, workorderline wol1 where wol1.workorder_id = wo1.workorder_id and wol1.product_link_id = p.product_id and
wol1.sizedefinition_link_id = pol.sizedefinition_link_id and wo1.origin = 12 /*Replenishment*/
and wo1.businessunit_id = wok.businessunit_id), 0) EnCDE,
coalesce((select sum(sq.qtynonunique + sq.qtyunique + sq.qtyuniquewithmodifications - coalesce(boa.quantityallocated, 0))
from stockquantity sq, stockdefinitionperitem sdi, stockroom stk, qualitygrade qg, stockroomlocation sl, stockreservationpergrade srg
     left outer join backorderallocationwol boa on boa.stockreservationpergrade_id = srg.stockreservationpergrade_id
where srg.stockreservationpergrade_id = sq.stockreservationpergrade_id and srg.stockdefinitionperitem_id = sdi.stockdefinitionperitem_id and
sdi.stockroom_id = stk.stockroom_id and stk.code = 'CA-16' and srg.qualitygrade_id = qg.Qualitygrade_Id and sl.stockroom_id = stk.stockroom_id and
sdi.product_id = p.product_id and sdi.sizedefinition_id = pol.sizedefinition_link_id and qg.priority <= qOrdered.priority and
coalesce(pold.customer_link_id, -1) = coalesce(sdi.customer_id, pold.customer_link_id, -1) and
pold.customerowned = sdi.customerowned and sq.stockroomlocation_id = sl.stockroomlocation_id and sl.locationtype_id <> 11 /*BLOCKED*/ ), 0)
-
coalesce((select sum(sq.qtynonunique + sq.qtyunique + sq.qtyuniquewithmodifications)
from stockquantity sq, stockdefinitionperitem sdi, stockroom stk, qualitygrade qg, stockroomlocation sl, stockreservationpergrade srg
where srg.stockreservationpergrade_id = sq.stockreservationpergrade_id and srg.stockdefinitionperitem_id = sdi.stockdefinitionperitem_id and
sdi.stockroom_id = stk.stockroom_id and stk.code = 'CA-16' and srg.qualitygrade_id = qg.Qualitygrade_Id and sl.stockroom_id = stk.stockroom_id and
sdi.product_id = p.product_id and sdi.sizedefinition_id = pol.sizedefinition_link_id and qg.priority <= qOrdered.priority and
coalesce(pold.customer_link_id, -1) = coalesce(sdi.customer_id, pold.customer_link_id, -1) and
pold.customerowned = sdi.customerowned and sq.stockroomlocation_id = sl.stockroomlocation_id and sl.locationtype_id = 11 /*BLOCKED*/ ), 0) StkChiff,
lan.code Language_code,  p.product_id, sd.sizedefinition_id, pol.sizedefinition_link_id, qOrdered.Qualitygrade_Id, pold.customer_link_id, pold.customerowned
from purchaseorderheader poh
inner join purchaseorderline pol
  inner join purchaseorderlinedetail pold
     left outer join backorderpurchaseorderwol bopo
          inner join backorderexecutionwol boe
              inner join backorderwol bo
                   inner join workorderline wokli
                        inner join workorder wok on wok.workorder_id = wokli.workorder_id
                   on wokli.workorderline_id = bo.workorderline_id
              on bo.backorderwol_id = boe.backorderwol_id
          on boe.backorderexecutionwol_id = bopo.backorderexecutionwol_id
     on bopo.purchaseorderlinedetail_id = pold.purchaseorderlinedetail_id
  on pold.purchaseorderline_id = pol.purchaseorderline_id
on pol.purchaseorderheader_id = poh.purchaseorderheader_id
left outer join customer cu on cu.customer_id = coalesce(wok.customer_link_id, poh.customer_link_id)
left outer join stockroom sk on sk.stockroom_id = poh.stockroom_id and sk.internalcustomer = 'Y'
, product p, sizedefinition sd, qualitygrade qOrdered, address ad, languages lan
where pol.product_link_id = p.product_id and pol.sizedefinition_link_id = sd.sizedefinition_id
and p.product_id = coalesce(wokli.product_link_id, pol.product_link_id)
and sd.sizedefinition_id = coalesce(wokli.sizedefinition_link_id, pol.sizedefinition_link_id)
and qOrdered.Qualitygrade_Id = coalesce(wokli.requestedgrade_id, pol.requestedgrade_id)
and ad.address_id = coalesce(cu.visitaddress_id, sk.deliveryaddress_id)

/
create or replace view V_WORKORDER_AUJ
 (WORKORDER_ID, WORKORDERNUMBER, ORDERDATE, ORIGIN, DOCKET, CUSTOMERNUMBER, NAME, STREET, ZIPCODE, CITY, PHONENO, DEPARTMENTNUMBER, ROUTENUMBER, ROUTEDESCRIPTION, NOTLAUNDRYOWNED, COUNTWORKORDERLINE, COUNTWORKORDERLINEEMBLEM, PRINT_BARCODE, LANGUAGE_CODE, PRINTREPLACEMENTSONWO, SYSUSER_NAME, BUCODE, BUDESC, CUSTNAMEONLABEL, CUSTSEARCHNAME, CREATIONTIMESTAMP, REASONCODEDESC, SALESAREACODE, WEARERSEARCHNAME, WEARERNAME, WO_REMARK, WO_REFNUMBER, CUSTOMERBILLINGDAYS)
as select wok.workorder_id, wok.workordernumber, wok.neededdate orderdate, wok.origin origin,
       wok.workordernumber docket, cu.customernumber, cu.name, address.street, address.zipcode,
       address.city, cu.phoneno, nvl(t.departmentnumber, t2.departmentnumber) departmentnumber,
       case
         when isnumeric(nvl(t.legacydepartmentcode, t2.legacydepartmentcode)) = 1 then
          to_number(nvl(t.legacydepartmentcode, t2.legacydepartmentcode)) --wbo 24-04-2012
         else
          0
       end routenumber, route.description routedescription, wok.customerowned notlaundryowned,
       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,
       (select ss.value
         from   systemsetting ss
         where  ss.plant_id = plant.plant_id
         and    ss.name = 'PRINTBARCODEONWORKORDER') print_barcode, lan.code language_code,
       (select sy.value
         from   systemsetting sy
         where  sy.plant_id = plant.plant_id
         and    sy.name = 'PRINTREPLACEMENTSONWO') printreplacementsonwo, su.fullname sysuser_name,
       bu.code bucode, bu.description budesc, cu.customermarkinggarment custnameonlabel,
       cu.name custsearchname, wok.creationtimestamp,
       (select rd.description
         from   reasoncode rc, reasoncode_desc rd
         where  rc.reasoncode_id = wok.reasoncode_id
         and    rc.reasoncode_id = rd.reasoncode_id
         and    rd.language_id = lan.language_id) reasoncodedesc,
       coalesce((select sa.code from salesarea sa where cu.salesarea_id = sa.salesarea_id), '') salesareacode,
       w.searchname wearersearchname, w.fullname wearername, wok.remark wo_remark,
       wok.referencenumber wo_refnumber,
       (select cast(listagg(cdd.day_id, ', ') within group(order by cdd.day_id) as varchar2(60))
         from   customerdeliveryday cdd
         where  cdd.customer_id = cu.customer_id
         and    cdd.deliverytype = 'B'
         and    cdd.typeofmerchadise = 2) customerbillingdays
from   workorder wok
left   outer join(weareremployment we
join   wearer w
on     w.wearer_id = we.wearer_id
join   distributionpoint dp
on     dp.distributionpoint_id = we.distributionpoint_id
join   department t
on     t.department_id = dp.department_id) on we.weareremployment_id = wok.weareremployment_link_id
left   outer join(distributionpoint dp2
join   department t2
on     t2.department_id = dp2.department_id) on dp2.distributionpoint_id = wok.distributionpoint_link_id
join   customer cu
on     cu.customer_id = wok.customer_link_id
join   address address
on     cu.visitaddress_id = address.address_id
left   outer join route
on     wok.route_id = route.route_id
left   outer join systemuser su
on     wok.creationuser_id = su.systemuser_id
join   status
on     wok.status_id = status.status_id
join   businessunit bu
on     wok.businessunit_id = bu.businessunit_id
join   plant
on     bu.plant_id = plant.plant_id
cross  join languages lan

/
create or replace view V_WORKORDER_CLIENTS_ANF
 (CUSTOMERNUMBER, CUSTOMERNAME, STREET, STREET2, ZIPCODE, CITY, STATE, COUNTY, HOUSENUMBER, HOUSENUMBEREXT, PURCHASEORDERHEADER_ID, PURCHASEORDERNUMBER, WORKORDERNUMBER, REQUESTDATE)
as select coalesce(castnumberasvarchar(cu.customernumber), sk.code) customernumber, coalesce(cu.name, sk.name) customername,
       ad.street, ad.street2, ad.zipcode, ad.city, ad.state,
       ad.county, ad.housenumber, ad.housenumberext, poh.purchaseorderheader_id,
       poh.purchaseordernumber, wo.workordernumber, wo.requestdate
from purchaseorderheader poh
inner join purchaseorderline pol
  inner join purchaseorderlinedetail pold
    left outer join backorderpurchaseorderwol bopo
          inner join backorderexecutionwol boe
              inner join backorderwol bo
                   inner join workorderline wol
                        inner join workorder wo on wo.workorder_id = wol.workorder_id
                   on wol.workorderline_id = bo.workorderline_id
              on bo.backorderwol_id = boe.backorderwol_id
          on boe.backorderexecutionwol_id = bopo.backorderexecutionwol_id
    on bopo.purchaseorderlinedetail_id = pold.purchaseorderlinedetail_id
  on pold.purchaseorderline_id = pol.purchaseorderline_id
on pol.purchaseorderheader_id = poh.purchaseorderheader_id
left outer join customer cu on cu.customer_id = coalesce(wo.customer_link_id, poh.customer_link_id)
left outer join stockroom sk on sk.stockroom_id = poh.stockroom_id and sk.internalcustomer = 'Y'
, address ad
where ad.address_id = coalesce(cu.visitaddress_id, sk.deliveryaddress_id)

/
create or replace view V_WORKORDER_NAF
 (WORKORDER_ID, WORKORDERNUMBER, ORDERDATE, REFERENCENUMBER, ORIGIN, ORDERREMARK, DELIVERYDATE, SCHEDULEDDELIVERY, CREATEUSER, DELIVERYDAY_DESC, SCHEDULEDDELIVERY_DESC, DOCKET, ALLOWPHASEDELIVERY, STOCKROOM, CUSTOMERNUMBER, NAME, CUSTOMERMARKINGGARMENT, STREET, ZIPCODE, CITY, WCUSTOMERNUMBER, WNAME, WCUSTOMERMARKINGGARMENT, WSTREET, WZIPCODE, WCITY, WEARERNR, WEARERNAME, WEARERSEARCHNAME, WEARERFIRSTNAME, ADMIN, EMPLNR, CUPBOARD, LOCKER, GARMENTDISPENSER, DELIVERYPOINT, DELIVERYPADR
, 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)
as select
wok.workorder_id, wok.workordernumber, wok.requestdate OrderDate, wok.referencenumber, wok.origin
, wok.remark OrderRemark, wok.neededdate DeliveryDate, wok.expectedcompletedate ScheduledDelivery
, (case when (wok.workordernumber like '30%' and wok.referencenumber IS NOT NULL and wok.origin <> 6)
  then (select s.username || '; ' || s.fullname
        from workorder wo, systemuser s
        where wo.creationuser_id = s.systemuser_id
        and wo.workordernumber = wok.referencenumber)
  else ''
  end) CreateUser
--, 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, wok.allowphasedelivery
, sr.name Stockroom
, cu.customernumber, cu.name, cu.customermarkinggarment
, address.street, address.zipcode, address.city
, null wcustomernumber, '' wname, '' wcustomermarkinggarment
, '' wstreet, '' wzipcode, '' wcity
, w.wearernumber WearerNr
, w.fullname WearerName, w.searchname wearersearchname, W.FIRSTNAME WearerFIRSTNAME
, w.customeremployeenumber Admin, welk.sequencenumber EmplNr, lo.bank CupBoard, lo.locker
, ga.code GarmentDispenser
, (case when we.locker_id IS NULL then de.code || ' ' || de.description
                                  else delo.code || ' ' || delo.description end) DeliveryPoint
, (case when we.locker_id IS NULL then deladr.street || ', '|| deladr.zipcode || ' ' || deladr.city
                                  else deloadr.street || ', '|| deloadr.zipcode || ' ' || deloadr.city end) Deliverypadr
, department.description Department
, department.departmentnumber
, w.emblemname NameOnLabel, distributionpoint.description ConsPoint
, (select wf.description from wearerfunction wf where we.wearerfunction_id = wf.wearerfunction_id) FunctionX
, w.remark WearerRemark, route.routenumber, route.description RouteDescription
, wok.customerowned NotLaundryOwned, status.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
, plant.code plant_code, plant.name plant_name, plant.phoneno plant_phoneno, plant.faxno plant_faxno
, plant.email plant_email, plant.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
, (select ss.value from systemsetting ss where ss.plant_id = plant.plant_id and ss.name = 'PRINTBARCODEONWORKORDER') Print_Barcode
, lan.code Language_code
, (select sy.value from systemsetting sy where sy.plant_id = plant.plant_id and sy.name = 'PRINTREPLACEMENTSONWO') PRINTREPLACEMENTSONWO
from workorder wok
join weareremployment_LINK welk on wok.weareremployment_link_id = welk.weareremployment_link_id
left outer join weareremployment we on welk.weareremployment_id = we.weareremployment_id
left outer join wearer w on w.wearer_id = we.wearer_id
left outer join locker lo
     left outer join deliverypoint delo
          left outer join address deloadr on (delo.deliveryaddress_id = deloadr.address_id)
     on (lo.deliverypoint_id = delo.deliverypoint_id)
on (we.locker_id=lo.locker_id)
left outer join garmentdispenser ga on we.garmentdispenser_id=ga.garmentdispenser_id
left outer join deliverypoint de
     left outer join address deladr on (de.deliveryaddress_id = deladr.address_id)
on we.deliverypoint_id=de.deliverypoint_id
left outer join distributionpoint on distributionpoint.distributionpoint_id = we.distributionpoint_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 address on cu.visitaddress_id = address.address_id
left outer join route on wok.route_id = route.route_id
left outer join stockroom sr on wok.processingstockroom_id = sr.stockroom_id
, status, businessunit bu, plant, address paddr
, languages lan
where wok.status_id = status.status_id
and wok.businessunit_id = bu.businessunit_id
and bu.plant_id = plant.plant_id
and plant.address_id = paddr.address_id
UNION ALL
select
wok.workorder_id, wok.workordernumber, wok.requestdate OrderDate, wok.referencenumber, wok.origin
, wok.remark OrderRemark, wok.neededdate DeliveryDate, wok.expectedcompletedate ScheduledDelivery
, (case when (wok.workordernumber like '30%' and wok.referencenumber IS NOT NULL and wok.origin <> 6)
  then (select s.username || '; ' || s.fullname
        from workorder wo, systemuser s
        where wo.creationuser_id = s.systemuser_id
        and wo.workordernumber = wok.referencenumber)
  else ''
  end) CreateUser
--, 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, wok.allowphasedelivery
, sr.name Stockroom
, cu.customernumber, cu.name, cu.customermarkinggarment
, address.street, address.zipcode, address.city
, cus.customernumber wcustomernumber, cus.name wname, cus.customermarkinggarment wcustomermarkinggarment
, addr.street wstreet, addr.zipcode wzipcode, addr.city wcity
, w.wearernumber WearerNr
, w.fullname WearerName, w.searchname wearersearchname, W.FIRSTNAME WearerFIRSTNAME
, w.customeremployeenumber Admin, welk.sequencenumber EmplNr, lo.bank CupBoard, lo.locker
, ga.code GarmentDispenser
, (case when we.locker_id IS NULL then de.code || ' ' || de.description
                                  else delo.code || ' ' || delo.description end) DeliveryPoint
, (case when we.locker_id IS NULL then deladr.street || ', '|| deladr.zipcode || ' ' || deladr.city
                                  else deloadr.street || ', '|| deloadr.zipcode || ' ' || deloadr.city end) Deliverypadr
, department.description Department
, department.departmentnumber
, w.emblemname NameOnLabel, distributionpoint.description ConsPoint
, (select wf.description from wearerfunction wf where we.wearerfunction_id = wf.wearerfunction_id) FunctionX
, w.remark WearerRemark, route.routenumber, route.description RouteDescription
, wok.customerowned NotLaundryOwned, status.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
, plant.code plant_code, plant.name plant_name, plant.phoneno plant_phoneno, plant.faxno plant_faxno
, plant.email plant_email, plant.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
, (select ss.value from systemsetting ss where ss.plant_id = plant.plant_id and ss.name = 'PRINTBARCODEONWORKORDER') Print_Barcode
, lan.code Language_code
, (select sy.value from systemsetting sy where sy.plant_id = plant.plant_id and sy.name = 'PRINTREPLACEMENTSONWO') PRINTREPLACEMENTSONWO
from workorder wok
left outer join weareremployment_LINK welk on wok.weareremployment_link_id = welk.weareremployment_link_id
left outer join weareremployment we on welk.weareremployment_id = we.weareremployment_id
left outer join wearer w on w.wearer_id = we.wearer_id
left outer join locker lo
     left outer join deliverypoint delo
          left outer join address deloadr on (delo.deliveryaddress_id = deloadr.address_id)
     on (lo.deliverypoint_id = delo.deliverypoint_id)
on (we.locker_id=lo.locker_id)
left outer join garmentdispenser ga on we.garmentdispenser_id=ga.garmentdispenser_id
left outer join deliverypoint de
     left outer join address deladr on (de.deliveryaddress_id = deladr.address_id)
on we.deliverypoint_id=de.deliverypoint_id
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 address on cu.visitaddress_id=address.address_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 address addr on cus.visitaddress_id=addr.address_id
left outer join stockroom sr on wok.processingstockroom_id = sr.stockroom_id
, status, businessunit bu, plant, address paddr
, languages lan
where wok.status_id = status.status_id
and wok.businessunit_id = bu.businessunit_id
and plant.address_id = paddr.address_id
and bu.plant_id = plant.plant_id
and wok.weareremployment_link_id is null

/
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_WO_REFERENCE_NAF
 (REFERENCENUMBER, PACKINGNOTE_ID)
as select distinct wo.referencenumber, pn.packingnote_id
  from deliveryscan ds, issuehistory ih, workorder wo, packingnote pn
 where ds.uniqueitem_link_id = ih.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 ih.workorder_id = wo.workorder_id
   and ds.packingnote_id = pn.packingnote_id
   and wo.deliverfrom = 2
union
select distinct wo.referencenumber, pn.packingnote_id
  from garmentsaleshistory gsh,
       workorderline       wol,
       workorder           wo,
       packingnoteline     pnl,
       packingnote         pn
 where gsh.workorderline_id = wol.workorderline_id
   and wol.workorder_id = wo.workorder_id
   and gsh.packingnoteline_id = pnl.packingnoteline_id
   and pnl.packingnote_id = pn.packingnote_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)

/
