create or replace package pack_sort is
  -- Author  : TATIANA
  -- Created : 6/21/2004 5:49:46 PM
  -- Purpose :
  -- Public type declarations
  -- Version 90104 02-10-2017
  -- Update 19-01-2017 ABS-42607 Make it possible to feed a UHF buffer
  -- Update 02-03-2017 ABS-45388 Sorting System UHF ID code filter compatible
  -- Update 07-04-2017 ABS-39934 Changes in getgarmentdata (for pool and route)
  type deliveryweeks is table of number index by binary_integer;
  type visitdates is table of number index by varchar2(8);
  type flags is table of number index by varchar2(22);
  i                              integer;
  gv_specialsizeid               sizedefinition.sizedefinition_id%type; --size star
  AUTOMATICFLAG_DECREASE_MAX_INV integer := 7;
  --SO 20015256 logging in database instead of to files
  procedure write_logging(fp_message    in abslog.message%type,
                          fp_loglevel   in number,
                          fp_logname    in varchar2,
                          fp_plantid    in plant.plant_id%type default null,
                          fp_priority   in number default 1,
                          fp_detailinfo in number default 0); ---0=no detail 1=detail
  ---
  procedure getadditionalabelinfo(fp_idcode                      in uniqueitem.primaryid%type,
                                  fp_unitcode                    in businessunit.code%type,
                                  fp_deliverypointcode           in deliverypoint.code%type,
                                  fp_departmentdescription       out department.description%type,
                                  fp_consumptionpointnumber      out distributionpoint.distributionpointnumber%type,
                                  fp_consumptionpointdescription out distributionpoint.description%type,
                                  fp_deliverypointdescription    out deliverypoint.description%type,
                                  fp_deliverypointstreet1        out address.street%type,
                                  fp_deliverypointstreet2        out address.street2%type,
                                  fp_deliverypointzipcode        out address.zipcode%type,
                                  fp_deliverypointcity           out address.city%type,
                                  fp_transportarticledescription out transportarticle_desc.description%type);
  function getdeliveryweeksforyear(year      in integer,
                                   frequency in integer,
                                   offset    in integer) return deliveryweeks;
  procedure getnextdeliveryweek(deliveryschemeid in deliveryscheme.deliveryscheme_id%type,
                                dayno            in day.day_id%type,
                                currentdate      in date,
                                nextdeliveryweek out integer,
                                nextdeliveryyear out integer);
  function getvisitdate(deliveryschemeid in deliveryscheme.deliveryscheme_id%type,
                        dayno            in day.day_id%type,
                        currentdate      in date) return date;
  function getnextdeliverydate(currentdate in date,
                               customerid  in customer.customer_id%type,
                               typeofmerch in product.typeofmerchandise%type)
    return date;
  function getroutestopforcustomer(plantid_garment in plant.plant_id%type,
                                   visitdate       in date,
                                   customerid      in customer.customer_id%type,
                                   deliverypointid in integer) return integer;
  procedure getlastinroute(customerid      in customer.customer_id%type,
                           datex           in date,
                           deliverypointid in deliverypoint.deliverypoint_id%type,
                           typeofmerch     in product.typeofmerchandise%type,
                           lastinroute     out route.route_id%type,
                           routestopx      out routestop.routestop_id%type,
                           lastindate      out date);
  procedure fillplannedoutroute(plantid_garment     in plant.plant_id%type,
                                currentdate         in date,
                                typeofmerch         in product.typeofmerchandise%type,
                                deliverymethod      in integer,
                                deedeliveryschemeid in deliveryscheme.deliveryscheme_id%type,
                                plpcid              in productlistpercustomer.productlistpercustomer_id%type,
                                customerid          in customer.customer_id%type,
                                deliverypointid     in deliverypoint.deliverypoint_id%type,
                                lastinroute         in route.route_id%type,
                                lastindate          in date,
                                routestopin         in routestop.routestop_id%type,
                                routestopid         out routestop.routestop_id%type,
                                routeid             out route.route_id%type,
                                plannedoutdate      out date,
                                scanbyroute         in varchar2);
  procedure getflags(uniqueitemid        in uniqueitem.uniqueitem_id%type,
                     plantid_param       in plant.plant_id%type,
                     wearerflagid        in flag.flag_id%type,
                     wearerflagstartdate in date,
                     empflagid           in flag.flag_id%type,
                     empflagstartdate    in date,
                     languageid          in languages.language_id%type,
                     flagsusage          in integer,
                     flagcode1           out nocopy sortaddressperflag.sortaddress%type,
                     flagcode2           out nocopy sortaddressperflag.sortaddress%type,
                     flagcode3           out nocopy sortaddressperflag.sortaddress%type,
                     flagcode4           out nocopy sortaddressperflag.sortaddress%type,
                     flagdescription1    out nocopy flag_desc.description%type,
                     flagdescription2    out nocopy flag_desc.description%type,
                     flagdescription3    out nocopy flag_desc.description%type,
                     flagdescription4    out nocopy flag_desc.description%type,
                     flagsinfo           out nocopy varchar2, --300
                     destinationstring   out nocopy varchar2,
                     fp_kann_yes_no      in varchar2 default 'N', --Default N, options Y,N
                     fp_flag_freetext1   out nocopy uniqueitemflag.freetextitem%type,
                     fp_flag_freetext2   out nocopy uniqueitemflag.freetextitem%type,
                     fp_flag_freetext3   out nocopy uniqueitemflag.freetextitem%type,
                     fp_flag_freetext4   out nocopy uniqueitemflag.freetextitem%type);
  procedure getflags(uniqueitemid           in uniqueitem.uniqueitem_id%type,
                     plantid_param          in plant.plant_id%type,
                     wearerflagid           in flag.flag_id%type,
                     wearerflagstartdate    in date,
                     empflagid              in flag.flag_id%type,
                     empflagstartdate       in date,
                     languageid             in languages.language_id%type,
                     flagsusage             in integer,
                     flagcode1              out nocopy sortaddressperflag.sortaddress%type,
                     flagcode2              out nocopy sortaddressperflag.sortaddress%type,
                     flagcode3              out nocopy sortaddressperflag.sortaddress%type,
                     flagcode4              out nocopy sortaddressperflag.sortaddress%type,
                     flagdescription1       out nocopy flag_desc.description%type,
                     flagdescription2       out nocopy flag_desc.description%type,
                     flagdescription3       out nocopy flag_desc.description%type,
                     flagdescription4       out nocopy flag_desc.description%type,
                     flagsinfo              out nocopy varchar2, --300
                     destinationstring      out nocopy varchar2, --3
                     fp_kann_yes_no         in varchar2 default 'N', --Default N, options Y,N
                     fp_flag_freetext1      out nocopy uniqueitemflag.freetextitem%type,
                     fp_flag_freetext2      out nocopy uniqueitemflag.freetextitem%type,
                     fp_flag_freetext3      out nocopy uniqueitemflag.freetextitem%type,
                     fp_flag_freetext4      out nocopy uniqueitemflag.freetextitem%type,
                     flag_freetext1         out nocopy uniqueitemflag.freetextitem%type,
                     flag_freetext2         out nocopy uniqueitemflag.freetextitem%type,
                     flag_freetext3         out nocopy uniqueitemflag.freetextitem%type,
                     flag_freetext4         out nocopy uniqueitemflag.freetextitem%type,
                     ui_status_assigned     in varchar2 default 'N',
                     freetext2descriptionyn in varchar2 default 'Y',
                     metricon               in varchar2 default 'N');
  procedure determinegarmentid(sortingsystem     in varchar2,
                               idcode            in uniqueitem.primaryid%type,
                               plantcode         in plant.code%type,
                               uniqueitemid      out nocopy uniqueitem.uniqueitem_id%type,
                               pool              out nocopy uniqueitem.poolitem%type,
                               unitcode          out nocopy businessunit.code%type,
                               businessunitid    out nocopy businessunit.businessunit_id%type,
                               plantid_garment   out nocopy plant.plant_id%type,
                               returnedplantcode out nocopy plant.code%type,
                               status            out nocopy integer,
                               idprimary         out uniqueitem.primaryid%type,
                               plantid_param     out nocopy plant.plant_id%type,
                               secondaryid       out secondaryuniqueitem.secondaryid%type);
  procedure determinegarmentid2(sortingsystem     in varchar2,
                                idcode            in uniqueitem.primaryid%type,
                                plantcode         in plant.code%type,
                                uniqueitemid      out nocopy uniqueitem.uniqueitem_id%type,
                                pool              out nocopy uniqueitem.poolitem%type,
                                unitcode          out nocopy businessunit.code%type,
                                businessunitid    out nocopy businessunit.businessunit_id%type,
                                plantid_garment   out nocopy plant.plant_id%type,
                                returnedplantcode out nocopy plant.code%type,
                                status            out nocopy integer,
                                idprimary         out uniqueitem.primaryid%type,
                                plantid_param     out nocopy plant.plant_id%type,
                                secondaryid       out secondaryuniqueitem.secondaryid%type,
                                relatedcustomerid out nocopy uniqueitem.relatedcustomer_id%type,
                                productid         out nocopy product.product_id%type,
                                sizeid            out nocopy sizedefinition.sizedefinition_id%type,
                                batchnumber       out nocopy uniqueitem.batchnumber%type,
                                prevstayid        out nocopy uniqueitem.prevstay_id%type,
                                plastinscandate   out nocopy uniqueitem.lastinscandate%type);
  procedure getsystemsettings(plantid_param   in plant.plant_id%type,
                              debuglevel      out nocopy integer,
                              utldir          out nocopy varchar2,
                              allowrepairscan out nocopy integer,
                              getgarment      in number default 0);
  procedure getgarmentlocation(lockerid             in locker.locker_id%type,
                               garmentdispenserid   in garmentdispenser.garmentdispenser_id%type,
                               deliverypointid      in out deliverypoint.deliverypoint_id%type,
                               banklocker           out nocopy varchar2,
                               garmentdispensercode out nocopy garmentdispenser.code%type,
                               deliverypointcode    out nocopy deliverypoint.code%type);
  procedure getgarmentdatainfo(sortingsystem           in varchar2,
                               plantid_garment         in plant.plant_id%type,
                               uniqueitemid            in uniqueitem.uniqueitem_id%type,
                               languageid              in out languages.language_id%type,
                               finishingcodeid         out nocopy finishingcode.finishingcode_id%type,
                               serviceteamid           out nocopy serviceteam.serviceteam_id%type,
                               vchargerepairs          out nocopy customer.chargerepairs%type,
                               vcustomerowned          out nocopy uniqueitem.customerowned%type,
                               colorid                 out nocopy color.color_id%type,
                               wearerflagid            out nocopy flag.flag_id%type,
                               wearerflagstartdate     out nocopy date,
                               empflagid               out nocopy flag.flag_id%type,
                               empflagstartdate        out nocopy date,
                               finishingmethodid       out nocopy finishingmethod.finishingmethod_id%type,
                               productid               out nocopy product.product_id%type,
                               productcode             out nocopy product.code%type,
                               productdescription      out nocopy product_desc.description%type,
                               sizecode                out nocopy sizedefinition.code%type,
                               customernumber          out nocopy customer.customernumber%type,
                               customerid              out nocopy customer.customer_id%type,
                               customername            out nocopy customer.name%type,
                               wearernumber            out nocopy wearer.wearernumber%type,
                               wearername              out nocopy wearer.searchname%type,
                               banklocker              out nocopy varchar2,
                               departmentnumber        out nocopy department.departmentnumber%type,
                               customeremployeenumber  out nocopy wearer.customeremployeenumber%type,
                               gender                  out nocopy wearer.sex%type,
                               garmentdispensercode    out nocopy garmentdispenser.code%type,
                               deliverypointcode       out nocopy deliverypoint.code%type,
                               infotext                out nocopy wearer.remark%type,
                               routenumber             out nocopy route.routenumber%type,
                               routeday                out nocopy day.daynumber%type,
                               stopnumber              out nocopy routestop.stopnumber%type,
                               packingsequence         out nocopy product.packingsequence%type,
                               stayid                  out nocopy stay.stay_id%type,
                               routeid                 out nocopy route.route_id%type,
                               imageid                 out nocopy product.image_id%type,
                               routestopid             out nocopy routestop.routestop_id%type,
                               planneddate             out nocopy date,
                               statusout               out nocopy integer,
                               valternatesortingstring out nocopy customer.alternatesorting%type,
                               debuglevel              in integer,
                               findpackingnote         in out varchar2,
                               pnnotenumber            out packingnote.notenumber%type,
                               routedate               in out date,
                               fp_washestotal          out nocopy uniqueitem.washestotal%type,
                               fp_routecodeonlabel     out nocopy route.codeonlabel%type,
                               fp_plant_idparam        in plant.plant_id%type default null,
                               fp_sortcustomerid       out nocopy customer.sortcustomer_id%type,
                               fp_languagecode         in languages.code%type default null);
  function convertstringdesc(receivedstring varchar2) return varchar2;
  function buildsortstring(productcode          in product.code%type,
                           sizecode             in sizedefinition.code%type,
                           customernumber       in customer.customernumber%type,
                           customerid           in customer.customer_id%type,
                           wearernumber         in wearer.wearernumber%type,
                           wearername           in wearer.searchname%type,
                           banklocker           in varchar2,
                           departmentnumber     in department.departmentnumber%type,
                           customeremployee#    in wearer.customeremployeenumber%type,
                           gender               in wearer.sex%type,
                           garmentdispensercode in garmentdispenser.code%type,
                           deliverypointcode    in deliverypoint.code%type,
                           stopnumber           in routestop.stopnumber%type,
                           plantid_param        in plant.plant_id%type,
                           customerownedyn      in varchar2,
                           ordernumber          in packingnote.notenumber%type,
                           productsortgroupseq  in productsortgroupperplant.sequencenumber%type default 0,
                           lockersortgroup#     in lockersortgroup.lockersortgroupnumber%type default 0,
                           distributionpoint#   in distributionpoint.distributionpointnumber%type default 0,
                           fp_sortcustomerid    in customer.sortcustomer_id%type default null,
                           fp_stackchange       in sortingdefinition.stackchange%type default 'N')
    return varchar2;
  function buildstackchangeinfo(productcode          in product.code%type,
                                sizecode             in sizedefinition.code%type,
                                customernumber       in customer.customernumber%type,
                                customerid           in customer.customer_id%type,
                                wearernumber         in wearer.wearernumber%type,
                                wearername           in wearer.searchname%type,
                                banklocker           in varchar2,
                                departmentnumber     in department.departmentnumber%type,
                                customeremployee#    in wearer.customeremployeenumber%type,
                                gender               in wearer.sex%type,
                                garmentdispensercode in garmentdispenser.code%type,
                                deliverypointcode    in deliverypoint.code%type,
                                stopnumber           in routestop.stopnumber%type,
                                plantid_param        in plant.plant_id%type,
                                customerownedyn      in varchar2,
                                ordernumber          in packingnote.notenumber%type,
                                productsortgroupseq  in productsortgroupperplant.sequencenumber%type default 0,
                                lockersortgroup#     in lockersortgroup.lockersortgroupnumber%type default 0,
                                distributionpoint#   in distributionpoint.distributionpointnumber%type default 0,
                                fp_sortcustomerid    in customer.sortcustomer_id%type default null)
    return varchar2;
  function getsortstring(plantid_param in plant.plant_id%type,
                         customerid    in customer.customer_id%type,
                         routestopid   in routestop.routestop_id%type,
                         uniqueitemid  in uniqueitem.uniqueitem_id%type)
    return varchar2;
  procedure getdeliverydaysmask(customerid      in customer.customer_id%type,
                                deliverydaymask out nocopy varchar2);
  procedure getdepot(routeid in route.route_id%type,
                     depot   out nocopy depot.code%type);
  function updateflags(flagsstring    in varchar2,
                       uniqueitemid   in uniqueitem.uniqueitem_id%type,
                       fplastscandate in date,
                       systemuserid   in systemuser.systemuser_id%type,
                       debuglevel     in integer) return integer;
  procedure getsendtrackinfo(pool                 in uniqueitem.poolitem%type,
                             uniqueitemid         in uniqueitem.uniqueitem_id%type,
                             stayid               out nocopy stay.stay_id%type,
                             statusid             out nocopy status.status_id%type,
                             productid            out nocopy product.product_id%type,
                             sizeid               out nocopy sizedefinition.sizedefinition_id%type,
                             weareremploymentid   out nocopy weareremployment.weareremployment_id%type,
                             customerid           out nocopy customer.customer_id%type,
                             vissuedate           out nocopy date,
                             finishingmethodid    out nocopy finishingmethod.finishingmethod_id%type,
                             distributionpointid  out nocopy distributionpoint.distributionpoint_id%type,
                             lastdistribpointid   out nocopy distributionpoint_link.distributionpoint_link_id%type,
                             vwashestotal         out nocopy integer,
                             vcustomerowned       out nocopy varchar2,
                             qualitygradeid       out nocopy qualitygrade.qualitygrade_id%type,
                             vfirstissuedate      out nocopy date,
                             vnumberofissues      out nocopy integer,
                             vlastonstockdate     out nocopy date,
                             vdaysinstockprevious out nocopy integer,
                             vstatuschangedate    out nocopy date,
                             vstartrentfrom       out nocopy integer,
                             vdaysincircprevissue out nocopy integer,
                             vwashesthisissue     out nocopy integer,
                             unrelatedloanid      out nocopy unrelatedloan.unrelatedloan_id%type,
                             vlastinscandate      out nocopy date,
                             deliverypointid      out nocopy deliverypoint.deliverypoint_id%type,
                             lockerid             out nocopy locker.locker_id%type,
                             garmentdispenserid   out nocopy garmentdispenser.garmentdispenser_id%type,
                             accept               in out varchar2);
  procedure writelogfile(sortsystem           in varchar2,
                         debuglevel           in integer,
                         plantcode            in plant.code%type,
                         idcode               in uniqueitem.primaryid%type,
                         unitcode             in businessunit.code%type,
                         status               in varchar2,
                         finishselection      in varchar2,
                         checkpointselection  in varchar2,
                         repairselection      in varchar2,
                         destination          in varchar2,
                         fold                 in varchar2,
                         stackchangeinfo      in varchar2,
                         routenumber          in integer,
                         stopnumber           in integer,
                         routeday             in day.daynumber%type,
                         depot                in varchar2,
                         sortstring           in varchar2,
                         alternatesortstring  in varchar2,
                         customernumber       in customer.customernumber%type,
                         customername         in customer.name%type,
                         wearernumber         in wearer.wearernumber%type,
                         wearername           in wearer.searchname%type,
                         department           in department.departmentnumber%type,
                         customeremployee#    in wearer.customeremployeenumber%type,
                         gender               in wearer.sex%type,
                         banklocker           in varchar2,
                         garmentdispensercode in garmentdispenser.code%type,
                         deliverypointcode    in deliverypoint.code%type,
                         productcode          in product.code%type,
                         productdescription   in product_desc.description%type,
                         sizecode             in sizedefinition.code%type,
                         productpicturecode   in image.code%type,
                         deliverydaymask      in varchar2,
                         secondaryid          in secondaryuniqueitem.secondaryid%type,
                         flagcode1            in sortaddressperflag.sortaddress%type,
                         flagcode2            in sortaddressperflag.sortaddress%type,
                         flagcode3            in sortaddressperflag.sortaddress%type,
                         flagcode4            in sortaddressperflag.sortaddress%type,
                         flagdescription1     in flag_desc.description%type,
                         flagdescription2     in flag_desc.description%type,
                         flagdescription3     in flag_desc.description%type,
                         flagdescription4     in flag_desc.description%type,
                         infotext             in wearer.remark%type,
                         requiredrepairs      in varchar2,
                         flags                in varchar2,
                         staycode             in varchar2,
                         sortbatchnumber      in integer,
                         spare2               in varchar2);
  function iscustomervisitdate(customerid  customer.customer_id%type,
                               planneddate date) return boolean;
  function iscustomervisitdateint(customerid  customer.customer_id%type,
                                  planneddate date) return integer;
  function isdepartmentdeliverydayint(depid  department.department_id%type,
                                      delday day.day_id%type) return integer;
  procedure processcheckpointscan(transactiontp   in sortingimportdefinition.transactiontype%type,
                                  idcode          in uniqueitem.primaryid%type,
                                  pool            in integer,
                                  secondaryid     in secondaryuniqueitem.secondaryid%type,
                                  businessunitid  in businessunit.businessunit_id%type,
                                  uniqueitemid    in uniqueitem.uniqueitem_id%type,
                                  workstationcode in workstation.code%type,
                                  datep           in number,
                                  timep           in varchar2,
                                  systemuserid    in systemuser.systemuser_id%type,
                                  debuglevel      in integer,
                                  accept          out varchar2,
                                  scanbyroute     in varchar2,
                                  plantid_garment in plant.plant_id%type,
                                  flagcode1       in sortaddressperflag.sortaddress%type default null,
                                  flagcode2       in sortaddressperflag.sortaddress%type default null,
                                  flagcode3       in sortaddressperflag.sortaddress%type default null,
                                  flagcode4       in sortaddressperflag.sortaddress%type default null);
  procedure processinscan(transactiontp   in sortingimportdefinition.transactiontype%type,
                          idcode          in uniqueitem.primaryid%type,
                          pool            in integer,
                          secondaryid     in secondaryuniqueitem.secondaryid%type,
                          plantid_garment in plant.plant_id%type,
                          plantid_param   in plant.plant_id%type,
                          businessunitid  in businessunit.businessunit_id%type,
                          uniqueitemid    in uniqueitem.uniqueitem_id%type,
                          workstationcode in workstation.code%type,
                          datep           in number,
                          timep           in varchar2,
                          countwashesat   in varchar2,
                          scanbyroute     in varchar2,
                          systemuserid    in systemuser.systemuser_id%type,
                          debuglevel      in integer,
                          accept          out varchar2,
                          scaninterval    out varchar2,
                          pickuproutedate in date,
                          fpsretransferyn in varchar2 default 'N',
                          flagcode1       in sortaddressperflag.sortaddress%type default null,
                          flagcode2       in sortaddressperflag.sortaddress%type default null,
                          flagcode3       in sortaddressperflag.sortaddress%type default null,
                          flagcode4       in sortaddressperflag.sortaddress%type default null);
  procedure processoutscan(transactiontp   in sortingimportdefinition.transactiontype%type,
                           idcode          in uniqueitem.primaryid%type,
                           secondaryid     in secondaryuniqueitem.secondaryid%type,
                           plantid_garment in plant.plant_id%type,
                           plantid_param   in plant.plant_id%type,
                           businessunitid  in businessunit.businessunit_id%type,
                           uniqueitemid    in uniqueitem.uniqueitem_id%type,
                           workstationid   in workstation.workstation_id%type,
                           workstationcode in workstation.code%type,
                           datep           in number,
                           timep           in varchar2,
                           countwashesat   in varchar2,
                           scanbyroute     in varchar2,
                           systemuserid    in systemuser.systemuser_id%type,
                           debuglevel      in integer,
                           accept          out varchar2,
                           scaninterval    out varchar2,
                           packingnoteid   in integer,
                           statusout       out integer,
                           flagcode1       in sortaddressperflag.sortaddress%type default null,
                           flagcode2       in sortaddressperflag.sortaddress%type default null,
                           flagcode3       in sortaddressperflag.sortaddress%type default null,
                           flagcode4       in sortaddressperflag.sortaddress%type default null,
                           m_deliveryscan  in varchar2 default 'Y');
  procedure processrepairscan(transactiontp   in sortingimportdefinition.transactiontype%type,
                              idcode          in uniqueitem.primaryid%type,
                              pool            in integer,
                              secondaryid     in secondaryuniqueitem.secondaryid%type,
                              businessunitid  in businessunit.businessunit_id%type,
                              uniqueitemid    in uniqueitem.uniqueitem_id%type,
                              workstationcode in workstation.code%type,
                              datep           in number,
                              timep           in varchar2,
                              repairsdone     in varchar2,
                              systemuserid    in systemuser.systemuser_id%type,
                              debuglevel      in integer,
                              accept          out varchar2,
                              flagcode1       in sortaddressperflag.sortaddress%type default null,
                              flagcode2       in sortaddressperflag.sortaddress%type default null,
                              flagcode3       in sortaddressperflag.sortaddress%type default null,
                              flagcode4       in sortaddressperflag.sortaddress%type default null);
  procedure processrewash(transactiontp   in sortingimportdefinition.transactiontype%type,
                          idcode          in uniqueitem.primaryid%type,
                          pool            in integer,
                          secondaryid     in secondaryuniqueitem.secondaryid%type,
                          plantid_garment in plant.plant_id%type,
                          plantid_param   in plant.plant_id%type,
                          businessunitid  in businessunit.businessunit_id%type,
                          uniqueitemid    in uniqueitem.uniqueitem_id%type,
                          workstationcode in workstation.code%type,
                          datep           in number,
                          timep           in varchar2,
                          scanbyroute     in varchar2,
                          systemuserid    in systemuser.systemuser_id%type,
                          debuglevel      in integer,
                          accept          out varchar2,
                          flagcode1       in sortaddressperflag.sortaddress%type default null,
                          flagcode2       in sortaddressperflag.sortaddress%type default null,
                          flagcode3       in sortaddressperflag.sortaddress%type default null,
                          flagcode4       in sortaddressperflag.sortaddress%type default null);
  procedure processsortscan(transactiontp   in sortingimportdefinition.transactiontype%type,
                            idcode          in uniqueitem.primaryid%type,
                            pool            in integer,
                            secondaryid     in secondaryuniqueitem.secondaryid%type,
                            businessunitid  in businessunit.businessunit_id%type,
                            uniqueitemid    in uniqueitem.uniqueitem_id%type,
                            workstationcode in workstation.code%type,
                            datep           in number,
                            timep           in varchar2,
                            systemuserid    in systemuser.systemuser_id%type,
                            debuglevel      in integer,
                            accept          out varchar2,
                            flagcode1       in sortaddressperflag.sortaddress%type default null,
                            flagcode2       in sortaddressperflag.sortaddress%type default null,
                            flagcode3       in sortaddressperflag.sortaddress%type default null,
                            flagcode4       in sortaddressperflag.sortaddress%type default null);
  function iscustomeractive(customerid   customer.customer_id%type,
                            specificdate date) return boolean;
  function getstopstatus(customerid   customer.customer_id%type,
                         specificdate date) return number;
  procedure importsoilscan(fpnplantid      plant.plant_id%type,
                           fpsreadfilename varchar2);
  function getsortstringsupport(plantid      in plant.plant_id%type,
                                customerid   in customer.customer_id%type,
                                routestopid  in routestop.routestop_id%type,
                                uniqueitemid in uniqueitem.uniqueitem_id%type)
    return varchar2;

  function iscustomer_nonbusinessday(customerid  customer.customer_id%type,
                                     planneddate date) return boolean;
  procedure getnextdeliverydatewithstop(currentdate     in date,
                                        plantid         in plant.plant_id%type,
                                        customerid      in customer.customer_id%type,
                                        typeofmerch     in product.typeofmerchandise%type,
                                        deliverypointid in deliverypoint.deliverypoint_id%type,
                                        retvisitdate    out date,
                                        retroute        out route.route_id%type);
  procedure addmaxrepairflag(uniqueitemid        in uniqueitem.uniqueitem_id%type,
                             systemuserid        in systemuser.systemuser_id%type,
                             debuglevel          in integer,
                             businessunitid      in businessunit.businessunit_id%type,
                             pool                in integer,
                             vlastscandate       in date,
                             repairstotal        in integer,
                             productid           in product.product_id%type,
                             sizeid              in sizedefinition.sizedefinition_id%type,
                             finishingmethodid   in finishingmethod.finishingmethod_id%type,
                             distributionpointid in distributionpoint.distributionpoint_id%type);
end pack_sort;
/
create or replace package body pack_sort is
  --order 20012023, additional getgarmentdata metricon fields
  gv_sortroutestop varchar2(1);
  --SO 20015256 logging in database instead of to files
  procedure write_logging(fp_message    in abslog.message%type,
                          fp_loglevel   in number,
                          fp_logname    in varchar2,
                          fp_plantid    in plant.plant_id%type default null,
                          fp_priority   in number default 1,
                          fp_detailinfo in number default 0) is ---0=no detail 1=detail
  begin
    --write_logging
    if fp_priority > 1 then
      begin
        abslogwrite.abslog_write(5,
                                 fp_logname,
                                 fp_plantid,
                                 fp_priority,
                                 fp_message);
      end;
    else
      case fp_loglevel
        when 0 then
          null; --no logging other then errors
        when 1 then
          if fp_detailinfo = 1 then
            --Log level 1 and detailinfo=1 write detail info
            abslogwrite.abslog_write(5,
                                     fp_logname,
                                     fp_plantid,
                                     fp_priority,
                                     fp_message);
          end if;
        when 2 then
          --write all logs
          abslogwrite.abslog_write(5,
                                   fp_logname,
                                   fp_plantid,
                                   fp_priority,
                                   fp_message);
        else
          null;
      end case;
    end if;
  end write_logging;
  ---
  function iscustomervisitdateint(customerid  customer.customer_id%type,
                                  planneddate date) return integer is
    xyear integer;
    xweek integer;
    xday  integer;
    i     integer;
  begin
    i     := 0;
    xday  := getabsdaynumber(planneddate);
    xweek := getisoweek(planneddate);
    xyear := getyearofweek(planneddate);
    for dcursor in (select d.deliveryscheme_id,
                           x.frequency,
                           x.offsetweek,
                           c.day_id
                      from customerdeliveryday    c,
                           customerdeliveryscheme d,
                           deliveryscheme         x
                     where c.customer_id = customerid
                       and c.customer_id = d.customer_id
                       and c.day_id = d.day_id
                       and d.deliveryscheme_id = x.deliveryscheme_id
                       and c.day_id = xday) loop
      begin
        if isweekdeliveryweek(xyear,
                              xweek,
                              dcursor.frequency,
                              dcursor.offsetweek) then
          i := 1;
          exit;
        end if;
      end;
    end loop;
    if i = 1 then
      return 1;
    else
      return 0;
    end if;
  end iscustomervisitdateint;
  function isdepartmentdeliverydayint(depid  department.department_id%type,
                                      delday day.day_id%type) return integer is
    depdelday deliveryday.day_id%type;
  begin
    begin
      select dd.day_id
        into depdelday
        from deliveryday dd
       where dd.department_id = depid
         and dd.day_id = delday;
    exception
      when no_data_found then
        return 1;
    end;
    if depdelday = delday then
      return 0;
    end if;
  end isdepartmentdeliverydayint;
  procedure getadditionalabelinfo(fp_idcode                      in uniqueitem.primaryid%type,
                                  fp_unitcode                    in businessunit.code%type,
                                  fp_deliverypointcode           in deliverypoint.code%type,
                                  fp_departmentdescription       out department.description%type,
                                  fp_consumptionpointnumber      out distributionpoint.distributionpointnumber%type,
                                  fp_consumptionpointdescription out distributionpoint.description%type,
                                  fp_deliverypointdescription    out deliverypoint.description%type,
                                  fp_deliverypointstreet1        out address.street%type,
                                  fp_deliverypointstreet2        out address.street2%type,
                                  fp_deliverypointzipcode        out address.zipcode%type,
                                  fp_deliverypointcity           out address.city%type,
                                  fp_transportarticledescription out transportarticle_desc.description%type) is
    lv_poolitem            uniqueitem.poolitem%type;
    lv_customerid          customer.customer_id%type;
    lv_distributionpointid distributionpoint.distributionpoint_id%type;
    lv_plantid             plant.plant_id%type;
    lv_languageid          languages.language_id%type;
    lv_sortcustomerid      customer.customer_id%type;
    lv_externalockerid     locker.locker_id%type;

    procedure make_null is
    begin
      --make all output variables null
      fp_departmentdescription       := null;
      fp_consumptionpointnumber      := null;
      fp_consumptionpointdescription := null;
      fp_deliverypointdescription    := null;
      fp_deliverypointstreet1        := null;
      fp_deliverypointstreet2        := null;
      fp_deliverypointzipcode        := null;
      fp_deliverypointcity           := null;
      fp_transportarticledescription := null;
    end make_null;
  begin
    make_null;
    --get garment id
    select u.poolitem,
           t.description,
           dp.distributionpointnumber,
           dp.description,
           t.customer_id,
           bu.plant_id,
           dp.distributionpoint_id,
           pt.language_id,
           c.sortcustomer_id,
           we.externallocker_id
      into lv_poolitem,
           fp_departmentdescription,
           fp_consumptionpointnumber,
           fp_consumptionpointdescription,
           lv_customerid,
           lv_plantid,
           lv_distributionpointid,
           lv_languageid,
           lv_sortcustomerid,
           lv_externalockerid
      from uniqueitem        u,
           uniqueitemnonpool un,
           businessunit      bu,
           weareremployment  we,
           department        t,
           distributionpoint dp,
           plant             pt,
           customer          c
     where u.primaryid = fp_idcode
       and u.businessunit_id = bu.businessunit_id
       and bu.code = fp_unitcode
       and u.uniqueitem_id = un.uniqueitem_id
       and bu.plant_id = pt.plant_id
       and un.weareremployment_id = we.weareremployment_id
       and we.distributionpoint_id = dp.distributionpoint_id
       and dp.department_id = t.department_id
       and c.customer_id = t.customer_id;
    --do nothing for pool=1
    if lv_poolitem <> 1 then
      begin
        begin
          -- Order 20013679 take delivery point info from sort customer
          if lv_externalockerid is not null and
             lv_sortcustomerid is not null then
            lv_customerid := lv_sortcustomerid;
          end if;
          --get deliverypoint
          select dpo.description,
                 ad.street,
                 ad.street2,
                 ad.zipcode,
                 ad.city
            into fp_deliverypointdescription,
                 fp_deliverypointstreet1,
                 fp_deliverypointstreet2,
                 fp_deliverypointzipcode,
                 fp_deliverypointcity
            from deliverypoint dpo, address ad
           where dpo.customer_id = lv_customerid
             and dpo.code = trim(fp_deliverypointcode)
             and dpo.deliveryaddress_id = ad.address_id;
        exception
          when no_data_found then
            begin
              fp_deliverypointdescription := null;
              fp_deliverypointstreet1     := null;
              fp_deliverypointstreet2     := null;
              fp_deliverypointzipcode     := null;
              fp_deliverypointcity        := null;
            end;
        end;
        begin
          --get transportarticledescription
          select td.description
            into fp_transportarticledescription
            from standarddelivery std, transportarticle_desc td
           where std.distributionpoint_id = lv_distributionpointid
             and std.sequencenumber = 1
             and std.transportarticle_id = td.transportarticle_id
             and td.language_id = lv_languageid;
        exception
          when no_data_found then
            begin
              fp_transportarticledescription := null;
            end;
        end;
      end; --lv_poolitem <> 1
    else
      make_null; --nothing to be returned
    end if;
  exception
    when no_data_found then
      make_null; --nothing to be returned
  end getadditionalabelinfo;
  --begin 502877
  function create_uniqueitemflag(fp_logname         in abslog.logsource%type,
                                 fp_debuglevel      in integer,
                                 fp_systemuserid    in systemuser.systemuser_id%type,
                                 fp_uniqueitemid    in uniqueitem.uniqueitem_id%type,
                                 fp_flagid          in flag.flag_id%type,
                                 fp_startdate       in uniqueitemflag.startdate%type default sysdate,
                                 fp_scanid          in scan.scan_id%type default null,
                                 fp_freetextitem    in uniqueitemflag.freetextitem%type default null,
                                 fp_treatmenttypeid in uniqueitemflag.treatmenttype_id%type default null,
                                 fp_plantid_param   in plant.plant_id%type default null)
    return boolean is
    lvcounter    number;
    flaginserted boolean;
  begin
    flaginserted := false;

    -- if flag id is null, then return
    if (fp_flagid is null) then
      return false;
    end if;

    --check if flag did not already exist yes or no
    select count(u.flag_id)
      into lvcounter
      from uniqueitemflag u
     where u.uniqueitem_id = fp_uniqueitemid
       and u.flag_id = fp_flagid;
    --only add flag when it did not yet exist, then counter=0
    if lvcounter = 0 then
      --insert into uniqueitemflag
      insert into uniqueitemflag
        (uniqueitem_id,
         flag_id,
         startdate,
         freetextitem,
         systemuser_id,
         timestamp,
         treatmenttype_id)
      values
        (fp_uniqueitemid,
         fp_flagid,
         trunc(fp_startdate),
         fp_freetextitem,
         fp_systemuserid,
         sysdate,
         fp_treatmenttypeid);
      flaginserted := true;
      --add scanflag when scanid is known
      if fp_scanid is not null then
        insert into scanflag
          (scan_id, flag_id, flagresponse, systemuser_id, timestamp)
        values
          (fp_scanid, fp_flagid, 'N', fp_systemuserid, sysdate);
      end if;
      --add debud information when needed
      if fp_debuglevel > 0 then
        pack_sort.write_logging('PACK_SORT.CREATE_UNIQUEITEMFLAG Insert uniqueitemflag for uniqueitemid ' ||
                                fp_uniqueitemid || ' flagid ' || fp_flagid ||
                                ' insert scanflag ' ||
                                nvl(to_char(fp_scanid), 'NULL'),
                                fp_debuglevel,
                                fp_logname,
                                fp_plantid_param,
                                1,
                                1);
      end if;
    end if; --lvcounter
    return flaginserted;
  exception
    when dup_val_on_index then
      return flaginserted;
      --does not matter when flag already exist
    when others then
      pack_sort.write_logging('PACK_SORT.CREATE_UNIQUEITEMFLAG !> create flagid ' ||
                              fp_flagid || ' for uniqueitemid ' ||
                              fp_uniqueitemid || ' ' || sqlerrm,
                              fp_debuglevel,
                              fp_logname,
                              fp_plantid_param,
                              3,
                              1);
      return flaginserted;
  end create_uniqueitemflag;

  function process_plpctreatmntcheckschm(fp_plpcid                     in productlistpercustomer.productlistpercustomer_id%type,
                                         fp_checkpercentage            in treatmentcheckschemedetail.checkpercentage%type,
                                         fp_treatmentchkschemedetailid in plpctreatmentcheckscheme.treatmentcheckschemedetail_id%type,
                                         fp_systemuserid               in systemuser.systemuser_id%type)
    return plpctreatmentcheckscheme.factor%type is
    lv_plpc_treat_factor plpctreatmentcheckscheme.factor%type;
  begin
    --get factor
    select pt.factor + (fp_checkpercentage / 100)
      into lv_plpc_treat_factor
      from plpctreatmentcheckscheme pt
     where pt.treatmentcheckschemedetail_id = fp_treatmentchkschemedetailid
       and pt.productlistpercustomer_id = fp_plpcid;
    --check if update is needed
    if lv_plpc_treat_factor > 1 then
      update plpctreatmentcheckscheme pt
         set pt.factor        = lv_plpc_treat_factor - 1,
             pt.systemuser_id = fp_systemuserid,
             pt.timestamp     = sysdate
       where pt.treatmentcheckschemedetail_id =
             fp_treatmentchkschemedetailid
         and pt.productlistpercustomer_id = fp_plpcid;
    else
      update plpctreatmentcheckscheme pt
         set pt.factor        = lv_plpc_treat_factor,
             pt.systemuser_id = fp_systemuserid,
             pt.timestamp     = sysdate
       where pt.treatmentcheckschemedetail_id =
             fp_treatmentchkschemedetailid
         and pt.productlistpercustomer_id = fp_plpcid;
    end if;
    return lv_plpc_treat_factor;
  exception
    when no_data_found then
      begin
        lv_plpc_treat_factor := (fp_checkpercentage / 100);
        insert into plpctreatmentcheckscheme
          (treatmentcheckschemedetail_id,
           productlistpercustomer_id,
           factor,
           systemuser_id,
           timestamp)
        values
          (fp_treatmentchkschemedetailid,
           fp_plpcid,
           lv_plpc_treat_factor,
           fp_systemuserid,
           sysdate);
        return lv_plpc_treat_factor;
      end;
  end process_plpctreatmntcheckschm;
  procedure add_treatmentcheck_flags(fp_debuglevel             in integer,
                                     fp_systemuserid           in systemuser.systemuser_id%type,
                                     fp_uniqueitemid           in uniqueitem.uniqueitem_id%type,
                                     fp_startdate              in uniqueitemflag.startdate%type default sysdate,
                                     fp_scanid                 in scan.scan_id%type default null,
                                     fp_freetextitem           in uniqueitemflag.freetextitem%type default null,
                                     fp_treatmentcheckschemeid in out productlistpercustomer.treatmentcheckscheme_id%type,
                                     fp_nrofwashes             in number,
                                     fp_plantid_param          in plant.plant_id%type,
                                     fp_productid              in product.product_id%type,
                                     fp_plpcid                 in productlistpercustomer.productlistpercustomer_id%type) is
    lv_plpc_treat_factor plpctreatmentcheckscheme.factor%type;
    flaginserted         boolean;
  begin
    --if fp_treatmentcheckid is null try to get it on another level
    if fp_treatmentcheckschemeid is null then
      begin
        begin
          select ps.treatmentcheckscheme_id
            into fp_treatmentcheckschemeid
            from plantproductsettings ps
           where ps.plant_id = fp_plantid_param
             and ps.product_id = fp_productid;
        exception
          when no_data_found then
            fp_treatmentcheckschemeid := null;
        end;
        if fp_treatmentcheckschemeid is null then
          begin
            select p.treatmentcheckscheme_id
              into fp_treatmentcheckschemeid
              from product p
             where p.product_id = fp_productid;
          end;
        end if;
      end;
    end if; --fp_treatmentcheckid is null
    --fp_treatmentcheckid is not null then check for flags
    if fp_treatmentcheckschemeid is not null then
      begin
        --0 = Fixed  1 = Repeated
        for x in (select tsd.flag_id,
                         tsd.checkpercentage,
                         tsd.treatmentcheckschemedetail_id,
                         tsd.treatmenttype_id
                    from treatmentcheckschemedetail tsd
                   where tsd.treatmentcheckscheme_id =
                         fp_treatmentcheckschemeid
                     and ((tsd.schemetype = 0 and tsd.washes = fp_nrofwashes) or
                         (tsd.schemetype = 1 and
                         fp_nrofwashes between tsd.fromwashes and
                         tsd.towashes and
                         (mod((fp_nrofwashes - tsd.fromwashes),
                                tsd.repeatwashes) = 0)))) loop
          begin
            if x.checkpercentage = 100 then
              lv_plpc_treat_factor := 1;
            else
              begin
                --get current factor
                lv_plpc_treat_factor := process_plpctreatmntcheckschm(fp_plpcid,
                                                                      x.checkpercentage,
                                                                      fp_treatmentcheckschemeid,
                                                                      fp_systemuserid);
              end;
            end if;
            if lv_plpc_treat_factor >= 1 then
              flaginserted := create_uniqueitemflag('PACK_SORT.ADD_TREATMENTCHECK_FLAGS',
                                                    fp_debuglevel,
                                                    fp_systemuserid,
                                                    fp_uniqueitemid,
                                                    x.flag_id,
                                                    fp_startdate,
                                                    fp_scanid,
                                                    fp_freetextitem,
                                                    x.treatmenttype_id,
                                                    fp_plantid_param);
            end if;
          end;
        end loop; --x
      end;
    end if;
  end add_treatmentcheck_flags;
  --end 502877
  procedure findplpcinfo(fp_customerid             in customer.customer_id%type,
                         fp_productid              in product.product_id%type,
                         fp_sizedefinitionid       in sizedefinition.sizedefinition_id%type,
                         fp_finishingmethodid      in finishingmethod.finishingmethod_id%type,
                         fp_deliverymethod         out integer,
                         fp_deedeliveryschemeid    out deliveryscheme.deliveryscheme_id%type,
                         fp_plpcid                 out productlistpercustomer.productlistpercustomer_id%type,
                         fp_maxwashes              out integer,
                         fp_plpcfinishingcode      out productlistpercustomer.finishingcode_id%type,
                         fp_plpcustomcode          out productlistpercustomer.customcode%type,
                         fp_plpcustomdescription   out productlistpercustomer.customdescription%type,
                         fp_chargewashesonlyforcog out varchar2,
                         fp_pbillingmethod         out productlistpercustomer.billingmethod%type,
                         fp_treatmentschemeid      out productlistpercustomer.treatmentcheckscheme_id%type) is
    lv_chargewashesonlyforcog productlistpercustomer.chargewashesonlyforcog%type;
  begin
    begin
      --find plpc for right size
      select p.productlistpercustomer_id,
             p.maxwashes,
             p.delayedevenexchange,
             p.deedeliveryscheme_id,
             p.finishingcode_id,
             p.customcode,
             p.customdescription,
             p.chargewashesonlyforcog,
             p.billingmethod,
             p.treatmentcheckscheme_id
        into fp_plpcid,
             fp_maxwashes,
             fp_deliverymethod,
             fp_deedeliveryschemeid,
             fp_plpcfinishingcode,
             fp_plpcustomcode,
             fp_plpcustomdescription,
             lv_chargewashesonlyforcog,
             fp_pbillingmethod,
             fp_treatmentschemeid
        from productlistpercustomer p
       where p.customer_id = fp_customerid
         and p.product_id = fp_productid
         and p.sizedefinition_id = fp_sizedefinitionid
         and p.finishingmethod_id = fp_finishingmethodid
         and sysdate between p.dateactive and p.dateinactive;
    exception
      when no_data_found then
        begin
          --when not found find for size *
          select p.productlistpercustomer_id,
                 p.maxwashes,
                 p.delayedevenexchange,
                 p.deedeliveryscheme_id,
                 p.finishingcode_id,
                 p.customcode,
                 p.customdescription,
                 p.chargewashesonlyforcog,
                 p.billingmethod,
                 p.treatmentcheckscheme_id
            into fp_plpcid,
                 fp_maxwashes,
                 fp_deliverymethod,
                 fp_deedeliveryschemeid,
                 fp_plpcfinishingcode,
                 fp_plpcustomcode,
                 fp_plpcustomdescription,
                 lv_chargewashesonlyforcog,
                 fp_pbillingmethod,
                 fp_treatmentschemeid
            from productlistpercustomer p
           where p.customer_id = fp_customerid
             and p.product_id = fp_productid
             and p.sizedefinition_id = gv_specialsizeid -->size star
             and p.finishingmethod_id = fp_finishingmethodid
             and sysdate between p.dateactive and p.dateinactive;
        exception
          when no_data_found then
            fp_deliverymethod := 1;
        end;
    end;
    --todo24970 do not change fp_deliverymethod when 0 to 1
    --order501280
    if fp_deliverymethod = 7 and fp_deedeliveryschemeid is null then
      fp_deliverymethod := 1;
    end if;
    --501875
    if lv_chargewashesonlyforcog in (1, 3) then
      fp_chargewashesonlyforcog := 'Y';
    else
      fp_chargewashesonlyforcog := 'N';
    end if;
  end findplpcinfo;
  function getdeliveryweeksforyear(year      in integer,
                                   frequency in integer,
                                   offset    in integer) return deliveryweeks is
    delweeks       deliveryweeks;
    countdelweeks  integer;
    firstweek      integer;
    w              integer;
    wb             integer;
    currentdelweek integer;
    i              integer;
  begin
    firstweek      := getfirstdeliveryweekforyear(year, frequency, offset);
    w              := getweeksinyear(year);
    currentdelweek := firstweek;
    wb             := firstweek - frequency;
    i              := 1;
    while (wb > 0) loop
      begin
        delweeks(i) := wb;
        i := i + 1;
        wb := wb - frequency;
      end;
    end loop;
    countdelweeks := i;
    delweeks(countdelweeks) := currentdelweek;
    while (currentdelweek <= w) loop
      begin
        currentdelweek := currentdelweek + frequency;
        if (currentdelweek <= w) then
          begin
            countdelweeks := countdelweeks + 1;
            delweeks(countdelweeks) := currentdelweek;
          end;
        end if;
      end;
    end loop;
    return(delweeks);
  end getdeliveryweeksforyear;
  procedure getnextdeliveryweek(deliveryschemeid in deliveryscheme.deliveryscheme_id%type,
                                dayno            in day.day_id%type,
                                currentdate      in date,
                                nextdeliveryweek out integer,
                                nextdeliveryyear out integer) is
    --Result       date;
    currentweek  integer;
    currentyear  integer;
    currentday   integer;
    weeksinyear  integer;
    compareweek  integer;
    compareyear  integer;
    nextdelweekv integer;
    frequency    integer;
    offsetweek   integer;
    v            deliveryweeks;
    countv       integer;
  begin
    currentweek := getisoweek(currentdate);
    currentday  := getabsdaynumber(currentdate);
    currentyear := getyearofweek(currentdate);
    weeksinyear := getweeksinyear(currentyear);
    --  //determine comparation week and year depanding on the current date and selected visit day
    if currentday > dayno then
      compareweek := currentweek + 1;
    else
      compareweek := currentweek;
    end if;
    if (compareweek > weeksinyear) then
      begin
        compareweek := 1;
        compareyear := currentyear + 1;
      end;
    else
      compareyear := currentyear;
    end if;
    select d.frequency, d.offsetweek
      into frequency, offsetweek
      from deliveryscheme d
     where d.deliveryscheme_id = deliveryschemeid;
    --  get delivery weeks for compare year and selected delivery scheme
    v      := pack_sort.getdeliveryweeksforyear(compareyear,
                                                frequency,
                                                offsetweek);
    countv := v.count;
    --  if no delivery weeks found for current year get delivery weeks for next year
    if countv = 0 then
      begin
        compareyear := compareyear + 1;
        compareweek := 1;
        v           := pack_sort.getdeliveryweeksforyear(compareyear,
                                                         frequency,
                                                         offsetweek);
      end;
    end if;
    -- //determine next delivery week
    for i in v.first .. v.last loop
      if v(i) = compareweek then
        begin
          nextdelweekv := compareweek;
          exit;
        end;
      else
        nextdelweekv := 0;
      end if;
    end loop;
    if nextdelweekv = 0 then
      while (compareweek < weeksinyear) loop
        begin
          compareweek := compareweek + 1;
          for i in v.first .. v.last loop
            if v(i) = compareweek then
              begin
                nextdelweekv := compareweek;
                exit;
              end;
            else
              nextdelweekv := 0;
            end if;
          end loop;
          if nextdelweekv > 0 then
            exit;
          end if;
        end;
      end loop;
    end if;
    -- //if there is no next delivery week this year then det delivery week from next year
    if nextdelweekv = 0 then
      begin
        compareyear := compareyear + 1;
        compareweek := 1;
        v           := pack_sort.getdeliveryweeksforyear(compareyear,
                                                         frequency,
                                                         offsetweek);
        for i in v.first .. v.last loop
          if v(i) = compareweek then
            begin
              nextdelweekv := compareweek;
              exit;
            end;
          end if;
        end loop;
      end;
    end if;
    --  //if there is a next delivery week this year or next year then add it in the hash map
    if (nextdelweekv > 0) then
      nextdeliveryweek := nextdelweekv;
      nextdeliveryyear := compareyear;
    else
      nextdeliveryweek := 0;
      nextdeliveryyear := 0;
    end if;
  end getnextdeliveryweek;
  function getvisitdate(deliveryschemeid in deliveryscheme.deliveryscheme_id%type,
                        dayno            in day.day_id%type,
                        currentdate      in date) return date is
    result           date;
    nextdeliveryweek integer;
    nextdeliveryyear integer;
  begin
    pack_sort.getnextdeliveryweek(deliveryschemeid,
                                  dayno,
                                  currentdate,
                                  nextdeliveryweek,
                                  nextdeliveryyear);
    if (nextdeliveryweek > 0) then
      result := getdateforweekyear(dayno,
                                   nextdeliveryweek,
                                   nextdeliveryyear);
    else
      return null;
    end if;
    return(result);
  end getvisitdate;
  function getnextdeliverydate(currentdate in date,
                               customerid  in customer.customer_id%type,
                               typeofmerch in product.typeofmerchandise%type)
    return date is
    result    date;
    visitdate date;
    dates     visitdates;
    i         integer;
  begin
    i := 1;
    for vcursor in (select c.day_id, d.deliveryscheme_id, x.frequency
                      from customerdeliveryday    c,
                           customerdeliveryscheme d,
                           deliveryscheme         x
                     where c.customer_id = customerid
                       and c.customer_id = d.customer_id
                       and c.day_id = d.day_id
                       and c.typeofmerchadise = typeofmerch
                       and c.deliverytype in ('B', 'D')
                       and d.deliveryscheme_id = x.deliveryscheme_id
                       and d.active = 'Y') loop
      begin
        visitdate := pack_sort.getvisitdate(vcursor.deliveryscheme_id,
                                            vcursor.day_id,
                                            currentdate);
        if visitdate is not null then
          begin
            dates(to_char(visitdate, 'YYYYMMDD')) := i;
            i := i + 1;
          end;
        end if;
      end;
    end loop;
    result := to_date(dates.first, 'YYYYMMDD');
    return(result);
  end getnextdeliverydate;
  function getroutestopforcustomer(plantid_garment in plant.plant_id%type,
                                   visitdate       in date,
                                   customerid      in customer.customer_id%type,
                                   deliverypointid in integer) return integer is
    result   integer; --routestops;
    year     integer;
    week     integer;
    routeday integer;
    i        integer;
    aux      integer;
  begin
    select count(d.routestop_id)
      into aux
      from deliveryschemesperstop d
     where d.customer_id = customerid;
    if aux > 0 then
      year     := getyearofweek(visitdate);
      week     := getisoweek(visitdate);
      routeday := getabsdaynumber(visitdate);
      aux      := deliverypointid;
      i        := 0;
      result   := null;
      while i = 0 loop
        begin
          for vcursor in (select d.deliveryscheme_id,
                                 d.frequency,
                                 d.offsetweek
                            from customerdeliveryscheme c, deliveryscheme d
                           where c.customer_id = customerid
                             and c.day_id = routeday
                             and c.deliveryscheme_id = d.deliveryscheme_id
                             and c.active = 'Y'
                           order by d.frequency asc) loop
            if isweekdeliveryweek(year,
                                  week,
                                  vcursor.frequency,
                                  vcursor.offsetweek) then
              begin
                if aux is not null then
                  begin
                    select min(rs.routestop_id)
                      into result
                      from route r, routestop rs
                     where r.route_id = rs.route_id
                       and r.plant_id = plantid_garment
                       and r.drivingday_id = routeday
                          -- and    rs.dateactive <= trunc(sysdate) -- order 502746
                       and trunc(sysdate) < trunc(rs.dateinactive)
                       and trunc(visitdate) < trunc(rs.dateinactive)
                       and exists
                     (select d.routestop_id
                              from deliveryschemesperstop d
                             where d.customer_id = customerid
                               and d.deliveryscheme_id =
                                   vcursor.deliveryscheme_id
                               and d.day_id = routeday
                               and d.routestop_id = rs.routestop_id)
                       and rs.deliverypoint_id = aux;
                    if result is not null then
                      i := i + 1;
                    end if;
                  exception
                    when no_data_found then
                      result := 0;
                  end;
                else
                  begin
                    select min(rs.routestop_id)
                      into result
                      from route r, routestop rs
                     where r.route_id = rs.route_id
                       and r.plant_id = plantid_garment
                       and r.drivingday_id = routeday
                       and trunc(sysdate) < trunc(rs.dateinactive)
                       and trunc(visitdate) < trunc(rs.dateinactive)
                       and exists
                     (select d.routestop_id
                              from deliveryschemesperstop d
                             where d.customer_id = customerid
                               and d.deliveryscheme_id =
                                   vcursor.deliveryscheme_id
                               and d.day_id = routeday
                               and d.routestop_id = rs.routestop_id);
                    -- and    rs.deliverypoint_id is null;  -- issue ABS-46343
                    if result is not null then
                      i := i + 1;
                    end if;
                  exception
                    when no_data_found then
                      result := 0;
                  end;
                end if;
                if result is not null then
                  exit;
                end if;
              end;
            end if;
          end loop;
          if i = 0 then
            if deliverypointid is not null and aux is not null then
              aux := null;
            else
              i := i + 1;
            end if;
          end if;
        end;
      end loop;
    end if;
    return(result);
  exception
    when others then
      null;
  end getroutestopforcustomer;
  procedure getlastinroute(customerid      in customer.customer_id%type,
                           datex           in date,
                           deliverypointid in deliverypoint.deliverypoint_id%type,
                           typeofmerch     in product.typeofmerchandise%type,
                           lastinroute     out route.route_id%type,
                           routestopx      out routestop.routestop_id%type,
                           lastindate      out date) is
    startyear        integer;
    year             integer;
    dayx             integer;
    week             integer;
    cnt              integer;
    vdeliverypointid deliverypoint.deliverypoint_id%type;
  begin
    select count(d.routestop_id)
      into cnt
      from deliveryschemesperstop d
     where d.customer_id = customerid;
    if cnt > 0 then
      vdeliverypointid := deliverypointid;
      startyear        := getyearofweek(datex);
      dayx             := getabsdaynumber(datex);
      week             := getisoweek(datex);
      lastindate       := datex;
      while dayx <> 0 loop
        begin
          for vcursor in (select ds.routestop_id,
                                 c.day_id,
                                 ds.deliveryscheme_id,
                                 x.frequency,
                                 x.offsetweek offset
                            from customerdeliveryday    c,
                                 routestop              rs,
                                 deliveryschemesperstop ds,
                                 deliveryscheme         x
                           where ds.customer_id = customerid
                             and ds.customer_id = c.customer_id
                             and c.typeofmerchadise = typeofmerch
                             and ds.routestop_id = rs.routestop_id
                             and ---
                                 (rs.deliverypoint_id = vdeliverypointid or
                                 rs.deliverypoint_id is null)
                             and ---
                                 c.day_id = dayx
                             and ds.day_id = c.day_id
                             and ds.deliveryscheme_id = x.deliveryscheme_id
                             and trunc(RS.Dateactive) <= lastindate
                             and trunc(RS.Dateinactive) > lastindate) loop
            begin
              if isweekdeliveryweek(year,
                                    week,
                                    vcursor.frequency,
                                    vcursor.offset) then
                begin
                  routestopx := vcursor.routestop_id;
                  dayx       := 0;
                  exit;
                end;
              end if;
            end;
          end loop;
          if routestopx is null then
            begin
              lastindate := lastindate - 1;
              dayx       := getabsdaynumber(lastindate);
              week       := getisoweek(lastindate);
              year       := getyearofweek(lastindate);
              if year < (startyear - 2) then
                dayx       := 0;
                lastindate := datex;
              end if;
            end;
          end if;
        end;
      end loop;
      select route_id
        into lastinroute
        from routestop
       where routestop_id = routestopx;
    end if;
  exception
    when others then
      null;
  end getlastinroute;
  procedure fillplannedoutroute(plantid_garment     in plant.plant_id%type,
                                currentdate         in date,
                                typeofmerch         in product.typeofmerchandise%type,
                                deliverymethod      in integer,
                                deedeliveryschemeid in deliveryscheme.deliveryscheme_id%type,
                                plpcid              in productlistpercustomer.productlistpercustomer_id%type,
                                customerid          in customer.customer_id%type,
                                deliverypointid     in deliverypoint.deliverypoint_id%type,
                                lastinroute         in route.route_id%type,
                                lastindate          in date,
                                routestopin         in routestop.routestop_id%type,
                                routestopid         out routestop.routestop_id%type,
                                routeid             out route.route_id%type,
                                plannedoutdate      out date,
                                scanbyroute         in varchar2) is
    dates             visitdates;
    returnrouteid     route.route_id%type;
    movedroutestopid  routestop.routestop_id%type;
    routedayp         integer;
    i                 integer;
    ii                integer;
    j                 integer;
    startdate         date;
    vdeliverypointid  deliverypoint.deliverypoint_id%type;
    deliverydays_us   varchar2(1);
    currentweek       integer;
    currentday        integer;
    nextdeliveryweek  integer;
    nextdeliveryyear  integer;
    dayid             integer;
    routestopactive   routestop.routestop_id%type;
    lv_deliverymethod integer;
  begin
    if deliverymethod = 8 then
      startdate := currentdate;
    else
      startdate := currentdate + 1; --todo4313
    end if;
    i                := 0;
    j                := 0;
    vdeliverypointid := deliverypointid;
    if typeofmerch = 2 then
      ii := 15;
    else
      ii := 30;
    end if;
    --todo24970 replace 0 with 1, use new variable to do this
    if deliverymethod in (1, 2, 3, 4, 5, 6, 7) then
      lv_deliverymethod := deliverymethod;
    else
      lv_deliverymethod := 1;
    end if;
    case lv_deliverymethod
      when 1 then
        --determine the first route when the customer is visited starting from today
        begin
          while j < 2 loop
            while i < ii loop
              plannedoutdate := pack_sort.getnextdeliverydate(startdate,
                                                              customerid,
                                                              typeofmerch);
              if plannedoutdate is null then
                plannedoutdate := lastindate + 7;
              end if;
              --todo3394
              if scanbyroute <> 'Y' then
                exit;
              end if;
              routestopid := pack_sort.getroutestopforcustomer(plantid_garment,
                                                               plannedoutdate,
                                                               customerid,
                                                               vdeliverypointid);
              if routestopid is null --and plannedoutdate is not null
               then
                i         := i + 1;
                startdate := plannedoutdate + 1;
              else
                i := ii;
              end if;
            end loop;
            if routestopid is null then
              vdeliverypointid := null;
              i                := 1;
              j                := j + 1;
            else
              j := 2;
            end if;
          end loop;
          select route_id
            into routeid
            from routestop s
           where s.routestop_id = routestopid;
        exception
          when no_data_found then
            begin
              routeid     := lastinroute;
              routestopid := routestopin;
            end;
        end;
      when 2 then
        begin
          --use the same route as the route of the item was brought in
          routeid        := lastinroute;
          plannedoutdate := lastindate + 7;
          routestopid    := routestopin;
          begin
            select s.routestop_id
              into routestopactive
              from routestop s
             where trunc(s.dateinactive) > trunc(plannedoutdate)
               and s.routestop_id = routestopid;
          exception
            when no_data_found then
              routestopactive := null;
          end;
          if (routestopactive is null) then
            begin
              select s.movedroutestop_id
                into movedroutestopid
                from routestop s
               where trunc(s.dateinactive) > trunc(plannedoutdate)
                 and s.routestop_id = routestopid;
            exception
              when no_data_found then
                movedroutestopid := null;
            end;
            if (movedroutestopid is null) then
              pack_sort.fillplannedoutroute(plantid_garment,
                                            plannedoutdate,
                                            typeofmerch,
                                            1,
                                            deedeliveryschemeid,
                                            plpcid,
                                            customerid,
                                            deliverypointid,
                                            lastinroute,
                                            lastindate,
                                            routestopin,
                                            routestopid,
                                            routeid,
                                            plannedoutdate,
                                            scanbyroute);
            else
              pack_sort.fillplannedoutroute(plantid_garment,
                                            plannedoutdate,
                                            typeofmerch,
                                            deliverymethod,
                                            deedeliveryschemeid,
                                            plpcid,
                                            customerid,
                                            deliverypointid,
                                            lastinroute,
                                            lastindate,
                                            movedroutestopid,
                                            routestopid,
                                            routeid,
                                            plannedoutdate,
                                            scanbyroute);
            end if;
          end if;
        end;
      when 3 then
        --same as 2
        begin
          dbms_output.put_line('plpc FOUND 3');
          routeid        := lastinroute;
          plannedoutdate := lastindate + 7;
          routestopid    := routestopin;
          begin
            select s.routestop_id
              into routestopactive
              from routestop s
             where trunc(s.dateinactive) > trunc(plannedoutdate)
               and s.routestop_id = routestopid;
          exception
            when no_data_found then
              routestopactive := null;
          end;
          if (routestopactive is null) then
            begin
              select s.movedroutestop_id
                into movedroutestopid
                from routestop s
               where trunc(s.dateinactive) > trunc(plannedoutdate)
                 and s.routestop_id = routestopid;
            exception
              when no_data_found then
                movedroutestopid := null;
            end;
            if (movedroutestopid is null) then
              pack_sort.fillplannedoutroute(plantid_garment,
                                            plannedoutdate,
                                            typeofmerch,
                                            1,
                                            deedeliveryschemeid,
                                            plpcid,
                                            customerid,
                                            deliverypointid,
                                            lastinroute,
                                            lastindate,
                                            routestopin,
                                            routestopid,
                                            routeid,
                                            plannedoutdate,
                                            scanbyroute);
            else
              pack_sort.fillplannedoutroute(plantid_garment,
                                            plannedoutdate,
                                            typeofmerch,
                                            deliverymethod,
                                            deedeliveryschemeid,
                                            plpcid,
                                            customerid,
                                            deliverypointid,
                                            lastinroute,
                                            lastindate,
                                            movedroutestopid,
                                            routestopid,
                                            routeid,
                                            plannedoutdate,
                                            scanbyroute);
            end if;
          end if;
        end;
      when 4 then
        begin
          begin
            select s.returnroute_id
              into returnrouteid
              from routestop s, route returnroute
             where returnroute.route_id = s.returnroute_id
               and returnroute.plant_id = plantid_garment
               and s.customer_id = customerid
               and s.route_id = lastinroute
               and s.routestop_id = routestopin;
          exception
            when no_data_found then
              returnrouteid := null;
          end;
          if routestopin is not null then

            if vdeliverypointid is not null then
              begin
                select min(routestop_id)
                  into routestopid
                  from routestop
                 where routestop.route_id = returnrouteid
                   and routestop.customer_id = customerid
                   and trunc(routestop.dateinactive) > trunc(startdate)
                   and routestop.deliverypoint_id = vdeliverypointid;
              exception
                when no_data_found then
                  routestopid := null;
              end;
            end if;
            if routestopid is null then
              select min(routestop_id)
                into routestopid
                from routestop
               where routestop.route_id = returnrouteid
                 and trunc(routestop.dateinactive) > trunc(startdate)
                 and routestop.customer_id = customerid
               order by stopnumber;
            end if;
          end if;
          if returnrouteid is null then
            begin
              routeid        := lastinroute;
              plannedoutdate := lastindate + 7;
              routestopid    := routestopin;
              begin
                select s.routestop_id
                  into routestopactive
                  from routestop s
                 where trunc(s.dateinactive) > trunc(plannedoutdate)
                   and s.routestop_id = routestopid;
              exception
                when no_data_found then
                  routestopactive := null;
              end;
              if (routestopactive is null) then
                begin
                  select s.movedroutestop_id
                    into movedroutestopid
                    from routestop s
                   where trunc(s.dateinactive) > trunc(plannedoutdate)
                     and s.routestop_id = routestopid;
                exception
                  when no_data_found then
                    movedroutestopid := null;
                end;
                if (movedroutestopid is null) then
                  pack_sort.fillplannedoutroute(plantid_garment,
                                                plannedoutdate,
                                                typeofmerch,
                                                1,
                                                deedeliveryschemeid,
                                                plpcid,
                                                customerid,
                                                deliverypointid,
                                                lastinroute,
                                                lastindate,
                                                routestopin,
                                                routestopid,
                                                routeid,
                                                plannedoutdate,
                                                scanbyroute);
                else
                  pack_sort.fillplannedoutroute(plantid_garment,
                                                plannedoutdate,
                                                typeofmerch,
                                                deliverymethod,
                                                deedeliveryschemeid,
                                                plpcid,
                                                customerid,
                                                deliverypointid,
                                                lastinroute,
                                                lastindate,
                                                movedroutestopid,
                                                routestopid,
                                                routeid,
                                                plannedoutdate,
                                                scanbyroute);
                end if;
              end if;
            end;
          else
            begin
              select r.drivingday_id
                into routedayp
                from route r
               where r.route_id = returnrouteid;
              i := 1;
              for vcursor in (select s.day_id,
                                     s.deliveryscheme_id,
                                     s.routestop_id
                                from deliveryschemesperstop s
                               where s.customer_id = customerid
                                 and s.day_id = routedayp
                                 and s.routestop_id = routestopid) loop
                begin
                  plannedoutdate := pack_sort.getvisitdate(vcursor.deliveryscheme_id,
                                                           routedayp,
                                                           startdate);
                  if plannedoutdate is not null then
                    begin
                      select s.routestop_id
                        into routestopactive
                        from routestop s
                       where trunc(s.dateinactive) > trunc(plannedoutdate)
                         and s.routestop_id = routestopid;
                    exception
                      when no_data_found then
                        routestopactive := null;
                    end;
                    if (routestopactive is not null) then
                      dates(to_char(plannedoutdate, 'YYYYMMDD')) := i;
                      i := i + 1;
                    end if;
                  end if;
                end;
              end loop;
              plannedoutdate := to_date(dates.first, 'YYYYMMDD');
              routeid        := returnrouteid;
            end;
          end if;
        end;
      when 5 then
        --same as 2 - but 14 days -order501096
        begin
          dbms_output.put_line('plpc FOUND 3');
          routeid        := lastinroute;
          plannedoutdate := lastindate + 14;
          routestopid    := routestopin;
          begin
            select s.routestop_id
              into routestopactive
              from routestop s
             where trunc(s.dateinactive) > trunc(plannedoutdate)
               and s.routestop_id = routestopid;
          exception
            when no_data_found then
              routestopactive := null;
          end;
          if (routestopactive is null) then
            begin
              select s.movedroutestop_id
                into movedroutestopid
                from routestop s
               where trunc(s.dateinactive) > trunc(plannedoutdate)
                 and s.routestop_id = routestopid;
            exception
              when no_data_found then
                movedroutestopid := null;
            end;
            if (movedroutestopid is null) then
              pack_sort.fillplannedoutroute(plantid_garment,
                                            plannedoutdate,
                                            typeofmerch,
                                            1,
                                            deedeliveryschemeid,
                                            plpcid,
                                            customerid,
                                            deliverypointid,
                                            lastinroute,
                                            lastindate,
                                            routestopin,
                                            routestopid,
                                            routeid,
                                            plannedoutdate,
                                            scanbyroute);
            else
              pack_sort.fillplannedoutroute(plantid_garment,
                                            plannedoutdate,
                                            typeofmerch,
                                            deliverymethod,
                                            deedeliveryschemeid,
                                            plpcid,
                                            customerid,
                                            deliverypointid,
                                            lastinroute,
                                            lastindate,
                                            movedroutestopid,
                                            routestopid,
                                            routeid,
                                            plannedoutdate,
                                            scanbyroute);
            end if;
          end if;
        end;
      when 6 then
        --same as 2 -but 28 days -order501096
        begin
          dbms_output.put_line('plpc FOUND 3');
          routeid        := lastinroute;
          plannedoutdate := lastindate + 28;
          routestopid    := routestopin;
          begin
            select s.routestop_id
              into routestopactive
              from routestop s
             where trunc(s.dateinactive) > trunc(plannedoutdate)
               and s.routestop_id = routestopid;
          exception
            when no_data_found then
              routestopactive := null;
          end;
          if (routestopactive is null) then
            begin
              select s.movedroutestop_id
                into movedroutestopid
                from routestop s
               where trunc(s.dateinactive) > trunc(plannedoutdate)
                 and s.routestop_id = routestopid;
            exception
              when no_data_found then
                movedroutestopid := null;
            end;
            if (movedroutestopid is null) then
              pack_sort.fillplannedoutroute(plantid_garment,
                                            plannedoutdate,
                                            typeofmerch,
                                            1,
                                            deedeliveryschemeid,
                                            plpcid,
                                            customerid,
                                            deliverypointid,
                                            lastinroute,
                                            lastindate,
                                            routestopin,
                                            routestopid,
                                            routeid,
                                            plannedoutdate,
                                            scanbyroute);
            else
              pack_sort.fillplannedoutroute(plantid_garment,
                                            plannedoutdate,
                                            typeofmerch,
                                            deliverymethod,
                                            deedeliveryschemeid,
                                            plpcid,
                                            customerid,
                                            deliverypointid,
                                            lastinroute,
                                            lastindate,
                                            movedroutestopid,
                                            routestopid,
                                            routeid,
                                            plannedoutdate,
                                            scanbyroute);
            end if;
          end if;
        end;
      when 7 then
        --according with deliveryscheme - order501280
        begin
          begin
            select s.value
              into deliverydays_us
              from systemsetting s
             where s.plant_id = plantid_garment
               and s.name = 'DELIVERYDAYS_US';
          exception
            when no_data_found then
              deliverydays_us := 'N';
          end;
          currentweek := getisoweek(currentdate);
          currentday  := getabsdaynumber(currentdate);
          pack_sort.getnextdeliveryweek(deedeliveryschemeid,
                                        currentday,
                                        currentdate,
                                        nextdeliveryweek,
                                        nextdeliveryyear);
          if currentweek <> nextdeliveryweek then
            begin
              if deliverydays_us = 'Y' then
                --deliverydays US
                begin
                  select min(p.day_id)
                    into dayid
                    from productdeliveryday p
                   where p.productlistpercustomer_id = plpcid
                     and p.deliverytype in ('B', 'D');
                  plannedoutdate := getdateforweekyear(dayid,
                                                       nextdeliveryweek,
                                                       nextdeliveryyear);
                exception
                  when others then
                    plannedoutdate := null;
                end;
              else
                --deliverydays EU
                begin
                  select min(c.day_id)
                    into dayid
                    from customerdeliveryday c, customerdeliveryscheme d
                   where c.customer_id = customerid
                     and c.customer_id = d.customer_id
                     and c.day_id = d.day_id
                     and c.typeofmerchadise = typeofmerch
                     and d.deliveryscheme_id = deedeliveryschemeid
                     and d.active = 'Y';
                  plannedoutdate := getdateforweekyear(dayid,
                                                       nextdeliveryweek,
                                                       nextdeliveryyear);
                exception
                  when others then
                    plannedoutdate := null;
                end;
              end if;
            end;
          else
            if deliverydays_us = 'Y' then
              --deliverydays US
              begin
                select min(p.day_id)
                  into dayid
                  from productdeliveryday p
                 where p.productlistpercustomer_id = plpcid
                   and p.deliverytype in ('B', 'D')
                   and p.day_id > currentday;
                if dayid is not null then
                  plannedoutdate := getdateforweekyear(dayid,
                                                       nextdeliveryweek,
                                                       nextdeliveryyear);
                else
                  begin
                    pack_sort.getnextdeliveryweek(deedeliveryschemeid,
                                                  currentday,
                                                  currentdate + 7,
                                                  nextdeliveryweek,
                                                  nextdeliveryyear);
                    select min(p.day_id)
                      into dayid
                      from productdeliveryday p
                     where p.productlistpercustomer_id = plpcid
                       and p.deliverytype in ('B', 'D');
                    plannedoutdate := getdateforweekyear(dayid,
                                                         nextdeliveryweek,
                                                         nextdeliveryyear);
                  exception
                    when others then
                      plannedoutdate := null;
                  end;
                end if;
              end;
            else
              --deliverydays EU
              begin
                select min(c.day_id)
                  into dayid
                  from customerdeliveryday c, customerdeliveryscheme d
                 where c.customer_id = customerid
                   and c.customer_id = d.customer_id
                   and c.day_id = d.day_id
                   and c.typeofmerchadise = typeofmerch
                   and d.deliveryscheme_id = deedeliveryschemeid
                   and c.day_id > currentday
                   and d.active = 'Y';
                if dayid is not null then
                  plannedoutdate := getdateforweekyear(dayid,
                                                       nextdeliveryweek,
                                                       nextdeliveryyear);
                else
                  begin
                    pack_sort.getnextdeliveryweek(deedeliveryschemeid,
                                                  currentday,
                                                  currentdate + 7,
                                                  nextdeliveryweek,
                                                  nextdeliveryyear);
                    select min(c.day_id)
                      into dayid
                      from customerdeliveryday c, customerdeliveryscheme d
                     where c.customer_id = customerid
                       and c.customer_id = d.customer_id
                       and c.day_id = d.day_id
                       and c.typeofmerchadise = typeofmerch
                       and d.deliveryscheme_id = deedeliveryschemeid
                       and d.active = 'Y';
                    plannedoutdate := getdateforweekyear(dayid,
                                                         nextdeliveryweek,
                                                         nextdeliveryyear);
                  exception
                    when others then
                      plannedoutdate := null;
                  end;
                end if;
              end;
            end if;
          end if;
          if plannedoutdate is not null and scanbyroute = 'Y' then
            begin
              routestopid := pack_sort.getroutestopforcustomer(plantid_garment,
                                                               plannedoutdate,
                                                               customerid,
                                                               vdeliverypointid);
              if routestopid is null then
                vdeliverypointid := null;
                routestopid      := pack_sort.getroutestopforcustomer(plantid_garment,
                                                                      plannedoutdate,
                                                                      customerid,
                                                                      vdeliverypointid);
              end if;
              select route_id
                into routeid
                from routestop s
               where s.routestop_id = routestopid;
            exception
              when no_data_found then
                begin
                  routeid        := lastinroute;
                  plannedoutdate := lastindate + 7;
                  routestopid    := routestopin;

                  dayid := -1;
                  select r.drivingday_id
                    into dayid
                    from route r
                   where r.route_id = routeid;
                  if (dayid <> -1 and
                     dayid <> getabsdaynumber(plannedoutdate)) then
                    getnextdeliverydatewithstop(plannedoutdate,
                                                plantid_garment,
                                                customerid,
                                                typeofmerch,
                                                vdeliverypointid,
                                                plannedoutdate,
                                                routeid);
                  end if;
                exception
                  when no_data_found then
                    begin
                      routeid := null;
                    end;
                end;
            end;
          end if;
        end;
      else
        begin
          routeid        := lastinroute;
          plannedoutdate := lastindate + 7;
          routestopid    := routestopin;
        end;
    end case;
  end fillplannedoutroute;
  procedure getflags(uniqueitemid        in uniqueitem.uniqueitem_id%type,
                     plantid_param       in plant.plant_id%type,
                     wearerflagid        in flag.flag_id%type,
                     wearerflagstartdate in date,
                     empflagid           in flag.flag_id%type,
                     empflagstartdate    in date,
                     languageid          in languages.language_id%type,
                     flagsusage          in integer,
                     flagcode1           out nocopy sortaddressperflag.sortaddress%type,
                     flagcode2           out nocopy sortaddressperflag.sortaddress%type,
                     flagcode3           out nocopy sortaddressperflag.sortaddress%type,
                     flagcode4           out nocopy sortaddressperflag.sortaddress%type,
                     flagdescription1    out nocopy flag_desc.description%type,
                     flagdescription2    out nocopy flag_desc.description%type,
                     flagdescription3    out nocopy flag_desc.description%type,
                     flagdescription4    out nocopy flag_desc.description%type,
                     flagsinfo           out nocopy varchar2, --300
                     destinationstring   out nocopy varchar2, --3
                     fp_kann_yes_no      in varchar2 default 'N', --Default N, options Y,N
                     fp_flag_freetext1   out nocopy uniqueitemflag.freetextitem%type,
                     fp_flag_freetext2   out nocopy uniqueitemflag.freetextitem%type,
                     fp_flag_freetext3   out nocopy uniqueitemflag.freetextitem%type,
                     fp_flag_freetext4   out nocopy uniqueitemflag.freetextitem%type) is
  begin
    getflags(uniqueitemid,
             plantid_param,
             wearerflagid,
             wearerflagstartdate,
             empflagid,
             empflagstartdate,
             languageid,
             flagsusage,
             flagcode1,
             flagcode2,
             flagcode3,
             flagcode4,
             flagdescription1,
             flagdescription2,
             flagdescription3,
             flagdescription4,
             flagsinfo,
             destinationstring,
             fp_kann_yes_no,
             fp_flag_freetext1,
             fp_flag_freetext2,
             fp_flag_freetext3,
             fp_flag_freetext4,
             fp_flag_freetext1,
             fp_flag_freetext2,
             fp_flag_freetext3,
             fp_flag_freetext4);

  end getflags;
  procedure getflags(uniqueitemid           in uniqueitem.uniqueitem_id%type,
                     plantid_param          in plant.plant_id%type,
                     wearerflagid           in flag.flag_id%type,
                     wearerflagstartdate    in date,
                     empflagid              in flag.flag_id%type,
                     empflagstartdate       in date,
                     languageid             in languages.language_id%type,
                     flagsusage             in integer,
                     flagcode1              out nocopy sortaddressperflag.sortaddress%type,
                     flagcode2              out nocopy sortaddressperflag.sortaddress%type,
                     flagcode3              out nocopy sortaddressperflag.sortaddress%type,
                     flagcode4              out nocopy sortaddressperflag.sortaddress%type,
                     flagdescription1       out nocopy flag_desc.description%type,
                     flagdescription2       out nocopy flag_desc.description%type,
                     flagdescription3       out nocopy flag_desc.description%type,
                     flagdescription4       out nocopy flag_desc.description%type,
                     flagsinfo              out nocopy varchar2, --300
                     destinationstring      out nocopy varchar2, --3
                     fp_kann_yes_no         in varchar2 default 'N', --Default N, options Y,N
                     fp_flag_freetext1      out nocopy uniqueitemflag.freetextitem%type,
                     fp_flag_freetext2      out nocopy uniqueitemflag.freetextitem%type,
                     fp_flag_freetext3      out nocopy uniqueitemflag.freetextitem%type,
                     fp_flag_freetext4      out nocopy uniqueitemflag.freetextitem%type,
                     flag_freetext1         out nocopy uniqueitemflag.freetextitem%type,
                     flag_freetext2         out nocopy uniqueitemflag.freetextitem%type,
                     flag_freetext3         out nocopy uniqueitemflag.freetextitem%type,
                     flag_freetext4         out nocopy uniqueitemflag.freetextitem%type,
                     ui_status_assigned     in varchar2 default 'N',
                     freetext2descriptionyn in varchar2 default 'Y',
                     metricon               in varchar2 default 'N') is
    cnt                 integer;
    checkpointscan      integer;
    inscan              integer;
    tempflags           flags;
    showalways          varchar2(1);
    confirm             varchar2(1);
    stringdate          varchar2(8);
    stringc             varchar2(21);
    flagid              flag.flag_id%type;
    flagid2             flag.flag_id%type;
    flagid3             flag.flag_id%type;
    flagid4             flag.flag_id%type;
    freetext            varchar2(80);
    flagstring          varchar2(10);
    xsortaddress        sortaddressperflag.sortaddress%type;
    sortadressperrc     sortaddressperreasoncode.sortaddress%type;
    sortadressperrcdesc reasoncode_desc.description%type;
    --flagsusage takes following values:
    --0 for determining Destinationstring,
    --4 for determining flagcode1...flagcode4,
    --100 for filling flagsinfo with all founded flags linked to a uniqueitem
  begin
    select dialog_id
      into inscan
      from dialogs
     where dialogs.code = 'InScan';
    select dialog_id
      into checkpointscan
      from dialogs
     where dialogs.code = 'CheckPointScan';
    cnt               := 0;
    destinationstring := '';
    flagsinfo         := '';
    for vcursor in (select b.startdate,
                           f.flag_id,
                           f.priority,
                           f.showalways,
                           f.code
                      from uniqueitemflag b, flag f
                     where b.uniqueitem_id = uniqueitemid
                       and b.flag_id = f.flag_id
                    union
                    select wearerflagstartdate startdate,
                           f.flag_id,
                           f.priority,
                           f.showalways,
                           f.code
                      from flag f
                     where f.flag_id = wearerflagid
                    union
                    select empflagstartdate startdate,
                           f.flag_id,
                           f.priority,
                           f.showalways,
                           f.code
                      from flag f
                     where f.flag_id = empflagid
                     minus
                     SELECT coalesce(uf.startdate, wearerflagstartdate, empflagstartdate),
                           f.flag_id,
                           f.priority,
                           f.showalways,
                           f.code
                       FROM PLANTFLAGOPTIONS, DIALOGS,
                            FLAG f left outer join uniqueitemflag uf  on (uf.flag_id = f.flag_id and uf.uniqueitem_id = uniqueitemid)

                        WHERE PLANTFLAGOPTIONS.FLAG_ID = f.FLAG_ID
                          AND PLANTFLAGOPTIONS.DIALOG_ID = (select d.dialog_id from dialogs d where d.code = 'CheckPointScan')
                          AND PLANTFLAGOPTIONS.PLANT_ID = plantid_param
                          AND PLANTFLAGOPTIONS.SHOW = 'N'
                          AND f.FLAGTYPE = 1
                          and ( f.flag_id = wearerflagid or uf.uniqueitem_id = uniqueitemid or f.flag_id = empflagid)
                          and metricon = 'Y'
            ) loop
      begin
        --first we check the plantflagoptions, if exist, ok use em.
        select decode(max(po.confirm), 'Y', '0', 'N', '1', '2')
          into confirm
          from plantflagoptions po
         where po.flag_id = vcursor.flag_id
           and po.plant_id = plantid_param
           and po.dialog_id in (inscan, checkpointscan)
           and po.show = 'Y';
        if nvl(confirm, '2') = '2' then
          --when confirm = 2 then no_data_found plantflagoptions, so check normal flagoptions
          select decode(max(o.confirm), 'Y', '0', 'N', '1', '2')
            into confirm
            from flagoptions o
           where o.flag_id = vcursor.flag_id
             and o.dialog_id in (inscan, checkpointscan)
             and o.show = 'Y';
        end if;
        if (vcursor.startdate <= sysdate) and confirm <> '2' then
          begin
            if vcursor.showalways = 'Y' then
              showalways := '0';
            else
              showalways := '1';
            end if;
            stringdate := to_char(vcursor.startdate, 'YYYYMMDD');
            flagstring := to_char(vcursor.flag_id);
            if (metricon = 'Y') then
              stringc := showalways || vcursor.priority || stringdate ||
                         flagstring; --string concatenat  dbms_output.put_line('string'||Stringc);
            else
              stringc := showalways || confirm || vcursor.priority ||
                         stringdate || flagstring; --string concatenat  dbms_output.put_line('string'||Stringc);
            end if;
            if tempflags.exists(stringc) then
              -- if combination of showalways/confirm/date exists already in the array
              begin
                flagid := tempflags(stringc);
                if flagid <> vcursor.flag_id then
                  --if flagID is NOT already stored in the array for the same combination of showalways/confirm/date then store it
                  tempflags(stringc) := vcursor.flag_id;
                  cnt := cnt + 1;
                end if;
              end;
            else
              -- if combination of showalways/confirm/date doesn't exists already in the array then add it
              tempflags(stringc) := vcursor.flag_id;
              cnt := cnt + 1;
            end if;
          end;
          if flagsusage = 0 then
            begin
              xsortaddress := '';
              select s.sortaddress
                into xsortaddress
                from sortaddressperflag s
               where s.flag_id = vcursor.flag_id
                 and s.plant_id = plantid_param;
              if xsortaddress is not null then
                destinationstring := substr(xsortaddress, 2, 2);
                -- end if;
                cnt := to_number(destinationstring);
                if cnt >= 0 then
                  destinationstring := substr(xsortaddress, 1, 3);
                  flagsinfo         := '';
                  exit;
                end if;
              end if;
            exception
              when others then
                destinationstring := '';
                flagsinfo         := '';
            end;
          end if;
          if flagsusage in (4, 100) then
            begin
              select fd.description
                into flagdescription1
                from flag_desc fd
               where fd.flag_id = vcursor.flag_id
                 and fd.language_id = languageid;
              flagsinfo := flagsinfo || vcursor.code || ':' ||
                           flagdescription1 || chr(13) || chr(10);
            exception
              when no_data_found then
                flagsinfo := flagsinfo || vcursor.code || ':' || chr(13) ||
                             chr(10);
            end;
            flagdescription1 := '';
          end if;
        end if;
      end;
    end loop;
    --added for order20011877
    begin
      if ui_status_assigned = 'Y' then
        select sarc.sortaddress, rsdesc.description
          into sortadressperrc, sortadressperrcdesc
          from uniqueitemfixedinfo      uif,
               sortaddressperreasoncode sarc,
               reasoncode               rs
          left outer join reasoncode_desc rsdesc
            on (rsdesc.reasoncode_id = rs.reasoncode_id and
               rsdesc.language_id = languageid)
         where uif.reasoncode_id = rs.reasoncode_id
           and rs.reasoncode_id = sarc.reasoncode_id
           and uif.uniqueitem_id = uniqueitemid
           and sarc.plant_id = plantid_param;
      end if;
    exception
      when others then
        sortadressperrc     := null;
        sortadressperrcdesc := null;
    end;
    --added for order501044
    if flagsusage = 4 then
      stringc := tempflags.first;
      if tempflags.exists(stringc) then
        cnt := 0;
        while stringc is not null loop
          begin
            if tempflags.exists(stringc) then
              cnt := cnt + 1;
              case cnt
                when 1 then
                  flagid := tempflags(stringc);
                when 2 then
                  flagid2 := tempflags(stringc);
                when 3 then
                  flagid3 := tempflags(stringc);
                when 4 then
                  flagid4 := tempflags(stringc);
              end case;
            end if;
            if cnt = 4 then
              exit;
            end if;
            stringc := tempflags.next(stringc); -- get subscript of next element
          end;
        end loop;
      end if; -- if tempflags.exists(stringc)
      if flagid > 0 then
        begin
          select s.sortaddress
            into flagcode1
            from sortaddressperflag s
           where s.flag_id = flagid
             and s.plant_id = plantid_param;
          begin
            select d.description
              into flagdescription1
              from flag_desc d
             where d.flag_id = flagid
               and d.language_id = languageid;
          exception
            when no_data_found then
              null;
          end;
          begin
            select u.freetextitem
              into freetext
              from uniqueitemflag u
             where u.flag_id = flagid
               and u.uniqueitem_id = uniqueitemid;
            flag_freetext1 := freetext;
            if length(freetext) > 0 and freetext2descriptionyn = 'Y' then
              begin
                if fp_kann_yes_no = 'Y' then
                  fp_flag_freetext1 := freetext;
                else
                  freetext         := flagdescription1 || ' ' || freetext;
                  flagdescription1 := substr(freetext, 1, 40);
                end if;
              end;
            end if;
          exception
            when no_data_found then
              null;
          end;
        exception
          when no_data_found then
            null;
        end;
      end if;
      if flagid2 > 0 then
        begin
          select s.sortaddress
            into flagcode2
            from sortaddressperflag s
           where s.flag_id = flagid2
             and s.plant_id = plantid_param;
          begin
            select d.description
              into flagdescription2
              from flag_desc d
             where d.flag_id = flagid2
               and d.language_id = languageid;
          exception
            when no_data_found then
              null;
          end;
          begin
            select u.freetextitem
              into freetext
              from uniqueitemflag u
             where u.flag_id = flagid2
               and u.uniqueitem_id = uniqueitemid;
            flag_freetext2 := freetext;
            if length(freetext) > 0 and freetext2descriptionyn = 'Y' then
              begin
                if fp_kann_yes_no = 'Y' then
                  fp_flag_freetext2 := freetext;
                else
                  freetext         := flagdescription2 || ' ' || freetext;
                  flagdescription2 := substr(freetext, 1, 40);
                end if;
              end;
            end if;
          exception
            when no_data_found then
              null;
          end;
        exception
          when no_data_found then
            null;
        end;
      end if; --end if flag2
      if flagid3 > 0 then
        begin
          select s.sortaddress
            into flagcode3
            from sortaddressperflag s
           where s.flag_id = flagid3
             and s.plant_id = plantid_param;
          begin
            select d.description
              into flagdescription3
              from flag_desc d
             where d.flag_id = flagid3
               and d.language_id = languageid;
          exception
            when no_data_found then
              null;
          end;
          begin
            select u.freetextitem
              into freetext
              from uniqueitemflag u
             where u.flag_id = flagid3
               and u.uniqueitem_id = uniqueitemid;
            flag_freetext3 := freetext;
            if length(freetext) > 0 and freetext2descriptionyn = 'Y' then
              begin
                if fp_kann_yes_no = 'Y' then
                  fp_flag_freetext3 := freetext;
                else
                  freetext         := flagdescription3 || ' ' || freetext;
                  flagdescription3 := substr(freetext, 1, 40);
                end if;
              end;
            end if;
          exception
            when no_data_found then
              null;
          end;
        exception
          when no_data_found then
            null;
        end;
      end if;
      if flagid4 > 0 then
        begin
          select s.sortaddress
            into flagcode4
            from sortaddressperflag s
           where s.flag_id = flagid4
             and s.plant_id = plantid_param;
          begin
            select d.description
              into flagdescription4
              from flag_desc d
             where d.flag_id = flagid4
               and d.language_id = languageid;
          exception
            when no_data_found then
              null;
          end;
          begin
            select u.freetextitem
              into freetext
              from uniqueitemflag u
             where u.flag_id = flagid4
               and u.uniqueitem_id = uniqueitemid;
            flag_freetext4 := freetext;
            if length(freetext) > 0 and freetext2descriptionyn = 'Y' then
              begin
                if fp_kann_yes_no = 'Y' then
                  fp_flag_freetext4 := freetext;
                else
                  freetext         := flagdescription4 || ' ' || freetext;
                  flagdescription4 := substr(freetext, 1, 40);
                end if;
              end;
            end if;
          exception
            when no_data_found then
              null;
          end;
          flagsinfo         := '';
          destinationstring := '';
        exception
          when no_data_found then
            null;
        end;
      end if;
      if (ui_status_assigned = 'Y' and sortadressperrc is not null) then
        flagdescription4 := flagdescription3;
        flagdescription3 := flagdescription2;
        flagdescription2 := flagdescription1;
        flagdescription1 := sortadressperrcdesc;
        flagcode4        := flagcode3;
        flagcode3        := flagcode2;
        flagcode2        := flagcode1;
        flagcode1        := sortadressperrc;
      end if;
    end if; --end for flagsusage 4
  exception
    when no_data_found then
      null;
  end getflags;
  procedure determinegarmentid(sortingsystem     in varchar2,
                               idcode            in uniqueitem.primaryid%type,
                               plantcode         in plant.code%type,
                               uniqueitemid      out nocopy uniqueitem.uniqueitem_id%type,
                               pool              out nocopy uniqueitem.poolitem%type,
                               unitcode          out nocopy businessunit.code%type,
                               businessunitid    out nocopy businessunit.businessunit_id%type,
                               plantid_garment   out nocopy plant.plant_id%type,
                               returnedplantcode out nocopy plant.code%type,
                               status            out nocopy integer,
                               idprimary         out uniqueitem.primaryid%type,
                               plantid_param     out nocopy plant.plant_id%type,
                               secondaryid       out secondaryuniqueitem.secondaryid%type) is
    lv_relatedcustid uniqueitem.relatedcustomer_id%type;
    lv_productid     product.product_id%type;
    lv_sizeid        sizedefinition.sizedefinition_id%type;
    batchnumber      uniqueitem.batchnumber%type;
    prevstayid       uniqueitem.prevstay_id%type;
    lastinscandate   uniqueitem.lastinscandate%type;
  begin
    determinegarmentid2(sortingsystem,
                        idcode,
                        plantcode,
                        uniqueitemid,
                        pool,
                        unitcode,
                        businessunitid,
                        plantid_garment,
                        returnedplantcode,
                        status,
                        idprimary,
                        plantid_param,
                        secondaryid,
                        lv_relatedcustid,
                        lv_productid,
                        lv_sizeid,
                        batchnumber,
                        prevstayid,
                        lastinscandate);
  end determinegarmentid;
  procedure determinegarmentid2(sortingsystem     in varchar2,
                                idcode            in uniqueitem.primaryid%type,
                                plantcode         in plant.code%type,
                                uniqueitemid      out nocopy uniqueitem.uniqueitem_id%type,
                                pool              out nocopy uniqueitem.poolitem%type,
                                unitcode          out nocopy businessunit.code%type,
                                businessunitid    out nocopy businessunit.businessunit_id%type,
                                plantid_garment   out nocopy plant.plant_id%type,
                                returnedplantcode out nocopy plant.code%type,
                                status            out nocopy integer,
                                idprimary         out uniqueitem.primaryid%type,
                                plantid_param     out nocopy plant.plant_id%type,
                                secondaryid       out secondaryuniqueitem.secondaryid%type,
                                relatedcustomerid out nocopy uniqueitem.relatedcustomer_id%type,
                                productid         out nocopy product.product_id%type,
                                sizeid            out nocopy sizedefinition.sizedefinition_id%type,
                                batchnumber       out nocopy uniqueitem.batchnumber%type,
                                prevstayid        out nocopy uniqueitem.prevstay_id%type,
                                plastinscandate   out nocopy uniqueitem.lastinscandate%type) is
    overalluniquegarmentid databasesettings.overalluniquegarmentid%type;
    codesequencenumber     uniqueitem.idcodesequencenumber%type;
    maxsequencenumber      integer;
    /*Same as determinegarmentid but with extra parameters*/

    procedure get_notoveralunique_primaryid(fp_primaryid in varchar2) is
    begin
      --get_notoveralunique_primaryid, overalluniquegarmentid = 'N'
      select u.uniqueitem_id,
             u.poolitem,
             u.businessunit_id,
             u.idcodesequencenumber,
             u.primaryid,
             u.relatedcustomer_id,
             u.product_id,
             u.sizedefinition_id,
             u.batchnumber,
             u.prevstay_id,
             u.lastinscandate
        into uniqueitemid,
             pool,
             businessunitid,
             codesequencenumber,
             idprimary,
             relatedcustomerid,
             productid,
             sizeid,
             batchnumber,
             prevstayid,
             plastinscandate
        from uniqueitem u
       where u.primaryid = fp_primaryid
         and u.idcodesequencenumber <= maxsequencenumber
         and exists (select 1
                from businessunit b
               where b.businessunit_id = u.businessunit_id
                 and b.plant_id = plantid_param);
    exception
      when no_data_found then
        begin
          select s.uniqueitem_id,
                 u.idcodesequencenumber,
                 u.poolitem,
                 s.businessunit_id,
                 u.primaryid,
                 u.relatedcustomer_id,
                 u.product_id,
                 u.sizedefinition_id,
                 u.batchnumber,
                 u.prevstay_id,
                 u.lastinscandate
            into uniqueitemid,
                 codesequencenumber,
                 pool,
                 businessunitid,
                 idprimary,
                 relatedcustomerid,
                 productid,
                 sizeid,
                 batchnumber,
                 prevstayid,
                 plastinscandate
            from secondaryuniqueitem s, uniqueitem u
           where s.secondaryid = fp_primaryid
             and u.idcodesequencenumber <= maxsequencenumber
             and s.uniqueitem_id = u.uniqueitem_id
             and exists (select 1
                    from businessunit b
                   where b.businessunit_id = s.businessunit_id
                     and b.plant_id = plantid_param);
        end;
    end get_notoveralunique_primaryid;

    procedure get_overalunique_primaryid(fp_primaryid in varchar2) is
    begin
      --get_overalunique_primaryid, overalluniquegarmentid = 'Y'
      select u.uniqueitem_id,
             u.poolitem,
             u.businessunit_id,
             u.idcodesequencenumber,
             u.primaryid,
             u.relatedcustomer_id,
             u.product_id,
             u.sizedefinition_id,
             u.batchnumber,
             u.prevstay_id,
             u.lastinscandate
        into uniqueitemid,
             pool,
             businessunitid,
             codesequencenumber,
             idprimary,
             relatedcustomerid,
             productid,
             sizeid,
             batchnumber,
             prevstayid,
             plastinscandate
        from uniqueitem u
       where u.primaryid = fp_primaryid
         and u.idcodesequencenumber <= maxsequencenumber;
    exception
      when no_data_found then
        begin
          select u.uniqueitem_id,
                 u.idcodesequencenumber,
                 u.poolitem,
                 s.businessunit_id,
                 u.primaryid,
                 u.relatedcustomer_id,
                 u.product_id,
                 u.sizedefinition_id,
                 u.batchnumber,
                 u.lastinscandate
            into uniqueitemid,
                 codesequencenumber,
                 pool,
                 businessunitid,
                 idprimary,
                 relatedcustomerid,
                 productid,
                 sizeid,
                 batchnumber,
                 plastinscandate
            from secondaryuniqueitem s, uniqueitem u
           where s.secondaryid = fp_primaryid
             and u.idcodesequencenumber <= maxsequencenumber
             and s.uniqueitem_id = u.uniqueitem_id;
        end;
    end get_overalunique_primaryid;

    function checktagfilter return varchar2 is
      newprimaryid varchar2(24);
    begin
      --if length=24, so UHF code, then check via uhftagfilter if newprimaryid maybe exists?
      if length(idcode) = 24 then
        begin
          select uhf.replacewith ||
                 substr(idcode, length(uhf.replaceprefix) + 1)
            into newprimaryid
            from uhftagfilter uhf
           where uhf.replaceprefix =
                 substr(idcode, 1, length(uhf.replaceprefix))
             and length(uhf.replaceprefix) between 4 and 16; --must have some length!
          return newprimaryid;
        end;
      else
        begin
          raise no_data_found;
        end;
      end if;
    end checktagfilter;
  begin
    maxsequencenumber := 99;
    if sortingsystem = 'KANNEGIESSER' then
      maxsequencenumber := 1;
    end if;
    status := 0;
    select overalluniquegarmentid
      into overalluniquegarmentid
      from databasesettings;
    if overalluniquegarmentid is null then
      overalluniquegarmentid := 'N';
    end if;
    begin
      --status
      if plantcode is not null then
        select p.plant_id
          into plantid_param
          from plant p
         where p.code = plantcode;
      else
        plantid_param := null;
      end if;
      if plantcode is not null and overalluniquegarmentid = 'N' then
        begin
          get_notoveralunique_primaryid(idcode);
        exception
          when no_data_found then
            begin
              get_notoveralunique_primaryid(checktagfilter);
            end;
        end;
      else
        begin
          --plantcode is null or overalluniqueID is Y
          get_overalunique_primaryid(idcode);
        exception
          when no_data_found then
            begin
              get_overalunique_primaryid(checktagfilter);
            end;
        end;
      end if;
    exception
      when no_data_found then
        begin
          pack_sort.write_logging('!> ' || 'Idcode ' ||
                                  nvl(idcode, 'NULL') || ' for plant ' ||
                                  nvl(plantcode, 'NULL') || case when
                                  plantid_param is null then
                                  '; (NULL)=No plant info, not found' else
                                  ' not found' end,
                                  1,
                                  'PACK_SORT.DETERMINEGARMENTID',
                                  plantid_garment,
                                  3,
                                  1);
          status := 1;
        end;
      when too_many_rows then
        begin
          pack_sort.write_logging('!> ' || 'Idcode ' ||
                                  nvl(idcode, 'NULL') || ' for plant ' ||
                                  nvl(plantcode, 'NULL') || case when
                                  plantid_param is null then
                                  ' (NULL)=No plant info, too many matching ID codes found' else
                                  ' too many matching ID codes found' end,
                                  1,
                                  'PACK_SORT.DETERMINEGARMENTID',
                                  plantid_garment,
                                  3,
                                  1);
          status := 1;
        end;
      when others then
        begin
          if sortingsystem = 'KANNEGIESSER' then
            status := 1;
          else
            status := 2;
          end if;
          pack_sort.write_logging('!> ' || 'Idcode ' ||
                                  nvl(idcode, 'NULL') || ' for plant ' ||
                                  nvl(plantcode, 'NULL') || case when
                                  plantid_param is null then
                                  ' (NULL)=No plant info, error ' else
                                  ' error ' end || sqlerrm,
                                  1,
                                  'PACK_SORT.DETERMINEGARMENTID',
                                  plantid_garment,
                                  3,
                                  1);
        end;
    end;
    if status = 0 then
      begin
        --BU
        select b.code, b.plant_id
          into unitcode, plantid_garment
          from businessunit b
         where b.businessunit_id = businessunitid;
      exception
        when no_data_found then
          status := 1;
        when others then
          if sortingsystem = 'KANNEGIESSER' then
            status := 1;
          else
            status := 2;
          end if;
      end;
    end if;
    if status = 0 and
       (sortingsystem = 'KANNEGIESSER' or sortingsystem = 'AMT') then
      select p.code
        into returnedplantcode
        from plant p
       where p.plant_id = plantid_garment;
    end if;
    --todo3437
    if status > 0 and plantcode is not null then
      begin
        select plant_id
          into plantid_param
          from plant
         where plant.code = plantcode;
      exception
        when no_data_found then
          select min(plant_id) into plantid_param from plant;
      end;
    elsif status > 0 and plantcode is null then
      select min(plant_id) into plantid_param from plant;
    end if;
    if plantid_garment is null then
      plantid_garment := plantid_param;
    end if;
    if plantid_param is null then
      plantid_param := plantid_garment;
    end if;
    --secondaryID
    begin
      select s.secondaryid
        into secondaryid
        from secondaryuniqueitem s
       where s.uniqueitem_id = uniqueitemid;
    exception
      when no_data_found then
        null;
    end;
  end determinegarmentid2;
  procedure getsystemsettings(plantid_param   in plant.plant_id%type,
                              debuglevel      out nocopy integer,
                              utldir          out nocopy varchar2,
                              allowrepairscan out nocopy integer,
                              getgarment      in number default 0) is
    lv_logdate date;

    procedure update_systemsetting is
      pragma autonomous_transaction;
    begin
      if getgarment = 0 then
        --turn of detailed logging
        update systemsetting ss
           set ss.value = '0'
         where ss.plant_id = plantid_param
           and ss.name = 'SORTLOGGETGARMENTDATA';
      else
        --turn of detailed logging
        update systemsetting ss
           set ss.value = '0'
         where ss.plant_id = plantid_param
           and ss.name = 'SORTLOGSENDTRACKINFO';
      end if;
      commit;
    end update_systemsetting;
  begin
    begin
      if getgarment = 0 then
        select s.value, trunc(s.timestamp) logdate
          into debuglevel, lv_logdate
          from systemsetting s
         where s.name = 'SORTLOGGETGARMENTDATA'
           and s.plant_id = plantid_param;
      else
        select s.value, trunc(s.timestamp) logdate
          into debuglevel, lv_logdate
          from systemsetting s
         where s.name = 'SORTLOGSENDTRACKINFO'
           and s.plant_id = plantid_param;
      end if;
      if debuglevel <> '0' and lv_logdate < trunc(sysdate) then
        update_systemsetting;
        debuglevel := '0';
      end if;
    exception
      when no_data_found then
        debuglevel := 0;
    end;
    begin
      select s.value
        into utldir
        from systemsetting s
       where s.name = 'DATABASELOGDIR'
         and s.plant_id = plantid_param;
    exception
      when no_data_found then
        utldir := 'C:\';
    end;
    if getgarment = 0 then
      begin
        select s.value
          into allowrepairscan
          from systemsetting s
         where s.name = 'ALLOWREPAIRSCAN'
           and s.plant_id = plantid_param;
      exception
        when no_data_found then
          allowrepairscan := 1;
      end;
    end if;
  end getsystemsettings;
  procedure getgarmentlocation(lockerid             in locker.locker_id%type,
                               garmentdispenserid   in garmentdispenser.garmentdispenser_id%type,
                               deliverypointid      in out deliverypoint.deliverypoint_id%type,
                               banklocker           out nocopy varchar2,
                               garmentdispensercode out nocopy garmentdispenser.code%type,
                               deliverypointcode    out nocopy deliverypoint.code%type) is
    vbank             varchar2(6);
    vlocker           varchar2(6);
    auxnumeric_bank   integer;
    auxnumeric_locker integer;
    databasecode      databasesettings.code%type;
  begin
    select d.code into databasecode from databasesettings d;
    --banklocker
    if lockerid is not null then
      begin
        select l.bank, isnumeric(l.bank), l.locker, isnumeric(l.locker)
          into vbank, auxnumeric_bank, vlocker, auxnumeric_locker
          from locker l
         where l.locker_id = lockerid;
        if auxnumeric_bank = 1 then
          --isnumeric returns 1 for numeric and 0 for alfanumeric
          if (databasecode = 'HPL' or databasecode = 'SGS') then
            vbank := rpad(vbank, 6, ' ');
          else
            vbank := lpad(vbank, 6, ' ');
          end if;
        else
          --alfanumeric
          vbank := rpad(vbank, 6, ' ');
        end if;
        if auxnumeric_locker = 1 then
          if (databasecode = 'HPL' or databasecode = 'SGS') then
            vlocker := rpad(vlocker, 6, ' ');
          else
            vlocker := lpad(vlocker, 6, ' ');
          end if;
        else
          vlocker := rpad(vlocker, 6, ' ');
        end if;
      exception
        when others then
          null;

      end;
      if vbank is null then
        banklocker := '      ' || vlocker;
      else
        banklocker := vbank || vlocker;
      end if;
    else
      banklocker := '            ';
    end if;
    --garmentdispenser
    if garmentdispenserid is not null then
      select g.code
        into garmentdispensercode
        from garmentdispenser g
       where g.garmentdispenser_id = garmentdispenserid;
      garmentdispensercode := rpad(garmentdispensercode, 6, ' ');
    else
      garmentdispensercode := '      ';
    end if;
    begin
      --deliverypoint
      if deliverypointid is not null then
        select d.code
          into deliverypointcode
          from deliverypoint d
         where d.deliverypoint_id = deliverypointid;
        -- exception when no_data_found then null;
      elsif lockerid is not null then
        select d.code, d.deliverypoint_id
          into deliverypointcode, deliverypointid
          from locker l, deliverypoint d
         where l.deliverypoint_id = d.deliverypoint_id
           and l.locker_id = lockerid;
      elsif garmentdispenserid is not null then
        select d.code, d.deliverypoint_id
          into deliverypointcode, deliverypointid
          from garmentdispenser g, deliverypoint d
         where g.deliverypoint_id = d.deliverypoint_id
           and g.garmentdispenser_id = garmentdispenserid;
      end if;
    exception
      when no_data_found then
        null;
    end;
    if deliverypointcode is not null then
      deliverypointcode := rpad(deliverypointcode, 12, ' ');
    else
      deliverypointcode := '           ';
    end if;
  end getgarmentlocation;
procedure getgarmentdatainfo(sortingsystem           in varchar2,
                               plantid_garment         in plant.plant_id%type,
                               uniqueitemid            in uniqueitem.uniqueitem_id%type,
                               languageid              in out languages.language_id%type,
                               finishingcodeid         out nocopy finishingcode.finishingcode_id%type,
                               serviceteamid           out nocopy serviceteam.serviceteam_id%type,
                               vchargerepairs          out nocopy customer.chargerepairs%type,
                               vcustomerowned          out nocopy uniqueitem.customerowned%type,
                               colorid                 out nocopy color.color_id%type,
                               wearerflagid            out nocopy flag.flag_id%type,
                               wearerflagstartdate     out nocopy date,
                               empflagid               out nocopy flag.flag_id%type,
                               empflagstartdate        out nocopy date,
                               finishingmethodid       out nocopy finishingmethod.finishingmethod_id%type,
                               productid               out nocopy product.product_id%type,
                               productcode             out nocopy product.code%type,
                               productdescription      out nocopy product_desc.description%type,
                               sizecode                out nocopy sizedefinition.code%type,
                               customernumber          out nocopy customer.customernumber%type,
                               customerid              out nocopy customer.customer_id%type,
                               customername            out nocopy customer.name%type,
                               wearernumber            out nocopy wearer.wearernumber%type,
                               wearername              out nocopy wearer.searchname%type,
                               banklocker              out nocopy varchar2,
                               departmentnumber        out nocopy department.departmentnumber%type,
                               customeremployeenumber  out nocopy wearer.customeremployeenumber%type,
                               gender                  out nocopy wearer.sex%type,
                               garmentdispensercode    out nocopy garmentdispenser.code%type,
                               deliverypointcode       out nocopy deliverypoint.code%type,
                               infotext                out nocopy wearer.remark%type,
                               routenumber             out nocopy route.routenumber%type,
                               routeday                out nocopy day.daynumber%type,
                               stopnumber              out nocopy routestop.stopnumber%type,
                               packingsequence         out nocopy product.packingsequence%type,
                               stayid                  out nocopy stay.stay_id%type,
                               routeid                 out nocopy route.route_id%type,
                               imageid                 out nocopy product.image_id%type,
                               routestopid             out nocopy routestop.routestop_id%type,
                               planneddate             out nocopy date,
                               statusout               out nocopy integer,
                               valternatesortingstring out nocopy customer.alternatesorting%type,
                               debuglevel              in integer,
                               findpackingnote         in out varchar2,
                               pnnotenumber            out packingnote.notenumber%type,
                               --Order 502022
                               routedate in out date,
                               --Order#502901
                               fp_washestotal      out nocopy uniqueitem.washestotal%type,
                               fp_routecodeonlabel out nocopy route.codeonlabel%type,
                               fp_plant_idparam    in plant.plant_id%type default null,
                               fp_sortcustomerid   out nocopy customer.sortcustomer_id%type,
                               fp_languagecode     in languages.code%type default null) is
    sizedefinitionid            sizedefinition.sizedefinition_id%type;
    plpcid                      productlistpercustomer.productlistpercustomer_id%type;
    deliverymethod              productlistpercustomer.delayedevenexchange%type;
    lastinroute                 route.route_id%type;
    staynumber                  stay.staynr%type;
    pool                        uniqueitem.poolitem%type;
    typeofmerch                 product.typeofmerchandise%type;
    weareremploymentid          weareremployment.weareremployment_id%type;
    lockerid                    locker.locker_id%type;
    externallockerid            locker.locker_id%type;
    garmentdispenserid          garmentdispenser.garmentdispenser_id%type;
    deliverypointid             deliverypoint.deliverypoint_id%type;
    savedeliverypointid         deliverypoint.deliverypoint_id%type;
    routestopin                 routestop.routestop_id%type;
    lastindate                  date;
    scanbyroute                 varchar2(1);
    allowcustlockersharing      varchar2(1);
    checkinternalsortingplant   varchar2(1);
    internalplantid             plant.plant_id%type;
    countdeliveryscheme         integer;
    countroutes                 integer;
    deedeliveryschemeid         deliveryscheme.deliveryscheme_id%type;
    vmaxwashes                  integer;
    sortbatchstop               integer;
    sortbatchroute              integer;
    stopbatch                   integer;
    routebatch                  integer;
    wearerinventoryid           wearerinventory.wearerinventory_id%type;
    vqtytobereturneddecreasemax integer;
    flagid                      flag.flag_id%type;
    systemuserid                systemuser.systemuser_id%type;
    idcode                      uniqueitem.primaryid%type;
    plpcfinishingcode           productlistpercustomer.finishingcode_id%type;
    diremarkondeliverynote      distributionpoint.remarkondeliverynote%type;
    productgroupid              productgroup.productgroup_id%type;
    plantdepartmentid           plantdepartment.plantdepartment_id%type;
    statusnew                   status.status_id%type;
    businessunitid              businessunit.businessunit_id%type;
    packingnoteid               packingnote.packingnote_id%type;
    routecontrolid              routecontrol.routecontrol_id%type;
    distributionpointid         distributionpoint.distributionpoint_id%type;
    defaulttranspart            transportarticle.transportarticle_id%type;
    rcpackingdeadline           routecontrol.packingdeadline%type;
    rcsortingstatus             routecontrol.sortingstatus%type;
    minpackingnotelineid        packingnoteline.packingnoteline_id%type;
    bucode                      businessunit.code%type;
    stopid                      stop.stop_id%type;
    rdeadline                   packingnote.deadline%type;
    plpcustomcode               productlistpercustomer.customcode%type;
    plpcustomdescription        productlistpercustomer.customdescription%type;
    pchargewashesonlyforcog     varchar2(1);
    pbillingmethod              integer;
    char_notenumber             varchar2(8);
    plantdepartment_notfound    integer;
    packingdatetime             date;
    drivingdate                 date;
    packingday                  number;
    createnewpackingnote        varchar2(1);
    createnewpackingnoteline    varchar2(1);
    routeinprogress             varchar2(1);
    lv_treatmentcheckschemeid   treatmentcheckscheme.treatmentcheckscheme_id%type;
    -- Order 20014102
    deliverydetermination integer;
    inroutecontrol_id     number;
    instop_id             number;
    outroutecontrol_id    number;
    deparment_id          number := null;
    lv_log                varchar2(1) := 'N';
begin
    statusout := 0;
    --systemuser
    begin
      select s.systemuser_id
        into systemuserid
        from systemuser s
       where s.username = 'SORT';
    exception
      when no_data_found then
        select min(systemuser_id) into systemuserid from systemuser;
    end;
    begin
      --scan by route
      select s.value
      into   scanbyroute
      from   systemsetting s
      where  s.plant_id = plantid_garment
      and    s.name = 'SCANBYROUTE';
    exception
      when others then
        null;
    end;
    begin
      --scan by route
      select s.value
      into   allowcustlockersharing
      from   systemsetting s
      where  s.plant_id = plantid_garment
      and    s.name = 'ALLOWCUSTLOCKERSHARING';
    exception
      when others then
        null;
    end;
    -- Order 20014102
    begin
      select s.value
      into   deliverydetermination
      from   systemsetting s
      where  s.plant_id = plantid_garment
      and    s.name = 'DELIVERYDETERMINATION';
    exception
      when others then
        null;
    end;
    if fp_languagecode is not null then
      begin
        select max(l.language_id)
          into languageid
          from languages l
         where l.code = fp_languagecode;
      end;
    end if;
    if languageid is null then
      --language
      select languages.language_id
        into languageid
        from languages, plant
       where languages.language_id = plant.language_id
         and plant.plant_id = plantid_garment;
    end if;
    --unique item
    select u.primaryid,
           u.stay_id,
           u.finishingmethod_id,
           u.sizedefinition_id,
           p.product_id,
           p.code,
           p.packingsequence,
           cfsgetdesc_product(p.product_id, languageid),
           s.code,
           p.finishingcode_id,
           p.color_id,
           p.typeofmerchandise,
           u.customerowned,
           u.poolitem,
           p.image_id,
           p.productgroup_id,
           u.businessunit_id,
           u.washestotal
      into idcode,
           stayid,
           finishingmethodid,
           sizedefinitionid,
           productid,
           productcode,
           packingsequence,
           productdescription,
           sizecode,
           finishingcodeid,
           colorid,
           typeofmerch,
           vcustomerowned,
           pool,
           imageid,
           productgroupid,
           businessunitid,
           fp_washestotal
      from uniqueitem u, product p, sizedefinition s
     where u.uniqueitem_id = uniqueitemid
       and u.product_id = p.product_id
       and u.sizedefinition_id = s.sizedefinition_id;
    begin
      select stay.staynr
        into staynumber
        from stay
       where stay.stay_id = stayid;
    exception
      when others then
        null;
    end;
    if pool = 2 then
      begin
        --nonpool items
        begin
          select c.customernumber,
                 c.name,
                 c.customer_id,
                 c.serviceteam_id,
                 d.departmentnumber,
                 w.wearernumber,
                 w.searchname,
                 w.sex,
                 e.weareremployment_id,
                 w.customeremployeenumber,
                 w.remark,
                 w.flag_id,
                 w.flagstartdate,
                 e.flag_id,
                 e.flagstartdate,
                 e.locker_id,
                 e.garmentdispenser_id,
                 e.deliverypoint_id,
                 c.chargerepairs,
                 c.alternatesorting,
                 di.remarkondeliverynote,
                 di.distributionpoint_id,
                 c.sortcustomer_id,
                 e.externallocker_id
            into customernumber,
                 customername,
                 customerid,
                 serviceteamid,
                 departmentnumber,
                 wearernumber,
                 wearername,
                 gender,
                 weareremploymentid,
                 customeremployeenumber,
                 infotext,
                 wearerflagid,
                 wearerflagstartdate,
                 empflagid,
                 empflagstartdate,
                 lockerid,
                 garmentdispenserid,
                 deliverypointid,
                 vchargerepairs,
                 valternatesortingstring,
                 diremarkondeliverynote,
                 distributionpointid,
                 fp_sortcustomerid,
                 externallockerid
            from uniqueitemnonpool n,
                 customer          c,
                 department        d,
                 wearer            w,
                 weareremployment  e,
                 distributionpoint di
           where n.uniqueitem_id = uniqueitemid
          and    n.weareremployment_id = e.weareremployment_id
          and    e.wearer_id = w.wearer_id
          and    w.customer_id = c.customer_id
          and    e.distributionpoint_id = di.distributionpoint_id
          and    di.department_id = d.department_id;
        exception
          when no_data_found then
            null;
        end;
        --order 501516
        begin
          select a.wearerinventory_id, a.qtytobereturneddecreasemax
          into   wearerinventoryid, vqtytobereturneddecreasemax
          from   wearerinventory a
          where  a.weareremployment_id = weareremploymentid
          and    a.product_id = productid
          and    a.sizedefinition_id = sizedefinitionid
          and    a.finishingmethod_id = finishingmethodid;
        exception
          when no_data_found then
            wearerinventoryid := null;
        end;
        if wearerinventoryid is not null then
          if vqtytobereturneddecreasemax > 0 then
            begin
              select flag_id
              into   flagid
              from   automaticflag a
              where  --a.event ='Return to stock because of decrease max inventory';
               a.automaticflag_id = 7;
              if pack_sort.create_uniqueitemflag('PACK_SORT.GETGARMENTDATAINFO',
                                                 debuglevel,
                                                 systemuserid,
                                                 uniqueitemid,
                                                 flagid,
                                                 sysdate,
                                                 null,
                                                 null,
                                                 null,
                                                 plantid_garment) then
                update wearerinventory w
                   set w.qtytobereturneddecreasemax = qtytobereturneddecreasemax - 1
                 where w.wearerinventory_id = wearerinventoryid;
                --add debug information when needed
                if debuglevel > 0 then
                  pack_sort.write_logging('update wearerinventory ' ||
                                          nvl(to_char(wearerinventoryid),
                                              'NULL'),
                                          debuglevel,
                                          'PACK_SORT.GETGARMENTDATAINFO',
                                          plantid_garment,
                                          1,
                                          1);
                end if;
                commit;
              end if;
            exception
              when others then
                rollback;
                pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                        debuglevel,
                                        'PACK_SORT.GETGARMENTDATAINFO',
                                        plantid_garment,
                                        3,
                                        1);
            end;
          end if; -- end if qtytobereturneddecrease
        end if; -- end if wearerinventory is not null
        --end order501516
        if customerid is not null then
          select count(*)
            into countdeliveryscheme
            from customerdeliveryscheme c
           where c.customer_id = customerid;
          if countdeliveryscheme = 0 then
            statusout := 1;
          elsif scanbyroute = 'Y' then
            select count(*)
              into countroutes
              from routestop r
             where r.customer_id = customerid;
          end if;
          if countroutes = 0 then
            statusout := 1;
          end if;
        end if;
        if statusout = 0 then
          -- Order 20013679
          -- do not use sortcustomer when wearer is not linked to external locker
          -- but only when systemsetting ALLOWCUSTLOCKERSHARING=1 for backwards compatibility
          if allowcustlockersharing = '1' and externallockerid is null and
             fp_sortcustomerid is not null then
            fp_sortcustomerid := null;
          end if;
          -- End Order 20013679
          pack_sort.getgarmentlocation(lockerid,
                                       garmentdispenserid,
                                       deliverypointid,
                                       banklocker,
                                       garmentdispensercode,
                                       deliverypointcode);
          -- use external locker if filled
          if externallockerid is not null then
            lockerid            := externallockerid;
            savedeliverypointid := deliverypointid;
            deliverypointid     := null;
            pack_sort.getgarmentlocation(lockerid,
                                         garmentdispenserid,
                                         deliverypointid,
                                         banklocker,
                                         garmentdispensercode,
                                         deliverypointcode);
            deliverypointid := savedeliverypointid;
          end if;
          -- End Order 20013679
          --route
          ---plpc info
          pack_sort.findplpcinfo(customerid,
                                 productid,
                                 sizedefinitionid,
                                 finishingmethodid,
                                 deliverymethod,
                                 deedeliveryschemeid,
                                 plpcid,
                                 vmaxwashes,
                                 plpcfinishingcode,
                                 plpcustomcode,
                                 plpcustomdescription,
                                 pchargewashesonlyforcog,
                                 pbillingmethod,
                                 lv_treatmentcheckschemeid);
        end if; --for statusout=0
      end; -- finish nonpool items
    else
      begin
        --pool items
        wearernumber    := 0;
        deliverypointid := null;
        routedate       := sysdate;

        select c.customernumber, c.name, c.serviceteam_id, c.customer_id, c.chargerepairs,
               c.sortcustomer_id
        into   customernumber, customername, serviceteamid, customerid, vchargerepairs, fp_sortcustomerid
        from   uniqueitem u
        join   customer c
        on     c.customer_id = u.relatedcustomer_id
        where  u.uniqueitem_id = uniqueitemid;

        pack_sort.findplpcinfo(customerid, productid, sizedefinitionid, finishingmethodid,
                               deliverymethod, deedeliveryschemeid, plpcid, vmaxwashes,
                               plpcfinishingcode, plpcustomcode, plpcustomdescription,
                               pchargewashesonlyforcog, pbillingmethod, lv_treatmentcheckschemeid);
      exception
        when no_data_found then
          begin
            vchargerepairs := 0;
            customernumber := 0;
            customername   := '';
            routenumber    := 0;
            stopnumber     := 0;
            routeday       := getabsdaynumber(sysdate);
          end;
      end;
    end if; --end pool/nonpool
    begin
      --Order 502022
      if routedate is null then
        routedate := sysdate;
      end if;
            -- Order 20014102
            if deliverydetermination = 1 then
              pack_deliverybasics.determinedeldateroutesoil(plantid_garment,
                                                            customerid,
                                                            deliverypointid,
                                                            deparment_id,
                                                            typeofmerch,
                                                            routedate,
                                                            plpcid,
                                                            distributionpointid,
                                                            lv_log,
                                                            lastinroute,
                                                            routestopin,
                                                            inroutecontrol_id,
                                                            instop_id,
                                                            lastindate,
                                                            routeid,
                                                            routestopid,
                                                            outroutecontrol_id,
                                                            stopid,
                                                            planneddate);

            else
              pack_sort.getlastinroute(customerid,
                                       routedate,
                                       deliverypointid,
                                       typeofmerch,
                                       lastinroute,
                                       routestopin,
                                       lastindate);

              pack_sort.fillplannedoutroute(plantid_garment,
                                            routedate,
                                            typeofmerch,
                                            deliverymethod,
                                            deedeliveryschemeid,
                                            plpcid,
                                            customerid,
                                            deliverypointid,
                                            lastinroute,
                                            lastindate,
                                            routestopin,
                                            routestopid,
                                            routeid,
                                            planneddate,
                                            scanbyroute);
            end if;
      /* Start Todo 8605 HVH 7/5/2009*/
      -- For Check if route is closed. If yes then determine next one
      if findpackingnote = 'Y' and pool = 2 then
        begin
          routecontrolid  := null;
          rcsortingstatus := null;
          begin
            select rc.routecontrol_id, rc.sortingstatus
            into   routecontrolid, rcsortingstatus
            from   routecontrol rc
            where  rc.route_id = routeid
            and    rc.drivingdate = trunc(planneddate); --HVH added trunc todo 7550
          exception
            when no_data_found then
              null;
          end;
          if rcsortingstatus = 2 /*Closed*/
           then
            begin
              if debuglevel > 0 then
                      pack_sort.write_logging(idcode || ' Route ID ' ||
                                              routecontrolid || ' on ' ||
                                              planneddate ||
                                              ' Closed. Try next visit for customer ' ||
                                              customernumber,
                                              debuglevel,
                                              'PACK_SORT.GETGARMENTDATAINFO',
                                              plantid_garment,
                                              1,
                                              1);
                    end if;
              -- Order 20014102
                    if deliverydetermination = 1 then
                      pack_deliverybasics.determinedeldateroutesoil(plantid_garment,
                                                                    customerid,
                                                                    deliverypointid,
                                                                    deparment_id,
                                                                    typeofmerch,
                                                                    routedate,
                                                                    plpcid,
                                                                    distributionpointid,
                                                                    lv_log,
                                                                    lastinroute,
                                                                    routestopin,
                                                                    inroutecontrol_id,
                                                                    instop_id,
                                                                    lastindate,
                                                                    routeid,
                                                                    routestopid,
                                                                    outroutecontrol_id,
                                                                    stopid,
                                                                    planneddate);
              else
                      -- Determine first next delivery day after previous determined next del.day
                      pack_sort.fillplannedoutroute(plantid_garment,
                                                    planneddate,
                                                    --routedate, (start from just determined del.date)
                                                    typeofmerch,
                                                    1,
                                                    --deliverymethod,  (always first next visit)
                                                    deedeliveryschemeid,
                                                    plpcid,
                                                    customerid,
                                                    deliverypointid,
                                                    lastinroute,
                                                    planneddate,
                                                    --lastindate, (start from just determined del.date)
                                                    routestopin,
                                                    routestopid,
                                                    routeid,
                                                    planneddate,
                                                    scanbyroute);
              end if;
              routecontrolid  := null;
              rcsortingstatus := null;
              begin
                select rc.routecontrol_id, rc.sortingstatus
                into   routecontrolid, rcsortingstatus
                from   routecontrol rc
                where  rc.route_id = routeid
                and    rc.drivingdate = trunc(planneddate); --HVH added trunc todo 7550
              exception
                when no_data_found then
                  null;
              end;
              -- if the next one is closed as well
                    if rcsortingstatus = 2 /*Closed*/
                     then
                      pack_sort.write_logging(idcode ||
                                              ' Next Route, Route ID ' ||
                                              routecontrolid || ' on ' ||
                                              planneddate ||
                                              ' also Closed.',
                                              debuglevel,
                                              'PACK_SORT.GETGARMENTDATAINFO',
                                              plantid_garment,
                                              1,
                                              1);
                    end if;
            end;
          end if;
        end;
      end if;
            -- Order 20014102, todo 24578
            if deliverydetermination = 1 and stopid is not null then
              begin
                select s.stopnumber
                  into stopnumber
                  from stop s
                 where s.stop_id = stopid;
              exception
                when others then
                  null;
              end;
              begin
                select r.routenumber,
                       r.drivingday_id,
                       r.sortbatchdefinition_id,
                       r.codeonlabel
                  into routenumber,
                       routeday,
                       sortbatchroute,
                       fp_routecodeonlabel
                  from route r
                 where r.route_id = routeid;
              exception
          when others then
            null;
        end;
        begin
          select s.specificsortbatchdefinition_id
          into   sortbatchstop
          from   routestop s
          where  s.routestop_id = routestopid;
        exception
          when others then
            null;
        end;
            else
              /* End Todo 8605 HVH 7/5/2009*/
              select r.routenumber,
                     r.drivingday_id,
                     s.specificsortbatchdefinition_id,
                     r.sortbatchdefinition_id,
                     r.codeonlabel
                into routenumber,
                     routeday,
                     sortbatchstop,
                     sortbatchroute,
                     fp_routecodeonlabel
                from route r, routestop s
               where s.route_id = routeid
        and    s.customer_id = customerid
        and    s.route_id = r.route_id
        and    s.routestop_id = routestopid;
        --> order 502746
        select s.stopnumber
        into   stopnumber
        from   route r, routestop s
        where  s.route_id = routeid
        and    s.customer_id = customerid
        and    s.route_id = r.route_id
        and    s.routestop_id = routestopid; --< order 502746
      end if;
      if sortingsystem = 'METRIC' then
        if sortbatchstop is not null then
          begin
            select s.batchnumber
            into   stopbatch
            from   sortbatchdefinition s
            where  s.sortbatchdefinition_id = sortbatchstop
            and    s.plant_id = plantid_garment
            and    s.day_id = routeday;
          exception
            when others then
              null;
          end;
        else
          begin
            select s.batchnumber
            into   routebatch
            from   sortbatchdefinition s
            where  s.sortbatchdefinition_id = sortbatchroute
            and    s.plant_id = plantid_garment
            and    s.day_id = routeday;
          exception
            when others then
              null;
          end;
        end if;
        if stopbatch is not null then
          routenumber := stopbatch;
        elsif routebatch is not null then
          routenumber := routebatch;
        end if;
      end if; --for METRIC
    exception
      when no_data_found then
        begin
          routenumber := 0;
          stopnumber  := 0;
          routeday    := getabsdaynumber(sysdate);
        end;
    end;
    --20011459
    if fp_plant_idparam is not null and sortingsystem = 'METRIC' then
      begin
        select s.value
        into   checkinternalsortingplant
        from   systemsetting s
        where  s.plant_id = fp_plant_idparam
        and    s.name = 'CHECKINTERNALSORTINGPLANT';
      exception
        when others then
          --default is 1, so when the system setting is not there work as normal
          checkinternalsortingplant := 1;
      end;
      if checkinternalsortingplant = 0 then
        begin
          select bu.plant_id
          into   internalplantid
          from   productgroup g, customeractivities ca, businessunit bu
          where  g.productgroup_id = productgroupid
          and    g.activity_id = ca.activity_id
          and    ca.customer_id = customerid
          and    ca.processbusinessunit_id = businessunitid
          and    ca.internalprocessingbu_id = bu.businessunit_id;
          if internalplantid <> fp_plant_idparam then
            --status 2, so getgarmentdatabasic can give a specific message internalplantid <> fp_plant_idparam
            statusout := 2;
          end if;
        exception
          when others then
            statusout := 2;
        end;
      end if;
    end if; --end 20011459
    --todo4964
    if plpcfinishingcode is not null then
      finishingcodeid := plpcfinishingcode;
    end if;
    --501875
    if findpackingnote = 'Y' and pool = 2 then
      begin
        plantdepartment_notfound := 1;
        begin
          select a.plantdepartment_id
          into   plantdepartmentid
          from   packingdepartmentdefinition a, plantdepartment pd
          where  a.productgroup_id = productgroupid
          and    a.plant_id = plantid_garment
          and    a.plantdepartment_id = pd.plantdepartment_id
          and    pd.code = 'METRIC';
        exception
          when others then
            plantdepartment_notfound := 0;
            pnnotenumber             := 0;
            findpackingnote          := '00000000';
        end;
        if plantdepartment_notfound = 1 then
          select s.status_id
          into   statusnew
          from   status s
          where  s.statustype = 'PN'
          and    s.code = '10';
          select t.transportarticle_id
          into   defaulttranspart
          from   transportarticle t
          where  t.defaulttransportarticle = 'Y';
          begin
            select rc.routecontrol_id,
                   rc.packingdeadline,
                   rc.packingday_id,
                   rc.drivingdate
              into routecontrolid,
                   rcpackingdeadline,
                   packingday,
                   drivingdate
            from   routecontrol rc
            where  rc.route_id = routeid
            and    rc.drivingdate = trunc(planneddate); --HVH added trunc todo 7550
          exception
            when no_data_found then
              select r.packingdeadline, r.drivingday_id
              into   rcpackingdeadline, routeday
              from   route r
              where  r.route_id = routeid;
              routecontrolid := null;
          end;
          if planneddate is null then
            planneddate := trunc(sysdate);
          else
            planneddate := trunc(planneddate); --HVH added trunc todo 7550
          end if;
          if substr(to_char(rcpackingdeadline, 'yyyymmddhh24miss'), -6, 6) is null then
            rcpackingdeadline := sysdate;
          end if;
          rdeadline                := to_date(substr(to_char(planneddate,
                                                             'yyyymmddhh24miss'),
                                                     1,
                                                     8) ||
                                              substr(to_char(rcpackingdeadline,
                                                             'yyyymmddhh24miss'),
                                                     -6,
                                                     6),
                                              'YYYYMMDDHH24MISS');
          packingnoteid            := null;
          createnewpackingnote     := 'N';
          createnewpackingnoteline := 'N';
          routeinprogress          := 'N';
          if routeinprogress = 'N' then
            createnewpackingnote     := 'Y'; -- assume yes, until one is found
            createnewpackingnoteline := 'Y'; -- assume yes, until one is found
            -- search for existing packingnotes:
            for vcursor in (select pn.packingnote_id,
                                   pn.notenumber,
                                   pn.routecontrol_id
                              from packingnote pn
                             where pn.route_id = routeid
                               and trunc(pn.deliverydate) = planneddate
                               and pn.deliverypoint_id = deliverypointid
                               and pn.distributionpoint_id =
                                   distributionpointid
                               and pn.status_id = statusnew
                               and pn.origin = 2 --in (0, 2) 24/9/2008/HVH COG always on separate PN
                               and pn.plantdepartment_id = plantdepartmentid) --;
             loop
              begin
                createnewpackingnote := 'N'; -- found one, so no new note to be created
                pnnotenumber         := vcursor.notenumber;
                packingnoteid        := vcursor.packingnote_id;
                -- Link packingnote to routecontrol:
                if (vcursor.routecontrol_id is null and
                   routecontrolid is not null) then
                  update packingnote p
                     set p.routecontrol_id = routecontrolid
                  where  p.packingnote_id = vcursor.packingnote_id;
                  -- update RouteControl packingstatus to 'Put Up Printed' when PN is linked to it - todo 8927
                  update routecontrol rc
                  set    rc.packingstatus = 2 -- put up printed
                  where  rc.routecontrol_id = routecontrolid;
                end if;
                select min(pl.packingnoteline_id)
                into   minpackingnotelineid
                from   packingnoteline pl
                where  pl.packingnote_id = vcursor.packingnote_id
                and    pl.product_id = productid
                and    pl.sizedefinition_id = sizedefinitionid;
                if minpackingnotelineid is not null then
                  update packingnoteline pl
                  set    pl.variationamount = pl.variationamount + 1,
                         pl.tobedeliveredamount = pl.tobedeliveredamount + 1
                   where pl.packingnoteline_id = minpackingnotelineid;
                  createnewpackingnoteline := 'N'; -- found row to update, so no new row needs to be created
                  if debuglevel > 0 then
                    pack_sort.write_logging(' update packingnoteline ID ' ||
                                            minpackingnotelineid ||
                                            ' at PN# ' || pnnotenumber,
                                            debuglevel,
                                            'PACK_SORT.GETGARMENTDATAINFO',
                                            plantid_garment,
                                            1,
                                            1);
                  end if;
                  exit; -- exit loop when packingnoteline found.
                end if; --minpackingnotelineid is not null
              exception
                when others then
                  pack_sort.write_logging('!> ' || idcode || ' ' ||
                                          sqlerrm,
                                          debuglevel,
                                          'PACK_SORT.GETGARMENTDATAINFO',
                                          plantid_garment,
                                          3,
                                          1);
              end;
            end loop;
          end if; -- route in progress
          if debuglevel > 0 then
            pack_sort.write_logging('After loop: ' || chr(10) ||
                                    pnnotenumber || ' pnnotenumber ' ||
                                    chr(10) || packingnoteid ||
                                    ' packingnoteid ' || chr(10) ||
                                    createnewpackingnote ||
                                    ' createnewpackingnote ' || chr(10) ||
                                    createnewpackingnoteline ||
                                    ' createnewpackingnoteline ',
                                    debuglevel,
                                    'PACK_SORT.GETGARMENTDATAINFO',
                                    plantid_garment,
                                    1,
                                    1);
          end if;
          begin
            --            if packingnoteid is null and pnnotenumber <> 0 then
            if createnewpackingnote = 'Y' then
              select b.code
                into bucode
                from businessunit b
               where b.businessunit_id = businessunitid;
              /* Start HVH 08/05/2009 Todo 8605 Solve issue when stop has no link to routestop*/
              begin
                if routecontrolid is not null and
                   deliverydetermination <> 1 then
                  select stop.stop_id, stop.stopnumber
                    into stopid, stopnumber
                    from stop
                   where stop.routecontrol_id = routecontrolid
                     and stop.routestop_id = routestopid
                     and stop.customer_link_id = customerid;
                end if;
              exception
                when no_data_found then
                  stopid := null;
              end;
              begin
                -- when not found try to find the first stop in route for customer
                if routecontrolid is not null and stopid is null then
                  select stop.stop_id, stop.stopnumber
                    into stopid, stopnumber
                    from stop
                   where stop.stop_id =
                         (select min(stop1.stop_id)
                            from stop stop1
                           where stop1.routecontrol_id = routecontrolid
                             and stop1.customer_link_id = customerid);
                end if;
              exception
                -- when still not found, then don't link Packingnote to routecontrol
                when no_data_found then
                  routecontrolid := null;
                  stopid         := null;
                  stopnumber     := 0;
              end;
              /* End HVH 08/05/2009 Todo 8605 Solve issue when stop has no link to routestop*/
              execute immediate 'select SEQ_DELIVERYNOTE_' || bucode ||
                                '.nextval from DUAL'
                into pnnotenumber;

              insert into packingnote
                (employee_id,
                 packingnote_id,
                 notenumber,
                 productiondate,
                 deliverydate,
                 status_id,
                 remark,
                 distributionpoint_id,
                 deliverypoint_id,
                 plantdepartment_id,
                 transportarticle_id,
                 systemuser_id,
                 processbusinessunit_id,
                 route_id,
                 timestamp,
                 cleanreturn,
                 sequencenumber,
                 deadline,
                 occupancy,
                 invoicebusinessunit_id,
                 routecontrol_id,
                 originaldeliverydate,
                 --invoiceheader_id,
                 enddateforuse,
                 origin,
                 stopnumber,
                 daynumber,
                 correctednotenumber,
                 creationtimestamp,
                 referencenumber,
                 returndateloan,
                 stop_id,
                 consignmentnote_id,
                 straightevenreturn,
                 numberofgarmentsinlocker,
                 numberoflockers,
                 bulkpackingnote_id,
                 freeofchargereason_id,
                 week,
                 year,
                 weighingticket_id,
                 totalamount,
                 totalamountexcludingvat,
                 pricescalculated,
                 showoninvoiceappendix,
                 deliveryremark)
              values
                (null,
                 seq_packingnote.nextval,
                 pnnotenumber,
                 --
                 trunc(sysdate),
                 trunc(planneddate),
                 statusnew,
                 diremarkondeliverynote,
                 distributionpointid,
                 deliverypointid,
                 plantdepartmentid,
                 defaulttranspart,
                 systemuserid,
                 businessunitid,
                 routeid,
                 sysdate,
                 'N',
                 1,
                 rdeadline,
                 --
                 0,
                 businessunitid,
                 routecontrolid,
                 planneddate,
                 --null,
                 planneddate,
                 2,
                 stopnumber,
                 ---
                 getabsdaynumber(planneddate),
                 0,
                 sysdate,
                 null,
                 null,
                 stopid,
                 null,
                 'N',
                 0,
                 0,
                 null,
                 null,
                 getisoweek(planneddate),
                 year(planneddate),
                 null,
                 0,
                 0,
                 'N',
                 'N',
                 'N'); --

              /*              -- update RouteControl packingstatus to 'Put Up Printed' when PN is linked to it - todo 8927
              update routecontrol rc
              set    rc.packingstatus = 2 -- put up printed
              where  rc.routecontrol_id = routeid;*/
              execute immediate 'select SEQ_PACKINGNOTE.currval from DUAL'
                into packingnoteid;
              if debuglevel > 0 then
                pack_sort.write_logging(' Create new Packnote with ID ' ||
                                        packingnoteid,
                                        debuglevel,
                                        'PACK_SORT.GETGARMENTDATAINFO',
                                        plantid_garment,
                                        1,
                                        1);
              end if;
            end if;
            if createnewpackingnoteline = 'Y' then
              begin
                insert into packingnoteline
                  (packingnoteline_id,
                   product_id,
                   packingsequence,
                   finishingmethod_id,
                   price,
                   discount,
                   packingnote_id,
                   sizedefinition_id,
                   systemuser_id,
                   location,
                   timestamp,
                   remarkforpackinginstructions,
                   customcode,
                   customdescription,
                   replacementqty,
                   autoreplacementqty,
                   updaterentqty,
                   adjustmentreason_id,
                   origin,
                   putuptype,
                   freeofchargereason_id,
                   nochargefirstissue,
                   nochargeactiveseason,
                   deliveredcogqty,
                   auxiliarystatus,
                   standardamount,
                   variationamount,
                   deliveredamount,
                   tobedeliveredamount,
                   amount,
                   taxgroupcode,
                   bundleqty,
                   nochargefirstissuecog,
                   scannedbundles,
                   pricecog,
                   invoiceheader_id)
                values
                  (seq_packingnoteline.nextval,
                   productid,
                   0,
                   finishingmethodid,
                   0,
                   --
                   0,
                   --
                   packingnoteid,
                   --seq_packingnote.currval,
                   sizedefinitionid,
                   systemuserid,
                   null,
                   sysdate,
                   '',
                   plpcustomcode,
                   plpcustomdescription,
                   0,
                   --replacementqty,
                   0,
                   --autoreplacementqty,
                   0,
                   --updaterentqty,
                   null,
                   --adjustmentreason_id,
                   2,
                   1,
                   null,
                   --freeofchargereason_id,
                   0,
                   --nochargefirstissue,
                   0,
                   --nochargeactiveseason,
                   0,
                   --deliveredcogqty,
                   null,
                   --auxiliarystatus,
                   0,
                   --standardamount,
                   1,
                   --variationamount,
                   0,
                   --deliveredamount,
                   1,
                   --tobedeliveredamount,
                   0,
                   --amount,
                   null,
                   --taxgroupcode,
                   0,
                   --bundleqty,
                   0,
                   --nochargefirstissuecog,
                   0,
                   --scannedbundles,
                   0,
                   --pricecog
                   null
                   --invoiceHeader
                   );
                if debuglevel > 0 then
                  pack_sort.write_logging(' Create new Packnoteline for PN# ' ||
                                          pnnotenumber,
                                          debuglevel,
                                          'PACK_SORT.GETGARMENTDATAINFO',
                                          plantid_garment,
                                          1,
                                          1);
                end if;
              exception
                when others then
                  pack_sort.write_logging('!> Create new Packnoteline for PN# ' ||
                                          pnnotenumber || ' for IDCODE ' ||
                                          idcode || ' ' || sqlerrm,
                                          debuglevel,
                                          'PACK_SORT.GETGARMENTDATAINFO',
                                          plantid_garment,
                                          3,
                                          1);
              end;
            end if;
          end;
          if length(to_char(pnnotenumber)) <= 8 then
            char_notenumber := lpad(to_char(pnnotenumber), 8, '0');
          elsif length(to_char(pnnotenumber)) > 8 then
            char_notenumber := substr(to_char(pnnotenumber), -8, 8);
          end if;
          if (drivingdate is not null or packingday is not null) then
            if (getabsdaynumber(drivingdate) - packingday >= 0) then
              packingdatetime := drivingdate -
                                 (getabsdaynumber(drivingdate) - packingday);
            else
              packingdatetime := drivingdate - (getabsdaynumber(drivingdate) +
                                 (7 - packingday));
            end if;
          else
            if (routeday - getabsdaynumber(sysdate + 1) >= 0) then
              packingdatetime := sysdate + 1 +
                                 (routeday - getabsdaynumber(sysdate + 1));
            else
              packingdatetime := sysdate + 1 +
                                 ((7 - getabsdaynumber(sysdate + 1)) +
                                 routeday);
            end if;
          end if;
          findpackingnote := char_notenumber ||
                             substr(to_char(packingdatetime,
                                            'yyyymmddhh24miss'),
                                    1,
                                    8) || substr(to_char(rcpackingdeadline,
                                                         'yyyymmddhh24miss'),
                                                 -6,
                                                 4);
          ---daca nu e plantdepartment atunci findpackingnote ar trebui sa returneze?
        end if;
      end;
    elsif findpackingnote = 'Y' and pool <> 2 then
      findpackingnote := '';
    end if; --end of 501875 packingnote
  end getgarmentdatainfo;
  function convertstringdesc(receivedstring varchar2) return varchar2 is
    aux          varchar2(1);
    newaux       varchar2(1);
    returnstring varchar2(100);
    cnt          integer;
  begin
    returnstring := '';
    cnt          := length(receivedstring);
    if cnt > 0 then
      for i in 1 .. cnt loop
        aux := substr(receivedstring, i, 1);
        if 32 <= ascii(aux) and ascii(aux) <= 126 then
          newaux := chr(126 - (ascii(aux) - 32));
        else
          newaux := aux;
        end if;
        returnstring := returnstring || newaux;
      end loop;
    end if;
    return returnstring;
  end convertstringdesc;
  function get_sortroutestop(fp_plantid_param  in plant.plant_id%type,
                             fp_stopnumber     in stop.stopnumber%type,
                             fp_customernumber in customer.customernumber%type)
    return varchar2 is
    lv_sortstring varchar2(255);
  begin
    --Sort string --Stack change info
    begin
      select s.value
        into gv_sortroutestop
        from systemsetting s
       where s.plant_id = fp_plantid_param
         and s.name = 'SORTROUTESTOP';
    exception
      when others then
        gv_sortroutestop := 'A';
    end;
    case gv_sortroutestop
      when 'A' then
        --default is 'A' ascending
        lv_sortstring := lpad(to_char(fp_stopnumber), 6, 0) ||
                         lpad(fp_customernumber, 12, 0);
      when 'D' then
        --other option 'D' descending
        lv_sortstring := lpad(to_char(999999 - fp_stopnumber), 6, 0) ||
                         lpad(999999999999 - fp_customernumber, 12, 0);
      when 'Y' then
        --new option 'Y' is customer only export
        lv_sortstring := lpad(fp_customernumber, 12, 0);
      when 'Z' then
        --new option 'Z' no customer nor stopnumber; order#502901
        lv_sortstring := null;
      when 'S' then
        --new short option 'S', to use shorter values for different field
        --customer length 10, deliverypoint 3, wearer# 6, wearer searchname 12
        lv_sortstring := lpad(to_char(fp_stopnumber), 6, 0) ||
                         lpad(substr(to_char(fp_customernumber), 1, 10),
                              10,
                              0);
      else
        lv_sortstring := lpad(to_char(fp_stopnumber), 6, 0) ||
                         lpad(fp_customernumber, 12, 0);
    end case;
    return lv_sortstring;
  end get_sortroutestop;
  function buildsortstring(productcode          in product.code%type,
                           sizecode             in sizedefinition.code%type,
                           customernumber       in customer.customernumber%type,
                           customerid           in customer.customer_id%type,
                           wearernumber         in wearer.wearernumber%type,
                           wearername           in wearer.searchname%type,
                           banklocker           in varchar2,
                           departmentnumber     in department.departmentnumber%type,
                           customeremployee#    in wearer.customeremployeenumber%type,
                           gender               in wearer.sex%type,
                           garmentdispensercode in garmentdispenser.code%type,
                           deliverypointcode    in deliverypoint.code%type,
                           stopnumber           in routestop.stopnumber%type,
                           plantid_param        in plant.plant_id%type,
                           customerownedyn      in varchar2,
                           ordernumber          in packingnote.notenumber%type,
                           productsortgroupseq  in productsortgroupperplant.sequencenumber%type,
                           lockersortgroup#     in lockersortgroup.lockersortgroupnumber%type,
                           distributionpoint#   in distributionpoint.distributionpointnumber%type,
                           fp_sortcustomerid    in customer.sortcustomer_id%type default null,
                           --always the last parout nocopyameter must be fp_stackchange,
                           fp_stackchange in sortingdefinition.stackchange%type default 'N')
    return varchar2 is
    --replaces getsortstrings together with build stackchangeinfo
    cnt                   integer;
    customerowned10       integer;
    vwearernumber         wearer.wearernumber%type;
    vwearername           wearer.searchname%type;
    vbanklocker           varchar2(12);
    vdepartmentnumber     department.departmentnumber%type;
    vcustomeremployee#    wearer.customeremployeenumber%type;
    vgender               wearer.sex%type;
    vgarmentdispensercode garmentdispenser.code%type;
    vdeliverypointcode    deliverypoint.code%type;
    vproductcode          product.code%type;
    vsizecode             sizedefinition.code%type;
    sortstringlength      integer;
    vordernumber          packingnote.notenumber%type;
    sortstring            varchar2(255);
    vproductsortgroup     productsortgroupperplant.sequencenumber%type;
    vlockersortgroup      lockersortgroup.lockersortgroupnumber%type;
    vdistributionpoint#   distributionpoint.distributionpointnumber%type;
    lv_prodsizesequence   productsize.sequencenumber%type;
    lvcustomernumber      customer.customernumber%type;

    procedure build_string(fp_sortfield      in sortingdefinition.sortfield%type,
                           fp_sortdescending in sortingdefinition.sortdescending%type) is
      lvbanklocker varchar2(12) := vbanklocker;
    begin
      case fp_sortfield
        when 1 then
          begin
            if fp_sortdescending = 'Y' then
              vdepartmentnumber := 999999 - departmentnumber;
            else
              vdepartmentnumber := departmentnumber;
            end if;
            sortstring := sortstring ||
                          lpad(to_char(vdepartmentnumber), 6, 0);
          end;
        when 2 then
          begin
            if fp_sortdescending = 'Y' then
              vwearernumber := 999999999999 - wearernumber;
            else
              vwearernumber := wearernumber;
            end if;
            if gv_sortroutestop = 'S' then
              sortstring := sortstring ||
                            lpad(substr(to_char(vwearernumber), 1, 6), 6, 0);
            else
              sortstring := sortstring ||
                            lpad(to_char(vwearernumber), 12, 0);
            end if;
          end;
        when 3 then
          begin
            if fp_sortdescending = 'Y' then
              vwearername := convertstringdesc(rpad(wearername, 20, ' '));
            else
              vwearername := rpad(wearername, 20, ' ');
            end if;
            if gv_sortroutestop = 'S' then
              sortstring := sortstring || substr(vwearername, 1, 4);
            else
              sortstring := sortstring || vwearername;
            end if;
          end;
        when 4 then
          begin
            if fp_sortdescending = 'Y' then
              vcustomeremployee# := convertstringdesc(rpad(vcustomeremployee#,
                                                           10,
                                                           ' '));
            else
              vcustomeremployee# := rpad(vcustomeremployee#, 10, ' ');
            end if;
            sortstring := sortstring || vcustomeremployee#;
          end;
        when 5 then
          begin
            if fp_sortdescending = 'Y' then
              lvbanklocker := convertstringdesc(lvbanklocker);
            end if;
            sortstring := sortstring || lvbanklocker;
          end;
        when 6 then
          begin
            if fp_sortdescending = 'Y' then
              vgender := convertstringdesc(gender);
            else
              vgender := gender;
            end if;
            sortstring := sortstring || vgender;
          end;
        when 7 then
          begin
            if fp_sortdescending = 'Y' then
              vproductcode := convertstringdesc(rpad(productcode, 12, ' '));
            else
              vproductcode := rpad(productcode, 12, ' ');
            end if;
            sortstring := sortstring || vproductcode;
          end;
        when 8 then
          begin
            if fp_sortdescending = 'Y' then
              vsizecode := convertstringdesc(rpad(sizecode, 12, ' '));
            else
              vsizecode := rpad(sizecode, 12, ' ');
            end if;
            sortstring := sortstring || vsizecode;
          end;
        when 9 then
          begin
            if fp_sortdescending = 'Y' then
              vdeliverypointcode := convertstringdesc(rpad(deliverypointcode,
                                                           12,
                                                           ' '));
            else
              vdeliverypointcode := rpad(deliverypointcode, 12, ' ');
            end if;
            if gv_sortroutestop = 'S' then
              sortstring := sortstring || substr(vdeliverypointcode, 1, 3);
            else
              sortstring := sortstring || vdeliverypointcode;
            end if;
          end;
        when 10 then
          begin
            if fp_sortdescending = 'Y' then
              vgarmentdispensercode := convertstringdesc(rpad(garmentdispensercode,
                                                              6,
                                                              ' '));
            else
              vgarmentdispensercode := rpad(garmentdispensercode, 6, ' ');
            end if;
            sortstring := sortstring || vgarmentdispensercode;
          end;
        when 11 then
          begin
            if fp_sortdescending = 'Y' then
              customerowned10 := 9 - customerowned10;
            end if;
            sortstring := sortstring || customerowned10;
          end;
        when 12 then
          begin
            if fp_sortdescending = 'Y' then
              vordernumber := 99999999 - ordernumber;
            else
              vordernumber := ordernumber;
            end if;
            if ordernumber = 0 then
              sortstring := sortstring || '00000000';
            else
              sortstring := sortstring || lpad(to_char(vordernumber), 8, 0);
            end if;
          end;
          --order#502177
        when 13 then
          begin
            if fp_sortdescending = 'Y' then
              lvbanklocker := convertstringdesc(substr(lvbanklocker, 1, 6));
            else
              lvbanklocker := substr(lvbanklocker, 1, 6);
            end if;
            sortstring := sortstring || lvbanklocker;
          end;
        when 14 then
          begin
            if fp_sortdescending = 'Y' then
              vproductsortgroup := 999 - productsortgroupseq;
            else
              vproductsortgroup := productsortgroupseq;
            end if;
            if vproductsortgroup = 0 then
              sortstring := sortstring || '000';
            else
              sortstring := sortstring ||
                            lpad(to_char(vproductsortgroup), 3, 0);
            end if;
          end;
        when 15 then
          begin
            if fp_sortdescending = 'Y' then
              vlockersortgroup := 999 - lockersortgroup#;
            else
              vlockersortgroup := lockersortgroup#;
            end if;
            if vlockersortgroup = 0 then
              sortstring := sortstring || '000';
            else
              sortstring := sortstring ||
                            lpad(to_char(vlockersortgroup), 3, 0);
            end if;
          end;
        when 16 then
          begin
            if fp_sortdescending = 'Y' then
              vdistributionpoint# := 99 - distributionpoint#;
            else
              vdistributionpoint# := distributionpoint#;
            end if;
            if vdistributionpoint# = 0 then
              sortstring := sortstring || '00';
            else
              sortstring := sortstring ||
                            lpad(to_char(vdistributionpoint#), 2, 0);
            end if;
          end;
        when 17 then
          --order#20012684
          begin
            select nvl(max(ps.sequencenumber), 0)
              into lv_prodsizesequence
              from productsize ps
              join product p
                on p.product_id = ps.product_id
              join sizedefinition s
                on s.sizedefinition_id = ps.sizedefinition_id
             where p.code = productcode
               and s.code = sizecode;
            if fp_sortdescending = 'Y' then
              lv_prodsizesequence := 999 - lv_prodsizesequence;
            end if;
            if lv_prodsizesequence = 0 then
              sortstring := sortstring || '000';
            else
              sortstring := sortstring ||
                            lpad(substr(to_char(lv_prodsizesequence), 1, 3),
                                 3,
                                 0);
            end if;
          end;
      end case;
    end build_string;
  begin
    if fp_sortcustomerid is null then
      lvcustomernumber := customernumber;
    else
      begin
        select nvl(max(c.customernumber), 0)
          into lvcustomernumber
          from customer c
         where c.customer_id = fp_sortcustomerid;
      end;
    end if;
    --order#502901
    sortstring := get_sortroutestop(plantid_param,
                                    stopnumber,
                                    lvcustomernumber);
    --
    if customerownedyn = 'Y' then
      customerowned10 := 1;
    else
      customerowned10 := 0;
    end if;
    if customeremployee# is not null then
      vcustomeremployee# := rpad(to_char(customeremployee#), 10, ' ');
    else
      vcustomeremployee# := '          ';
    end if;
    if banklocker is null then
      vbanklocker := '            ';
    else
      vbanklocker := rpad(banklocker, 12, ' ');
    end if;
    cnt := 0;
    if fp_sortcustomerid is not null then
      for vcursor in (select s.sortfield,
                             s.sortdescending,
                             s.stackchange,
                             (select count(t.sortingdefinition_id)
                                from sortingdefinition t
                               where t.customer_id = s.customer_id
                                 and t.stackchange = 'Y') stackyescount
                        from sortingdefinition s
                       where s.customer_id = fp_sortcustomerid
                       order by s.priority asc) loop
        begin
          cnt := cnt + 1;
          exit when(fp_stackchange = 'Y' and vcursor.stackyescount = 0);
          build_string(vcursor.sortfield, vcursor.sortdescending);
          exit when fp_stackchange = 'Y' and vcursor.stackchange = 'Y';
        end;
      end loop;
    end if;
    if cnt = 0 then
      for vcursor in (select s.sortfield,
                             s.sortdescending,
                             s.stackchange,
                             (select count(t.sortingdefinition_id)
                                from sortingdefinition t
                               where t.customer_id = s.customer_id
                                 and t.stackchange = 'Y') stackyescount
                        from sortingdefinition s
                       where s.customer_id = customerid
                       order by s.priority asc) loop
        begin
          cnt := cnt + 1;
          exit when(fp_stackchange = 'Y' and vcursor.stackyescount = 0);
          build_string(vcursor.sortfield, vcursor.sortdescending);
          exit when fp_stackchange = 'Y' and vcursor.stackchange = 'Y';
        end;
      end loop;
    end if;
    if cnt = 0 then
      for vcursor in (select s.sortfield,
                             s.sortdescending,
                             s.stackchange,
                             (select count(t.sortingdefinition_id)
                                from sortingdefinition t
                               where t.plant_id = s.plant_id
                                 and t.stackchange = 'Y') stackyescount
                        from sortingdefinition s
                       where s.plant_id = plantid_param
                       order by s.priority asc) loop
        begin
          exit when(fp_stackchange = 'Y' and vcursor.stackyescount = 0);
          build_string(vcursor.sortfield, vcursor.sortdescending);
          exit when fp_stackchange = 'Y' and vcursor.stackchange = 'Y';
        end;
      end loop;
    end if;
    --order 501781
    begin
      select s.value
        into sortstringlength
        from systemsetting s
       where s.plant_id = plantid_param
         and s.name = 'SORTSTRINGLENGTH';
      if sortstringlength = 2 then
        sortstringlength := 80;
      else
        sortstringlength := 60;
      end if;
    exception
      when others then
        sortstringlength := 60;
    end;
    sortstring := substr(sortstring, 1, sortstringlength);
    return sortstring;
  end buildsortstring;
  function buildstackchangeinfo(productcode          in product.code%type,
                                sizecode             in sizedefinition.code%type,
                                customernumber       in customer.customernumber%type,
                                customerid           in customer.customer_id%type,
                                wearernumber         in wearer.wearernumber%type,
                                wearername           in wearer.searchname%type,
                                banklocker           in varchar2,
                                departmentnumber     in department.departmentnumber%type,
                                customeremployee#    in wearer.customeremployeenumber%type,
                                gender               in wearer.sex%type,
                                garmentdispensercode in garmentdispenser.code%type,
                                deliverypointcode    in deliverypoint.code%type,
                                stopnumber           in routestop.stopnumber%type,
                                plantid_param        in plant.plant_id%type,
                                customerownedyn      in varchar2,
                                ordernumber          in packingnote.notenumber%type,
                                productsortgroupseq  in productsortgroupperplant.sequencenumber%type default 0,
                                lockersortgroup#     in lockersortgroup.lockersortgroupnumber%type default 0,
                                distributionpoint#   in distributionpoint.distributionpointnumber%type default 0,
                                fp_sortcustomerid    in customer.sortcustomer_id%type default null)
    return varchar2 is
  begin
    --replaces getsortstrings this one builds stackchangeinfo
    return pack_sort.buildsortstring(productcode,
                                     sizecode,
                                     customernumber,
                                     customerid,
                                     wearernumber,
                                     wearername,
                                     banklocker,
                                     departmentnumber,
                                     customeremployee#,
                                     gender,
                                     garmentdispensercode,
                                     deliverypointcode,
                                     stopnumber,
                                     plantid_param,
                                     customerownedyn,
                                     ordernumber,
                                     productsortgroupseq,
                                     lockersortgroup#,
                                     distributionpoint#,
                                     fp_sortcustomerid,
                                     'Y');
  end buildstackchangeinfo;
  function getsortstring(plantid_param in plant.plant_id%type,
                         customerid    in customer.customer_id%type,
                         routestopid   in routestop.routestop_id%type,
                         uniqueitemid  in uniqueitem.uniqueitem_id%type)
    return varchar2 is
    sortstring           varchar2(255);
    productcode          product.code%type;
    sizecode             sizedefinition.code%type;
    customernumber       customer.customernumber%type;
    wearernumber         wearer.wearernumber%type;
    wearername           wearer.searchname%type;
    banklocker           varchar2(12);
    departmentnumber     department.departmentnumber%type;
    customeremployee#    wearer.customeremployeenumber%type;
    gender               wearer.sex%type;
    garmentdispensercode garmentdispenser.code%type;
    deliverypointcode    deliverypoint.code%type;
    lockerid             locker.locker_id%type;
    garmentdispenserid   garmentdispenser.garmentdispenser_id%type;
    deliverypointid      deliverypoint.deliverypoint_id%type;
    stopnumber           routestop.stopnumber%type;
    packingsequence      product.packingsequence%type;
    vcustomerowned       varchar2(1);
    vordernumber         packingnote.notenumber%type;
    productsortgroupseq  productsortgroupperplant.sequencenumber%type;
    lockersortgroup#     lockersortgroup.lockersortgroupnumber%type;
    distributionpoint#   distributionpoint.distributionpointnumber%type;
  begin
    sortstring := '';
    begin
      begin
        select p.code,
               s.code,
               w.wearernumber,
               w.searchname,
               w.customeremployeenumber,
               w.sex,
               (select d.departmentnumber
                  from department d, distributionpoint di
                 where di.distributionpoint_id =
                       coalesce(e.distributionpoint_id,
                                u.distributionpoint_id)
                   and di.department_id = d.department_id),
               e.deliverypoint_id,
               e.locker_id,
               e.garmentdispenser_id,
               p.packingsequence,
               u.customerowned,
               nvl(psgp.sequencenumber, 0),
               nvl(lsg.lockersortgroupnumber, 0),
               (select di.distributionpointnumber
                  from distributionpoint di
                 where di.distributionpoint_id =
                       coalesce(e.distributionpoint_id,
                                u.distributionpoint_id)) distributionpointnumber,
               (select c.customernumber
                  from customer c
                 where c.customer_id = coalesce(w.customer_id, customerid)) customernumber
          into productcode,
               sizecode,
               wearernumber,
               wearername,
               customeremployee#,
               gender,
               departmentnumber,
               deliverypointid,
               lockerid,
               garmentdispenserid,
               packingsequence,
               vcustomerowned,
               productsortgroupseq,
               lockersortgroup#,
               distributionpoint#,
               customernumber
          from uniqueitem u
          left outer join(uniqueitemnonpool n
          join weareremployment e
            on e.weareremployment_id = n.weareremployment_id
          join wearer w
            on w.wearer_id = e.wearer_id) on n.uniqueitem_id = u.uniqueitem_id
          left outer join(locker l
          join lockersortgroup lsg
            on lsg.lockersortgroup_id = l.lockersortgroup_id) on e.locker_id = l.locker_id
          join product p
            on p.product_id = u.product_id
          left outer join productsortgroupperplant psgp
            on (psgp.productsortgroup_id = p.productsortgroup_id and
               psgp.plant_id = plantid_param)
          join sizedefinition s
            on s.sizedefinition_id = u.sizedefinition_id
         where u.uniqueitem_id = uniqueitemid;
      exception
        when no_data_found then
          sortstring := '01';
      end;
      if sortstring is null then
        pack_sort.getgarmentlocation(lockerid,
                                     garmentdispenserid,
                                     deliverypointid,
                                     banklocker,
                                     garmentdispensercode,
                                     deliverypointcode);
        begin
          select rs.stopnumber
            into stopnumber
            from routestop rs
           where rs.routestop_id = routestopid;
        exception
          when no_data_found then
            sortstring := '02';
        end;
      end if;
      --Sort string
      if sortstring is null then
        begin
          sortstring := pack_sort.buildsortstring(productcode,
                                                  sizecode,
                                                  customernumber,
                                                  customerid,
                                                  wearernumber,
                                                  wearername,
                                                  banklocker,
                                                  departmentnumber,
                                                  customeremployee#,
                                                  gender,
                                                  garmentdispensercode,
                                                  deliverypointcode,
                                                  stopnumber,
                                                  plantid_param,
                                                  vcustomerowned,
                                                  vordernumber,
                                                  productsortgroupseq,
                                                  lockersortgroup#,
                                                  distributionpoint#);
        end;
      end if;
    exception
      when others then
        sortstring := '0';
    end;
    return(sortstring);
  end getsortstring;
  procedure getdeliverydaysmask(customerid      in customer.customer_id%type,
                                deliverydaymask out nocopy varchar2) is
    aux varchar2(8);
  begin
    -- delivery day mask
    deliverydaymask := 'NNNNNNN';
    for vcursor in (select x.day_id
                      from customerdeliveryday x
                     where x.customer_id = customerid
                       and x.typeofmerchadise = 2) loop
      begin
        aux             := replace(substr(deliverydaymask,
                                          vcursor.day_id,
                                          1),
                                   'N',
                                   'Y');
        deliverydaymask := substr(deliverydaymask, 1, vcursor.day_id - 1) || aux ||
                           substr(deliverydaymask, vcursor.day_id + 1, 7);
      end;
    end loop;
  end getdeliverydaysmask;
  procedure getdepot(routeid in route.route_id%type,
                     depot   out nocopy depot.code%type) is
  begin
    --depot
    select d.code
      into depot
      from depot d, route r
     where r.route_id = routeid
       and r.depot_id = d.depot_id;
  exception
    when no_data_found then
      depot := 0;
  end getdepot;
  --update flags
  function updateflags(flagsstring    in varchar2,
                       uniqueitemid   in uniqueitem.uniqueitem_id%type,
                       fplastscandate in date,
                       systemuserid   in systemuser.systemuser_id%type,
                       debuglevel     in integer) return integer is
    statusout    integer;
    flagcode     flag.code%type;
    aux          varchar2(500);
    laststring   varchar2(300);
    flagid       flag.flag_id%type;
    flaginserted boolean;
  begin
    statusout  := 0;
    laststring := flagsstring;
    while laststring is not null loop
      --aux := substr(laststring, 1, instr(laststring, chr(10), 1) - 1);
      aux := replace(laststring, chr(10));
      if aux is null then
        flagcode   := null;
        laststring := null;
      else
        flagcode   := substr(aux, 1, instr(aux, ':', 1) - 1);
        aux        := aux || chr(13) || chr(10);
        laststring := ltrim(laststring, aux);
      end if;
      flagid := null;
      begin
        begin
          select f.flag_id
            into flagid
            from flag f
           where f.code = flagcode
             and not exists (select u.flag_id
                    from uniqueitemflag u
                   where u.uniqueitem_id = uniqueitemid
                     and u.flag_id = f.flag_id);
        exception
          when no_data_found then
            null;
        end;
        if flagid is not null then
          flaginserted := pack_sort.create_uniqueitemflag('PACK_SORT.UPDATEFLAGS',
                                                          debuglevel,
                                                          systemuserid,
                                                          uniqueitemid,
                                                          flagid,
                                                          fplastscandate);
        end if;
      exception
        when others then
          begin
            statusout := 1;
            pack_sort.write_logging(' NOT insert uniqueitemflag - scanflag for uniqueitemID/flagID ' ||
                                    uniqueitemid || '/' || flagid,
                                    debuglevel,
                                    'PACK_SORT.UPDATEFLAGS',
                                    null,
                                    3,
                                    1);
          end;
      end;
    end loop;
    return(statusout);
  end updateflags;
  procedure getsendtrackinfo(pool                 in uniqueitem.poolitem%type,
                             uniqueitemid         in uniqueitem.uniqueitem_id%type,
                             stayid               out nocopy stay.stay_id%type,
                             statusid             out nocopy status.status_id%type,
                             productid            out nocopy product.product_id%type,
                             sizeid               out nocopy sizedefinition.sizedefinition_id%type,
                             weareremploymentid   out nocopy weareremployment.weareremployment_id%type,
                             customerid           out nocopy customer.customer_id%type,
                             vissuedate           out nocopy date,
                             finishingmethodid    out nocopy finishingmethod.finishingmethod_id%type,
                             distributionpointid  out nocopy distributionpoint.distributionpoint_id%type,
                             lastdistribpointid   out nocopy distributionpoint_link.distributionpoint_link_id%type,
                             vwashestotal         out nocopy integer,
                             vcustomerowned       out nocopy varchar2,
                             qualitygradeid       out nocopy qualitygrade.qualitygrade_id%type,
                             vfirstissuedate      out nocopy date,
                             vnumberofissues      out nocopy integer,
                             vlastonstockdate     out nocopy date,
                             vdaysinstockprevious out nocopy integer,
                             vstatuschangedate    out nocopy date,
                             vstartrentfrom       out nocopy integer,
                             vdaysincircprevissue out nocopy integer,
                             vwashesthisissue     out nocopy integer,
                             unrelatedloanid      out nocopy unrelatedloan.unrelatedloan_id%type,
                             vlastinscandate      out nocopy date,
                             deliverypointid      out nocopy deliverypoint.deliverypoint_id%type,
                             lockerid             out nocopy locker.locker_id%type,
                             garmentdispenserid   out nocopy garmentdispenser.garmentdispenser_id%type,
                             accept               in out varchar2) is
  begin
    if pool = 2 then
      --nonpool
      begin
        select u.product_id,
               u.sizedefinition_id,
               u.finishingmethod_id,
               n.weareremployment_id,
               w.customer_id,
               f.lastissuedate,
               u.lastinscandate,
               u.stay_id,
               u.status_id,
               u.statuschangedate,
               u.washestotal,
               u.customerowned,
               f.qualitygrade_id,
               f.firstissuedate,
               f.numberofissues,
               f.lastonstockdate,
               f.daysinstockprevious,
               f.daysincircprevissue,
               n.washesthisissue,
               u.unrelatedloan_id,
               u.startrentfrom,
               e.distributionpoint_id,
               e.deliverypoint_id,
               e.locker_id,
               e.garmentdispenser_id
          into productid,
               sizeid,
               finishingmethodid,
               weareremploymentid,
               customerid,
               vissuedate,
               vlastinscandate,
               stayid,
               statusid,
               vstatuschangedate,
               vwashestotal,
               vcustomerowned,
               qualitygradeid,
               vfirstissuedate,
               vnumberofissues,
               vlastonstockdate,
               vdaysinstockprevious,
               vdaysincircprevissue,
               vwashesthisissue,
               unrelatedloanid,
               vstartrentfrom,
               distributionpointid,
               deliverypointid,
               lockerid,
               garmentdispenserid
          from uniqueitem          u,
               uniqueitemnonpool   n,
               uniqueitemfixedinfo f,
               weareremployment    e,
               wearer              w
         where u.uniqueitem_id = uniqueitemid
           and u.uniqueitem_id = n.uniqueitem_id
           and n.weareremployment_id = e.weareremployment_id
           and e.wearer_id = w.wearer_id
           and u.uniqueitem_id = f.uniqueitem_id;
      exception
        when no_data_found then
          accept := 'N';
          pack_sort.write_logging('!> ' || uniqueitemid ||
                                  ' No data found',
                                  1,
                                  'PACK_SORT.GETSENDTRACKINFO',
                                  null,
                                  3,
                                  1);
      end;
    else
      --pool
      begin
        select u.relatedcustomer_id,
               u.product_id,
               u.sizedefinition_id,
               u.finishingmethod_id,
               f.lastissuedate,
               u.distributionpoint_id,
               u.lastdistributionpoint_link_id,
               u.lastinscandate,
               u.stay_id,
               u.status_id,
               u.statuschangedate,
               u.washestotal,
               u.customerowned,
               f.qualitygrade_id,
               f.firstissuedate,
               f.numberofissues,
               f.lastonstockdate,
               f.daysinstockprevious,
               f.daysincircprevissue,
               u.unrelatedloan_id,
               u.startrentfrom
          into customerid,
               productid,
               sizeid,
               finishingmethodid,
               vissuedate,
               distributionpointid,
               lastdistribpointid,
               vlastinscandate,
               stayid,
               statusid,
               vstatuschangedate,
               vwashestotal,
               vcustomerowned,
               qualitygradeid,
               vfirstissuedate,
               vnumberofissues,
               vlastonstockdate,
               vdaysinstockprevious,
               vdaysincircprevissue,
               unrelatedloanid,
               vstartrentfrom
          from uniqueitem u, uniqueitemfixedinfo f
         where u.uniqueitem_id = uniqueitemid
           and u.uniqueitem_id = f.uniqueitem_id;
        if customerid is null then
          if distributionpointid is not null then
            select e.customer_id
              into customerid
              from distributionpoint d, department e
             where distributionpointid = d.distributionpoint_id
               and d.department_id = e.department_id;
          elsif lastdistribpointid is not null then
            select e.customer_link_id
              into customerid
              from distributionpoint_link d, department_link e
             where lastdistribpointid = d.distributionpoint_id
               and d.department_link_id = e.department_link_id;
          end if;
        end if;
      exception
        when no_data_found then
          accept := 'N';
          pack_sort.write_logging('!> ' || uniqueitemid || ' ' || sqlerrm,
                                  1,
                                  'PACK_SORT.GETSENDTRACKINFO',
                                  null,
                                  3,
                                  1);
      end;
    end if;
  end getsendtrackinfo;
  procedure writelogfile(sortsystem           in varchar2,
                         debuglevel           in integer,
                         plantcode            in plant.code%type,
                         idcode               in uniqueitem.primaryid%type,
                         unitcode             in businessunit.code%type,
                         status               in varchar2,
                         finishselection      in varchar2,
                         checkpointselection  in varchar2,
                         repairselection      in varchar2,
                         destination          in varchar2,
                         fold                 in varchar2,
                         stackchangeinfo      in varchar2,
                         routenumber          in integer,
                         stopnumber           in integer,
                         routeday             in day.daynumber%type,
                         depot                in varchar2,
                         sortstring           in varchar2,
                         alternatesortstring  in varchar2,
                         customernumber       in customer.customernumber%type,
                         customername         in customer.name%type,
                         wearernumber         in wearer.wearernumber%type,
                         wearername           in wearer.searchname%type,
                         department           in department.departmentnumber%type,
                         customeremployee#    in wearer.customeremployeenumber%type,
                         gender               in wearer.sex%type,
                         banklocker           in varchar2,
                         garmentdispensercode in garmentdispenser.code%type,
                         deliverypointcode    in deliverypoint.code%type,
                         productcode          in product.code%type,
                         productdescription   in product_desc.description%type,
                         sizecode             in sizedefinition.code%type,
                         productpicturecode   in image.code%type,
                         deliverydaymask      in varchar2,
                         secondaryid          in secondaryuniqueitem.secondaryid%type,
                         flagcode1            in sortaddressperflag.sortaddress%type,
                         flagcode2            in sortaddressperflag.sortaddress%type,
                         flagcode3            in sortaddressperflag.sortaddress%type,
                         flagcode4            in sortaddressperflag.sortaddress%type,
                         flagdescription1     in flag_desc.description%type,
                         flagdescription2     in flag_desc.description%type,
                         flagdescription3     in flag_desc.description%type,
                         flagdescription4     in flag_desc.description%type,
                         infotext             in wearer.remark%type,
                         requiredrepairs      in varchar2,
                         flags                in varchar2,
                         staycode             in varchar2,
                         sortbatchnumber      in integer,
                         spare2               in varchar2) is
  begin
    if debuglevel > 0 then
      pack_sort.write_logging('PlantCode ' || plantcode || ' IDCode ' ||
                              idcode || ' UnitCode ' || unitcode ||
                              ' Status ' || status || case sortsystem when
                              'METRIC' then
                              ' FinishSelection ' || finishselection ||
                              ' FoldProgram ' || fold || ' Depot' || depot ||
                              ' ProductPicture ' || productpicturecode ||
                              ' DeliveryDayMask ' || deliverydaymask ||
                              ' SecondaryID ' || secondaryid ||
                              ' FlagCode1 ' || flagcode1 || ' FlagCode2 ' ||
                              flagcode2 || ' FlagCode3 ' || flagcode3 ||
                              ' FlagCode4 ' || flagcode4 || ' FlagDescr1 ' ||
                              flagdescription1 || ' FlagDescr2 ' ||
                              flagdescription2 || ' FlagDescr3 ' ||
                              flagdescription3 || ' FlagDescr4 ' ||
                              flagdescription4 when 'KANNEGIESSER' then
                              ' FinisherSelection ' || finishselection ||
                              ' Fold ' || fold || ' Flags' || flags when
                              'SORTBATCH' then
                              ' StayCode ' || staycode || ' SortBatch# ' ||
                              sortbatchnumber else null
                              end || ' StackChangeInfo' || stackchangeinfo ||
                              ' Route# ' || routenumber || ' Stop# ' ||
                              stopnumber || ' RouteDay ' || routeday ||
                              ' SortString ' || sortstring ||
                              ' AlternateSortString ' ||
                              alternatesortstring || ' Customer# ' ||
                              customernumber || ' CustomerName ' ||
                              customername || ' Wearer# ' || wearernumber ||
                              ' WearerName ' || wearername || ' info ' ||
                              infotext || ' Department# ' || department ||
                              ' CustomerEmployee# ' || customeremployee# ||
                              '  Gender ' || gender || ' BankLocker ' ||
                              trim(banklocker) || ' GarmentDispenserCode ' ||
                              trim(garmentdispensercode) ||
                              ' DeliveryPointCode ' ||
                              trim(deliverypointcode) || ' Product ' ||
                              productcode || ' ProductDescr ' ||
                              productdescription || ' Size ' || sizecode || case when
                              spare2 <> ' ' then
                              ' OrderInformation ' || spare2 else null
                              end || ' CheckpointSelection ' ||
                              checkpointselection || ' RepairSel. ' ||
                              repairselection || ' Dest. ' || destination ||
                              ' RequiredRepairs ' || requiredrepairs,
                              debuglevel,
                              'PACK_SORT.WRITELOGFILE',
                              null,
                              1,
                              1);
    end if;
  end writelogfile;
  function iscustomer_nonbusinessday(customerid  customer.customer_id%type,
                                     planneddate date) return boolean is
    nonbusinessday date;
  begin
    begin
      select A.NONBUSINESSDAY
        into nonbusinessday
        from NONBUSINESSDAY A, CUSTOMER B, BUSINESSUNIT C
       WHERE B.CUSTOMER_ID = customerid
         AND B.DEFAULTBUSINESSUNIT_ID = C.BUSINESSUNIT_ID
         AND A.PLANT_ID = C.PLANT_ID
         AND nvl(A.CUSTOMER_ID, 0) = 0
         and nvl(A.DEPARTMENT_ID, 0) = 0
         AND A.NONBUSINESSDAY = planneddate
         AND NOT EXISTS (select NONBUSINESSDAY_ID
                from NONBUSINESSDAY
               WHERE CUSTOMER_ID = customerid
                 AND nvl(DEPARTMENT_ID, 0) = 0
                 AND NONBUSINESSDAY = planneddate
                 AND CLOSESTATUS = 3)
      UNION
      select A.NONBUSINESSDAY
        from NONBUSINESSDAY A
       WHERE A.CUSTOMER_ID = customerid
         AND nvl(DEPARTMENT_ID, 0) = 0
         AND A.NONBUSINESSDAY = planneddate
         AND (A.CLOSESTATUS = 1 OR A.CLOSESTATUS = 2);
    exception
      when no_data_found then
        return false;
    end;
    return true;
  end iscustomer_nonbusinessday;
  function iscustomervisitdate(customerid  customer.customer_id%type,
                               planneddate date) return boolean is
    xyear integer;
    xweek integer;
    xday  integer;
    i     integer;
  begin
    i     := 0;
    xday  := getabsdaynumber(planneddate);
    xweek := getisoweek(planneddate);
    xyear := getyearofweek(planneddate);
    for dcursor in (select d.deliveryscheme_id,
                           x.frequency,
                           x.offsetweek,
                           c.day_id
                      from customerdeliveryday    c,
                           customerdeliveryscheme d,
                           deliveryscheme         x
                     where c.customer_id = customerid
                       and c.customer_id = d.customer_id
                       and c.day_id = d.day_id
                       and d.deliveryscheme_id = x.deliveryscheme_id
                       and c.day_id = xday) loop
      begin
        if isweekdeliveryweek(xyear,
                              xweek,
                              dcursor.frequency,
                              dcursor.offsetweek) then
          i := 1;
          exit;
        end if;
      end;
    end loop;
    if i = 1 then
      return true;
    else
      return false;
    end if;
  end iscustomervisitdate;
  --  procedure
  function createroutecontrol(plannedroute    in route.route_id%type,
                              planneddate     in date,
                              plantid_garment in plant.plant_id%type,
                              systemuserid    in systemuser.systemuser_id%type,
                              debuglevel      in varchar2,
                              idcode          in uniqueitem.primaryid%type)
    return number is
    routecontrolid        routecontrol.routecontrol_id%type;
    vpackingday           integer;
    vloadingdock          route.loadingdock%type;
    vpackingdeadline      date;
    driverid              employee.employee_id%type;
    vdrivernumber         employee.employeenumber%type;
    instructions          routestop.routelistinstructions%type;
    truckid               truck.truck_id%type;
    vtruckcode            truck.code%type;
    vroutecontrolcreation varchar2(1);
    lv_stopid             stop.stop_id%type;
    vstatus               integer;
  begin
    if plannedroute is null then
      return null; --do not create routecontrol
    else
      begin
        begin
          select r.routecontrol_id
            into routecontrolid
            from routecontrol r
           where r.route_id = plannedroute
             and trunc(r.drivingdate) = trunc(planneddate);
          return routecontrolid; --return existing route control
        exception
          when no_data_found then
            null; --continue to create it
        end;
        select s.value
          into vroutecontrolcreation
          from systemsetting s
         where s.plant_id = plantid_garment
           and s.name = 'ROUTECONTROLCREATION';
        if vroutecontrolcreation < 3 then
          return null; --do not create routecontrol
        end if; --vroutecontrolcreation <> 3
      end;
    end if; --plannedroute is null
    ---- create RouteControl
    select r.packingday_id,
           r.loadingdock,
           r.packingdeadline,
           r.driver_id,
           r.truck_id
      into vpackingday, vloadingdock, vpackingdeadline, driverid, truckid
      from route r
     where r.route_id = plannedroute;
    if driverid is not null then
      select e.employeenumber
        into vdrivernumber
        from employee e
       where e.employee_id = driverid;
    end if;
    if truckid is not null then
      -- LCO, todo 8189
      select t.code
        into vtruckcode
        from truck t
       where t.truck_id = truckid;
    end if;
    select seq_routecontrol.nextval into routecontrolid from dual;
    insert into routecontrol
      (routecontrol_id,
       route_id,
       routelistprinted,
       soilticketsprinted,
       soilcountstatus,
       settlementstatus,
       packingstatus,
       originaldrivingdate,
       drivingdate,
       packingday_id,
       timestamp,
       systemuser_id,
       overageamount,
       voucheramount,
       totalcashcollected,
       totalcoddelayed,
       totalcodpaythisamnt,
       totalcodundelivered,
       totalcodplusadj,
       totalcodminusadj,
       totalcodprebilled,
       totalchargecollections,
       totalchargepaythisamnt,
       totalchargeundelivered,
       totalchargeplusadj,
       totalchargeminusadj,
       totalchargeprebilled,
       returntime,
       returndate,
       starttime,
       loadingdock,
       packingdeadline,
       truckcode,
       drivernumber,
       plant_id,
       invoicesgenerated,
       arbalance_id,
       pocketpcstatus,
       startmileage,
       endmileage,
       straightevenreturnstatus,
       routesettlementprinted,
       activestockcompleted,
       bulkputuproutecompleted,
       safetyremarks)
    values
      (routecontrolid,
       plannedroute,
       'N',
       'N',
       1,
       1,
       1,
       trunc(planneddate),
       trunc(planneddate),
       vpackingday,
       sysdate,
       systemuserid,
       0,
       0,
       0,
       0,
       0,
       0,
       0,
       0,
       0,
       0,
       0,
       0,
       0,
       0,
       0,
       null,
       null,
       null,
       vloadingdock,
       vpackingdeadline,
       vtruckcode,
       vdrivernumber,
       plantid_garment,
       1,
       null,
       0,
       0,
       0,
       0,
       'N',
       'N',
       'N',
       null);
    if debuglevel > 0 then
      pack_sort.write_logging(' insert routecontrol for route ' ||
                              plannedroute,
                              debuglevel,
                              'PACK_SORT.ROUTECONTROLCREATION',
                              plantid_garment,
                              1,
                              1);
    end if;
    --insert stops for routecontrol
    for stopcursor in (select rs.routestop_id,
                              rs.stopnumber,
                              rs.customer_id,
                              rs.deliverypoint_id,
                              rs.routelistinstructions,
                              rs.instructionsstartdate,
                              rs.instructionsenddate,
                              rs.contactperson_id,
                              rs.stoptype,
                              rs.chargedeliveryfee
                         from routestop rs
                        where rs.route_id = plannedroute
                          and rs.dateactive <= planneddate
                          and rs.dateinactive >= planneddate
                          and rs.stoptype <> 4 -- not incidental
                       ) loop
      begin
        --check for customer active
        /*check for customer active and for stop status - TD 25261*/
        vstatus := pack_sort.getstopstatus(stopcursor.customer_id,
                                           trunc(planneddate));
        if vstatus >= 0 and --pack_sort.iscustomeractive(stopcursor.customer_id, trunc(planneddate)) and
           pack_sort.iscustomervisitdate(stopcursor.customer_id,
                                         trunc(planneddate)) then
          if (trunc(planneddate) >= stopcursor.instructionsstartdate and
             trunc(planneddate) <= stopcursor.instructionsenddate) then
            instructions := stopcursor.routelistinstructions;
          else
            instructions := null;
          end if;
          insert into stop
            (stop_id,
             routecontrol_id,
             routestop_id,
             customer_link_id,
             stopnumber,
             arrivaltime,
             departuretime,
             travelminutes,
             visitminutes,
             routelistinstructions,
             systemuser_id,
             timestamp,
             movedtostop_id,
             status,
             deliverypoint_id,
             contactperson_id,
             stoptype,
             chargedeliveryfee)
          values
            (seq_stop.nextval,
             routecontrolid,
             stopcursor.routestop_id,
             stopcursor.customer_id,
             stopcursor.stopnumber,
             null,
             null,
             0,
             0,
             instructions,
             systemuserid,
             sysdate,
             null,
             vstatus,
             stopcursor.deliverypoint_id,
             stopcursor.contactperson_id,
             stopcursor.stoptype,
             stopcursor.chargedeliveryfee)
          returning stop_id into lv_stopid;
          --link packingnotes to routecontrol
          update packingnote up
             set up.routecontrol_id = routecontrolid,
                 up.stop_id         = lv_stopid,
                 up.stopnumber      = stopcursor.stopnumber,
                 up.timestamp       = sysdate,
                 up.systemuser_id   = systemuserid
           where up.packingnote_id in
                 (select p.packingnote_id
                    from packingnote p, deliverypoint delp
                   where p.route_id = plannedroute
                     and p.deliverydate = planneddate
                     and p.deliverypoint_id =
                         coalesce(stopcursor.deliverypoint_id,
                                  p.deliverypoint_id)
                     and p.routecontrol_id is null
                     and p.deliverypoint_id = delp.deliverypoint_id
                     and delp.customer_id = stopcursor.customer_id);
          --link ClientDeliveryNote to routecontrol
          update clientdeliverynote cdn
             set cdn.routecontrol_id = routecontrolid,
                 cdn.stop_id         = lv_stopid,
                 cdn.stopnumber      = stopcursor.stopnumber,
                 cdn.timestamp       = sysdate,
                 cdn.systemuser_id   = systemuserid
           where cdn.clientdeliverynote_id in
                 (select cdnl.clientdeliverynote_id
                    from clientdeliverynote cdnl, deliverypoint delp
                   where cdnl.route_id = plannedroute
                     and cdnl.deliverydate = planneddate
                     and delp.deliverypoint_id =
                         coalesce(stopcursor.deliverypoint_id,
                                  delp.deliverypoint_id)
                     and cdnl.routecontrol_id is null
                     and delp.deliverypoint_id =
                         (select dp.deliverypoint_id
                            from clientresident    cr,
                                 departmentroom    de,
                                 department        d,
                                 distributionpoint dp
                           where cdnl.customer_link_id =
                                 stopcursor.customer_id
                             and cdnl.client_link_id = cr.client_id
                             and cr.departmentroom_id = de.departmentroom_id
                             and de.department_id = d.department_id
                             and de.distributionpoint_id =
                                 dp.distributionpoint_id
                          union
                          select cp.deliverypoint_id
                            from clientprivateperson cp
                           where cdnl.customer_link_id =
                                 stopcursor.customer_id
                             and cdnl.client_link_id = cp.client_id));
          --link straightevenreturn to routecontrol
          update straightevenreturn us
             set us.stop_id       = lv_stopid,
                 us.timestamp     = sysdate,
                 us.systemuser_id = systemuserid
           where us.straightevenreturn_id in
                 (select s.straightevenreturn_id
                    from straightevenreturn s,
                         status             st,
                         distributionpoint  di,
                         department         d
                   where s.stop_id is null
                     and s.pickupdate <= planneddate
                     and di.distributionpoint_id = s.distributionpoint_id
                     and d.department_id = di.department_id
                     and d.customer_id = stopcursor.customer_id
                     and (di.deliverypoint_id = stopcursor.deliverypoint_id or
                         stopcursor.deliverypoint_id is null)
                     and s.status_id = st.status_id
                     and st.code = '10');
        end if;
      end;
    end loop;
    return(routecontrolid);
  exception
    when others then
      begin
        -- order 20014102
        pack_sort.write_logging('!> error during createroutecontrol for idcode ' ||
                                idcode || ' ' || sqlerrm,
                                debuglevel,
                                'PACK_SORT.ROUTECONTROLCREATION',
                                plantid_garment,
                                3,
                                1);
        return null;
      end;
  end createroutecontrol;
  procedure createscanflag(vscanflagid  in scan.scan_id%type,
                           systemuserid in systemuser.systemuser_id%type,
                           debuglevel   in integer,
                           flagcode1    in sortaddressperflag.sortaddress%type,
                           flagcode2    in sortaddressperflag.sortaddress%type,
                           flagcode3    in sortaddressperflag.sortaddress%type,
                           flagcode4    in sortaddressperflag.sortaddress%type,
                           plantid      in plant.plant_id%type) is
    type flagcodes_type is varray(4) of sortaddressperflag.sortaddress%type;
    flagcodes flagcodes_type;
  begin
    flagcodes := flagcodes_type(flagcode1, flagcode2, flagcode3, flagcode4);
    for i in 1 .. 4 loop
      if (flagcodes(i) is not null) then
        begin
          insert into scanflag
            (scan_id, flag_id, flagresponse, systemuser_id, timestamp)
            select vscanflagid, f.flag_id, null, systemuserid, sysdate
              from flag f, sortaddressperflag s
             where f.flagtype = 1
               and f.flag_id = s.flag_id
               and s.sortaddress = flagcodes(i)
               and s.plant_id = plantid;
          if debuglevel > 0 then
            pack_sort.write_logging(' inserted scanflag(s) ' ||
                                    sql%rowcount || ' for scanid ' ||
                                    vscanflagid,
                                    debuglevel,
                                    'PACK_SORT.CREATESCANFLAG',
                                    plantid,
                                    1,
                                    1);
          end if;
        exception
          when dup_val_on_index then
            null; --no problem scan flag is already there
          when no_data_found then
            pack_sort.write_logging(' flagcode ' || flagcodes(i) ||
                                    ' not found',
                                    debuglevel,
                                    'PACK_SORT.CREATESCANFLAG',
                                    plantid,
                                    3,
                                    1);
        end;
      end if;
    end loop;
  end createscanflag;
  procedure add_scanflag(fp_scanid       in scan.scan_id%type,
                         fp_uniqueitemid in uniqueitem.uniqueitem_id%type,
                         fp_dialogcode   in dialogs.code%type,
                         fp_plantid      in plant.plant_id%type,
                         fp_systemuserid in systemuser.systemuser_id%type) is
    lv_counter number;
    lv_remove  flagoptions.remove%type;
  begin
    --get the uniqueitem flags
    for vcursor in (select uif.flag_id, uif.rowid
                      from uniqueitemflag uif
                     where uif.startdate <= sysdate
                       and uif.uniqueitem_id = fp_uniqueitemid) loop
      begin
        --first we check the plantflagoptions, if exist, ok use em.
        select count(1), nvl(max(po.remove), 'N')
          into lv_counter, lv_remove
          from plantflagoptions po
          join dialogs d
            on d.dialog_id = po.dialog_id
         where po.flag_id = vcursor.flag_id
           and po.plant_id = fp_plantid
           and d.garmentscan = 'Y'
           and d.code = fp_dialogcode;
        if nvl(lv_counter, 0) = 0 then
          --not found then check the options on flagoptions level
          select count(1), nvl(max(o.remove), 'N')
            into lv_counter, lv_remove
            from flagoptions o
            join dialogs d
              on d.dialog_id = o.dialog_id
           where o.flag_id = vcursor.flag_id
             and d.garmentscan = 'Y'
             and d.code = fp_dialogcode;
        end if;
        if nvl(lv_counter, 0) >= 1 then
          --add the scan flag
          insert into scanflag
            (scan_id, flag_id, flagresponse, systemuser_id, timestamp)
          values
            (fp_scanid, vcursor.flag_id, null, fp_systemuserid, sysdate);
        end if;
        if nvl(lv_remove, 'N') = 'Y' then
          begin
            --flag must be removed
            delete from uniqueitemflag uf
             where uf.uniqueitem_id = fp_uniqueitemid
               and uf.flag_id = vcursor.flag_id
               and rowid = vcursor.rowid;
          end;
        end if;
      exception
        when no_data_found then
          null; --nothing to be done
        when dup_val_on_index then
          null; --was already there
      end;
    end loop;
  end add_scanflag;
  procedure processcheckpointscan(transactiontp   in sortingimportdefinition.transactiontype%type,
                                  idcode          in uniqueitem.primaryid%type,
                                  pool            in integer,
                                  secondaryid     in secondaryuniqueitem.secondaryid%type,
                                  businessunitid  in businessunit.businessunit_id%type,
                                  uniqueitemid    in uniqueitem.uniqueitem_id%type,
                                  workstationcode in workstation.code%type,
                                  datep           in number,
                                  timep           in varchar2, --number,
                                  systemuserid    in systemuser.systemuser_id%type,
                                  debuglevel      in integer,
                                  accept          out varchar2,
                                  scanbyroute     in varchar2,
                                  plantid_garment in plant.plant_id%type,
                                  flagcode1       in sortaddressperflag.sortaddress%type default null,
                                  flagcode2       in sortaddressperflag.sortaddress%type default null,
                                  flagcode3       in sortaddressperflag.sortaddress%type default null,
                                  flagcode4       in sortaddressperflag.sortaddress%type default null) is
    stayid                    stay.stay_id%type;
    statusid                  status.status_id%type;
    assigned                  status.status_id%type;
    incirc                    status.status_id%type;
    productid                 product.product_id%type;
    sizeid                    sizedefinition.sizedefinition_id%type;
    weareremploymentid        weareremployment.weareremployment_id%type;
    customerid                customer.customer_id%type;
    vissuedate                date;
    finishingmethodid         finishingmethod.finishingmethod_id%type;
    distributionpointid       distributionpoint.distributionpoint_id%type;
    lastdistribpointid        distributionpoint_link.distributionpoint_link_id%type;
    vlastscandate             date;
    vlastscandatetime         timestamp;
    voldlastscandatetime      timestamp;
    vpreviousstay             stay.stay_id%type;
    vwashestotal              integer;
    vyear                     integer;
    vweek                     integer;
    vdayno                    integer;
    vcustomerowned            varchar2(1);
    routeid                   route.route_id%type;
    plannedrouteid            route.route_id%type;
    planneddate               date;
    lastdatein                date;
    plannedroute              route.route_id%type;
    lastinroute               route.route_id%type;
    qualitygradeid            qualitygrade.qualitygrade_id%type;
    deliverypointid           deliverypoint.deliverypoint_id%type;
    vfirstissuedate           date;
    vlastonstockdate          date;
    vtypeofmerch              product.typeofmerchandise%type;
    vnumberofissues           integer;
    routestopin               routestop.routestop_id%type;
    deliverymethod            integer;
    deedeliveryschemeid       deliveryscheme.deliveryscheme_id%type;
    vdaysinstockprevious      integer;
    vdaysincircprevissue      integer;
    plpcid                    productlistpercustomer.productlistpercustomer_id%type;
    vstatuschangedate         date;
    routestopid               routestop.routestop_id%type;
    vstartrentfrom            integer;
    vlastinscandate           date;
    vwashesthisissue          integer;
    unrelatedloanid           unrelatedloan.unrelatedloan_id%type;
    lockerid                  locker.locker_id%type;
    garmentdispenserid        garmentdispenser.garmentdispenser_id%type;
    vmaxwashes                integer;
    plpcfinishingcode         productlistpercustomer.finishingcode_id%type;
    lastoutrouteid            route.route_id%type;
    plpcustomcode             productlistpercustomer.customcode%type;
    plpcustomdescription      productlistpercustomer.customdescription%type;
    pchargewashesonlyforcog   varchar2(1);
    pbillingmethod            integer;
    vscanid                   scanflag.scan_id%type; -- MBA td 9345
    lv_treatmentcheckschemeid treatmentcheckscheme.treatmentcheckscheme_id%type;
    -- Order 20014102
    deliverydetermination integer;
    inroutecontrol_id     number;
    instop_id             number;
    outroutecontrol_id    number;
    stopid                number;
    deparment_id          number := null;
    lv_log                varchar2(1) := 'N';
    lv_lastoutdate        date;
    lv_lastoutstopid      number;
    lv_lastoutrouteid     number;
  begin
    -- Order 20014102
    begin
      select s.value
        into deliverydetermination
        from systemsetting s
       where s.plant_id = plantid_garment
         and s.name = 'DELIVERYDETERMINATION';
    exception
      when others then
        null;
    end;
    accept            := 'Y';
    vlastscandate     := to_timestamp(to_char(datep) || to_char(timep),
                                      'YYYYMMDDHH24MISS');
    vlastscandatetime := to_timestamp(to_char(datep) || to_char(timep),
                                      'YYYYMMDDHH24MISS');
    vyear             := getyearofweek(vlastscandate); --to_number(to_char(vlastscandate,  ' IYYY '));
    vweek             := getisoweek(vlastscandate); --to_char(vlastscandate,' IW ');
    vdayno            := getabsdaynumber(vlastscandate);
    vscanid           := 0;
    pack_sort.getsendtrackinfo(pool,
                               uniqueitemid,
                               stayid,
                               statusid,
                               productid,
                               sizeid,
                               weareremploymentid,
                               customerid,
                               vissuedate,
                               finishingmethodid,
                               distributionpointid,
                               lastdistribpointid,
                               vwashestotal,
                               vcustomerowned,
                               qualitygradeid,
                               vfirstissuedate,
                               vnumberofissues,
                               vlastonstockdate,
                               vdaysinstockprevious,
                               vstatuschangedate,
                               vstartrentfrom,
                               vdaysincircprevissue,
                               vwashesthisissue,
                               unrelatedloanid,
                               vlastinscandate,
                               deliverypointid,
                               lockerid,
                               garmentdispenserid,
                               accept);
    --stay, status
    vpreviousstay := stayid;
    select stay_id
      into stayid
      from stay
     where stay.staytype = 1
       and stay.staynr = 33; --CheckPointScan
    select status_id
      into assigned
      from status
     where status.statustype = 'UI'
       and status.code = '30'; --assigned
    select status_id
      into incirc
      from status
     where status.statustype = 'UI'
       and status.code = '20'; --in circulation
    if statusid = incirc or statusid = assigned then
      accept := 'Y';
    else
      accept := 'N';
      if debuglevel > 0 then
        pack_sort.write_logging('!> ' ||
                                ' status not in circulation or assigned for IDCode:' ||
                                idcode,
                                debuglevel,
                                'PROCESSCHECKPOINTSCAN',
                                plantid_garment,
                                1,
                                1);
      end if;
    end if;
    if accept = 'Y' then
      begin
        begin
          select u.staychangedate
            into voldlastscandatetime
            from uniqueitem u
           where u.uniqueitem_id = uniqueitemid;

          if voldlastscandatetime < vlastscandatetime then
            update uniqueitem u
               set u.lastscandate   = vlastscandatetime,
                   u.prevstay_id    = vpreviousstay,
                   u.stay_id        = stayid,
                   u.staychangedate = vlastscandatetime,
                   u.systemuser_id  = systemuserid,
                   u.timestamp      = sysdate
             where u.uniqueitem_id = uniqueitemid;
          end if;

          if debuglevel > 0 then
            pack_sort.write_logging(' update uniqueitem ' || uniqueitemid ||
                                    ' for IDCode:' || idcode,
                                    debuglevel,
                                    'PROCESSCHECKPOINTSCAN',
                                    plantid_garment,
                                    1,
                                    1);
          end if;
        exception
          when others then
            accept := 'N';
            pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                    debuglevel,
                                    'PROCESSCHECKPOINTSCAN',
                                    plantid_garment,
                                    3,
                                    1);
        end;
        --scan record
        routeid := -1;
        begin
          select u.lastoutroute_id,
                 u.plannedoutroute_id,
                 u.plannedoutdate,
                 u.lastoutdate,
                 u.lastoutroute_id,
                 u.lastoutstop_id
            into lastoutrouteid,
                 plannedrouteid,
                 planneddate,
                 lv_lastoutdate,
                 lv_lastoutrouteid,
                 lv_lastoutstopid
            from uniqueitemroute u
           where u.uniqueitem_id = uniqueitemid;
        exception
          when no_data_found then
            routeid        := null;
            plannedrouteid := null;
            lastoutrouteid := null;
        end;
        ---order563
        begin
          if scanbyroute = 'Y' then
            begin
              ------------
              pack_sort.findplpcinfo(customerid,
                                     productid,
                                     sizeid,
                                     finishingmethodid,
                                     deliverymethod,
                                     deedeliveryschemeid,
                                     plpcid,
                                     vmaxwashes,
                                     plpcfinishingcode,
                                     plpcustomcode,
                                     plpcustomdescription,
                                     pchargewashesonlyforcog,
                                     pbillingmethod,
                                     lv_treatmentcheckschemeid);
              if plpcid is null then
                if pool = 2 then
                  deliverymethod := 1;
                else
                  deliverymethod := 0;
                end if;
              end if;
              --deliverypoint
              begin
                if deliverypointid is null and pool = 2 then
                  if lockerid is not null then
                    select l.deliverypoint_id
                      into deliverypointid
                      from locker l
                     where l.locker_id = lockerid;
                  elsif garmentdispenserid is not null then
                    select g.deliverypoint_id
                      into deliverypointid
                      from garmentdispenser g
                     where g.garmentdispenser_id = garmentdispenserid;
                  end if;
                end if;
                if pool = 1 then
                  begin
                    select d.deliverypoint_id
                      into deliverypointid
                      from distributionpoint d
                     where d.distributionpoint_id = distributionpointid;
                  exception
                    when no_data_found then
                      null;
                  end;
                end if;
              end;
              ------------
              -----
              if deliverydetermination <> 1 then
                if customerid is not null then
                  select p.typeofmerchandise
                    into vtypeofmerch
                    from product p
                   where p.product_id = productid;
                  pack_sort.getlastinroute(customerid,
                                           vlastscandate,
                                           deliverypointid,
                                           vtypeofmerch,
                                           lastinroute,
                                           routestopin,
                                           lastdatein);
                end if;

                if pool = 1 then
                  plannedroute := null;
                  planneddate  := null;
                elsif pool = 2 then
                  pack_sort.fillplannedoutroute(plantid_garment,
                                                vlastscandate,
                                                vtypeofmerch,
                                                deliverymethod,
                                                deedeliveryschemeid,
                                                plpcid,
                                                customerid,
                                                deliverypointid,
                                                lastinroute,
                                                lastdatein,
                                                routestopin,
                                                routestopid,
                                                plannedroute,
                                                planneddate,
                                                scanbyroute);
                end if;
              end if;
              ------------------------------
              if routeid is null and deliverydetermination <> 1 then
                insert into uniqueitemroute
                  (uniqueitem_id,
                   lastinroute_id,
                   lastoutroute_id,
                   plannedoutroute_id,
                   lastindate,
                   lastoutdate,
                   plannedoutdate,
                   systemuser_id,
                   timestamp)
                values
                  (uniqueitemid,
                   lastinroute,
                   null,
                   plannedroute,
                   lastdatein,
                   null,
                   planneddate,
                   systemuserid,
                   sysdate);
                if debuglevel > 0 then
                  pack_sort.write_logging(' insert uniqueitemroute ' ||
                                          uniqueitemid || ' for IDCode:' ||
                                          idcode,
                                          debuglevel,
                                          'PROCESSCHECKPOINTSCAN',
                                          plantid_garment,
                                          1,
                                          1);
                end if;
              elsif plannedrouteid is null and deliverydetermination <> 1 then
                update uniqueitemroute u
                   set u.lastinroute_id     = lastinroute,
                       u.plannedoutroute_id = plannedroute,
                       u.lastindate         = to_date(lastdatein),
                       u.plannedoutdate     = to_date(planneddate),
                       u.systemuser_id      = systemuserid,
                       u.timestamp          = sysdate
                 where u.uniqueitem_id = uniqueitemid;
                if debuglevel > 0 then
                  pack_sort.write_logging(' update uniqueitemroute ' ||
                                          uniqueitemid || ' for IDCode:' ||
                                          idcode,
                                          debuglevel,
                                          'PROCESSCHECKPOINTSCAN',
                                          plantid_garment,
                                          1,
                                          1);
                end if;
                -- order 20014102
              elsif planneddate is null and deliverydetermination = 1 then
                if (lv_lastoutdate is not null and
                   lv_lastoutdate >= trunc(sysdate)) and
                   (lv_lastoutstopid is not null) and
                   (lv_lastoutrouteid is not null) then
                  select uir.lastindate,
                         uir.lastinroute_id,
                         uir.lastinstop_id,
                         uir.lastoutdate,
                         uir.lastoutroute_id,
                         uir.lastoutstop_id
                    into lastdatein,
                         lastinroute,
                         instop_id,
                         planneddate,
                         plannedroute,
                         stopid
                    from uniqueitemroute uir
                   where uir.uniqueitem_id = uniqueitemid;

                  update uniqueitem ui
                     set ui.planneddeliverydate = planneddate
                   where ui.uniqueitem_id = uniqueitemid;
                else
                  pack_deliverybasics.determinedeldateroutesoil(plantid_garment,
                                                                customerid,
                                                                deliverypointid,
                                                                deparment_id,
                                                                vtypeofmerch,
                                                                vlastscandate,
                                                                plpcid,
                                                                distributionpointid,
                                                                lv_log,
                                                                lastinroute,
                                                                routestopin,
                                                                inroutecontrol_id,
                                                                instop_id,
                                                                lastdatein,
                                                                plannedroute,
                                                                routestopid,
                                                                outroutecontrol_id,
                                                                stopid,
                                                                planneddate);
                end if;

                update uniqueitemroute u
                   set u.lastinroute_id     = lastinroute,
                       u.plannedoutroute_id = plannedroute,
                       u.lastindate         = to_date(lastdatein),
                       u.plannedoutdate     = to_date(planneddate),
                       u.systemuser_id      = systemuserid,
                       u.timestamp          = sysdate,
                       lastinstop_id        = instop_id,
                       plannedoutstop_id    = stopid
                 where u.uniqueitem_id = uniqueitemid;
                if debuglevel > 0 then
                  pack_sort.write_logging(' update uniqueitemroute ' ||
                                          uniqueitemid || ' for IDCode:' ||
                                          idcode,
                                          debuglevel,
                                          'PROCESSCHECKPOINTSCAN',
                                          plantid_garment,
                                          1,
                                          1);
                end if;
              elsif planneddate < trunc(sysdate) and
                    deliverydetermination = 1 then
                pack_deliverybasics.determinedeldaterouteclean(plantid_garment,
                                                               customerid,
                                                               deliverypointid,
                                                               deparment_id,
                                                               vtypeofmerch,
                                                               vlastscandate,
                                                               plpcid,
                                                               distributionpointid,
                                                               lv_log,
                                                               routestopid,
                                                               plannedroute,
                                                               stopid,
                                                               outroutecontrol_id,
                                                               planneddate);
                update uniqueitemroute u
                   set u.plannedoutroute_id = plannedroute,
                       u.plannedoutdate     = to_date(planneddate),
                       u.systemuser_id      = systemuserid,
                       u.timestamp          = sysdate,
                       plannedoutstop_id    = stopid
                 where u.uniqueitem_id = uniqueitemid;
                if debuglevel > 0 then
                  pack_sort.write_logging(' update uniqueitemroute ' ||
                                          uniqueitemid || ' for IDCode:' ||
                                          idcode,
                                          debuglevel,
                                          'PROCESSCHECKPOINTSCAN',
                                          plantid_garment,
                                          1,
                                          1);
                end if;
                -- end order 20014102
              end if;
            end;
          end if; --end scanbyroute='Y'
        end;
        if routeid = -1 then
          routeid := plannedrouteid;
        end if;
        begin
          insert into scan
            (scan_id,
             businessunit_id,
             scantimestamp,
             primaryid,
             customer_link_id,
             weareremployment_link_id,
             distributionpoint_link_id,
             product_link_id,
             sizedefinition_link_id,
             stay_id,
             status_id,
             scanstation,
             issuedate,
             route_id,
             reasoncode_id,
             customerowned,
             year,
             week,
             dayno,
             qualitygrade_id,
             systemuser_id,
             timestamp,
             prevstay_id,
             transactiontype_id,
             dayslate,
             uniqueitem_link_id,
             secondaryid)
          values
            (seq_scan.nextval,
             businessunitid,
             vlastscandatetime,
             idcode,
             customerid,
             weareremploymentid,
             distributionpointid,
             productid,
             sizeid,
             stayid,
             statusid,
             workstationcode,
             vissuedate,
             routeid,
             null,
             vcustomerowned,
             vyear,
             vweek,
             vdayno,
             null,
             systemuserid,
             sysdate,
             vpreviousstay,
             transactiontp,
             0,
             uniqueitemid,
             secondaryid)
          returning scan_id into vscanid;
          if debuglevel > 0 then
            pack_sort.write_logging(' insert into scan ' || uniqueitemid ||
                                    ' for IDCode:' || idcode,
                                    debuglevel,
                                    'PROCESSCHECKPOINTSCAN',
                                    plantid_garment,
                                    1,
                                    1);
          end if;
          -- MBA td 9345
          --          select seq_scan.currval into vscanflagid from dual;
        exception
          when others then
            accept := 'N';
            pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                    debuglevel,
                                    'PROCESSCHECKPOINTSCAN',
                                    plantid_garment,
                                    3,
                                    1);
        end;
        -- MBA td 9345 - insert also scanflag if flag1/2/3/4 is provided
        if (vscanid > 0 and (flagcode1 is not null or flagcode2 is not null or
           flagcode3 is not null or flagcode4 is not null)) then
          createscanflag(vscanid,
                         systemuserid,
                         debuglevel,
                         flagcode1,
                         flagcode2,
                         flagcode3,
                         flagcode4,
                         plantid_garment);
        end if;
        if (vscanid > 0) then
          add_scanflag(vscanid,
                       uniqueitemid,
                       'CheckPointScan',
                       plantid_garment,
                       systemuserid);
        end if;
        -- end td 9345
      end; --for accept='Y'
    end if; --for accept='Y'
  end processcheckpointscan;
  procedure processinscan(transactiontp   in sortingimportdefinition.transactiontype%type,
                          idcode          in uniqueitem.primaryid%type,
                          pool            in integer,
                          secondaryid     in secondaryuniqueitem.secondaryid%type,
                          plantid_garment in plant.plant_id%type,
                          plantid_param   in plant.plant_id%type,
                          businessunitid  in businessunit.businessunit_id%type,
                          uniqueitemid    in uniqueitem.uniqueitem_id%type,
                          workstationcode in workstation.code%type,
                          datep           in number,
                          timep           in varchar2, --number,
                          countwashesat   in varchar2,
                          scanbyroute     in varchar2,
                          systemuserid    in systemuser.systemuser_id%type,
                          debuglevel      in integer,
                          accept          out varchar2,
                          scaninterval    out varchar2,
                          pickuproutedate in date,
                          --502595
                          fpsretransferyn in varchar2 default 'N',
                          flagcode1       in sortaddressperflag.sortaddress%type default null,
                          flagcode2       in sortaddressperflag.sortaddress%type default null,
                          flagcode3       in sortaddressperflag.sortaddress%type default null,
                          flagcode4       in sortaddressperflag.sortaddress%type default null) is
    stayid                    stay.stay_id%type;
    statusid                  status.status_id%type;
    assigned                  status.status_id%type;
    incirc                    status.status_id%type;
    productid                 product.product_id%type;
    sizeid                    sizedefinition.sizedefinition_id%type;
    weareremploymentid        weareremployment.weareremployment_id%type;
    customerid                customer.customer_id%type;
    vissuedate                date;
    plpcid                    productlistpercustomer.productlistpercustomer_id%type;
    finishingmethodid         finishingmethod.finishingmethod_id%type;
    deliverymethod            integer;
    planneddate               date;
    plannedroute              route.route_id%type;
    distributionpointid       distributionpoint.distributionpoint_id%type;
    lastdistribpointid        distributionpoint_link.distributionpoint_link_id%type;
    vlastscandate             date;
    vlastscandatetime         timestamp(0); --21-09-2005
    vpreviousstay             stay.stay_id%type;
    vpreviousstatus           status.status_id%type;
    vmaxwashes                integer;
    productmaxwashes          integer;
    vwashestotal              integer;
    vyear                     integer;
    vweek                     integer;
    vdayno                    integer;
    cnt                       integer;
    vcustomerowned            varchar2(1);
    flagid                    flag.flag_id%type;
    qualitygradeid            qualitygrade.qualitygrade_id%type;
    vfirstissuedate           date;
    vnumberofissues           integer;
    vlastonstockdate          date;
    vdaysinstockprevious      integer;
    routestopid               routestop.routestop_id%type;
    lastdatein                date;
    vdeliverydate             date;
    vstatuschangedate         date;
    vstartrentfrom            integer;
    venddatefullrent          date;
    vdaysincircprevissue      integer;
    vwashesthisissue          integer;
    unrelatedloanid           unrelatedloan.unrelatedloan_id%type;
    lastinroute               route.route_id%type;
    routestopin               routestop.routestop_id%type;
    lastdistributionpointlink distributionpoint.distributionpoint_id%type;
    reconsiteinv              varchar2(1);
    prodlistid                productlistperdistribpoint.productlistperdistribpoint_id%type;
    vinscaninterval           integer;
    vlastinscandate           date;
    deliverypointid           deliverypoint.deliverypoint_id%type;
    lockerid                  locker.locker_id%type;
    garmentdispenserid        garmentdispenser.garmentdispenser_id%type;
    vtypeofmerch              product.typeofmerchandise%type;
    vtransactiontype          sortingimportdefinition.transactiontype%type;
    deedeliveryschemeid       deliveryscheme.deliveryscheme_id%type;
    inscandif                 number;
    plpcfinishingcode         productlistpercustomer.finishingcode_id%type;
    plpcustomcode             productlistpercustomer.customcode%type;
    plpcustomdescription      productlistpercustomer.customdescription%type;
    pchargewashesonlyforcog   varchar2(1);
    pbillingmethod            integer;
    vbringincircatinscan      integer;
    --502595
    lvcustomerstayid stay.stay_id%type;
    lvretransferyn   varchar2(1);
    -- td 9545
    wearerinventoryid           wearerinventory.wearerinventory_id%type;
    vqtytobereturneddecreasemax wearerinventory.qtytobereturneddecreasemax%type;
    vscanid                     scan.scan_id%type; -- MBA td 9345
    lv_treatmentcheckschemeid   treatmentcheckscheme.treatmentcheckscheme_id%type;
    lv_use_treatmentcheck       systemsetting.value%type;
    lv_sortingdaysrecalcdeldate systemsetting.value%type;
    currentuniquebundleid       uniqueitem.currentuniquebundle_id%type;
    flaginserted                boolean;
    -- Order 20014102
    deliverydetermination integer;
    inroutecontrol_id     number;
    instop_id             number;
    outroutecontrol_id    number;
    stopid                number;
    department_id         number := null;
    lv_log                varchar2(1) := 'N';
    cntDelivered          number := 0;

    procedure get_routeinfo_inscan is
    begin
      -- Order 20014102
      if deliverydetermination = 1 then
        pack_deliverybasics.determinedeldateroutesoil(plantid_garment,
                                                      customerid,
                                                      deliverypointid,
                                                      department_id,
                                                      vtypeofmerch,
                                                      vlastscandate,
                                                      plpcid,
                                                      distributionpointid,
                                                      lv_log,
                                                      lastinroute,
                                                      routestopin,
                                                      inroutecontrol_id,
                                                      instop_id,
                                                      lastdatein,
                                                      plannedroute,
                                                      routestopid,
                                                      outroutecontrol_id,
                                                      stopid,
                                                      planneddate);

        vdeliverydate := planneddate;
      else
        if customerid is not null then
          pack_sort.getlastinroute(customerid,
                                   nvl(pickuproutedate, vlastscandate),
                                   deliverypointid,
                                   vtypeofmerch,
                                   lastinroute,
                                   routestopin,
                                   lastdatein);
        end if;
        if pool = 1 then
          if distributionpointid is not null then
            lastdistributionpointlink := distributionpointid;
            distributionpointid       := null;
          end if;
          plannedroute := null;
          planneddate  := null;
        end if;
        if pool = 2 then
          if customerid is not null then
            pack_sort.fillplannedoutroute(plantid_garment,
                                          vlastscandate,
                                          vtypeofmerch,
                                          deliverymethod,
                                          deedeliveryschemeid,
                                          plpcid,
                                          customerid,
                                          deliverypointid,
                                          lastinroute,
                                          lastdatein,
                                          routestopin,
                                          routestopid,
                                          plannedroute,
                                          planneddate,
                                          scanbyroute);
          else
            plannedroute := null;
            planneddate  := null;
          end if;
        end if;
      end if;
    end get_routeinfo_inscan;

  begin
    vtransactiontype  := transactiontp;
    accept            := 'Y';
    vlastscandate     := to_date(to_char(datep), 'YYYYMMDD'); --21-09-2005
    vlastscandatetime := to_timestamp(to_char(datep) || to_char(timep),
                                      'YYYYMMDDHH24MISS'); --21-09-2005
    vyear             := getyearofweek(vlastscandate); --to_number(to_char(vlastscandate, 'IYYY'));
    vweek             := getisoweek(vlastscandate); --to_char(vlastscandate, 'IW');
    vdayno            := getabsdaynumber(vlastscandate);
    --502346 fill pickuproutedate in case its NULL
    pack_sort.getsendtrackinfo(pool,
                               uniqueitemid,
                               stayid,
                               statusid,
                               productid,
                               sizeid,
                               weareremploymentid,
                               customerid,
                               vissuedate,
                               finishingmethodid,
                               distributionpointid,
                               lastdistribpointid,
                               vwashestotal,
                               vcustomerowned,
                               qualitygradeid,
                               vfirstissuedate,
                               vnumberofissues,
                               vlastonstockdate,
                               vdaysinstockprevious,
                               vstatuschangedate,
                               vstartrentfrom,
                               vdaysincircprevissue,
                               vwashesthisissue,
                               unrelatedloanid,
                               vlastinscandate,
                               deliverypointid,
                               lockerid,
                               garmentdispenserid,
                               accept);
    begin
      -- INSCANALLOWHOURINTERVAL
      select s.value
        into vinscaninterval
        from systemsetting s
       where s.name = 'INSCANALLOWHOURINTERVAL'
         and s.plant_id = plantid_param;
    exception
      when no_data_found then
        vinscaninterval := 0;
    end;
    begin
      -- USETREATMENTCHECK
      select s.value
        into lv_use_treatmentcheck
        from systemsetting s
       where s.name = 'USETREATMENTCHECK'
         and s.plant_id = plantid_param;
    exception
      when no_data_found then
        lv_use_treatmentcheck := '0';
    end;
    -- Order 20014102
    begin
      select s.value
        into deliverydetermination
        from systemsetting s
       where s.plant_id = plantid_garment
         and s.name = 'DELIVERYDETERMINATION';
    exception
      when others then
        null;
    end;
    -- Order 20014732
    select nvl(max(s.value), 0)
      into lv_sortingdaysrecalcdeldate
      from systemsetting s
     where s.plant_id = plantid_garment
       and s.name = 'SORTINGDAYSRECALCDELDATE';
    --stay, status
    vpreviousstay   := stayid;
    vpreviousstatus := statusid;
    select stay_id
      into stayid
      from stay
     where stay.staytype = 1
       and stay.staynr = 30; --inscan/soil received
    select status_id
      into assigned
      from status
     where status.statustype = 'UI'
       and status.code = '30'; --assigned
    select status_id
      into incirc
      from status
     where status.statustype = 'UI'
       and status.code = '20'; --in circulation
    -- Order 20014732
    scaninterval := 'Y';
    if lv_sortingdaysrecalcdeldate = -1 then
      begin
        /*
        field 'plannedoutdate' in table 'uniqueitemroute'
        and field 'planneddeliverydate ' in table 'uniqueitem'
        is filled and the value is not in the past
        then: do not do any processing
        else: it shall work as before.
        */
        select max(u.planneddeliverydate),
               nvl(max(ur.plannedoutdate), vlastscandate - 1)
          into vdeliverydate, planneddate
          from uniqueitem u
          left outer join uniqueitemroute ur
            on ur.uniqueitem_id = u.uniqueitem_id
         where ur.uniqueitem_id = uniqueitemid;
        if vdeliverydate > vlastscandate and planneddate > vlastscandate then
          begin
            --do nothing, so skip doing anythings setting this to N
            scaninterval := 'N';
          end;
        end if;
      end;
    elsif lv_sortingdaysrecalcdeldate > 0 then
      begin
        if vpreviousstay = stayid and vlastscandate > vlastinscandate and
           vlastscandate - vlastinscandate < lv_sortingdaysrecalcdeldate then
          begin
            --only now do something special, item was scanned in before
            select nvl(max(ur.plannedoutdate), vlastscandate - 1)
              into planneddate
              from uniqueitemroute ur
             where ur.uniqueitem_id = uniqueitemid;
            --do nothing, so skip doing anythings setting this to N
            scaninterval := 'N';
            if planneddate < vlastscandate and pool = 2 then
              begin
                --only redetermine the planned out date/route
                pack_sort.findplpcinfo(customerid,
                                       productid,
                                       sizeid,
                                       finishingmethodid,
                                       deliverymethod,
                                       deedeliveryschemeid,
                                       plpcid,
                                       vmaxwashes,
                                       plpcfinishingcode,
                                       plpcustomcode,
                                       plpcustomdescription,
                                       pchargewashesonlyforcog,
                                       pbillingmethod,
                                       lv_treatmentcheckschemeid);
                if customerid is not null then
                  --deliverypoint
                  if deliverypointid is null then
                    if lockerid is not null then
                      select l.deliverypoint_id
                        into deliverypointid
                        from locker l
                       where l.locker_id = lockerid;
                    elsif garmentdispenserid is not null then
                      select g.deliverypoint_id
                        into deliverypointid
                        from garmentdispenser g
                       where g.garmentdispenser_id = garmentdispenserid;
                    end if;
                  end if;
                  --get product ino
                  select p.typeofmerchandise, p.maxwashes
                    into vtypeofmerch, productmaxwashes
                    from product p
                   where p.product_id = productid;
                  --get_routeinfo_inscan
                  get_routeinfo_inscan;
                  --update uniqueitemroute
                  update uniqueitemroute u
                     set u.plannedoutroute_id = plannedroute,
                         u.plannedoutdate     = to_date(planneddate),
                         u.systemuser_id      = systemuserid,
                         u.timestamp          = sysdate,
                         plannedoutstop_id    = stopid
                   where u.uniqueitem_id = uniqueitemid;
                  update uniqueitem u
                     set u.planneddeliverydate = to_date(planneddate),
                         u.systemuser_id       = systemuserid,
                         u.timestamp           = sysdate
                   where u.uniqueitem_id = uniqueitemid;
                end if;
              end;
            end if;
          end;
        end if;
      end;
    end if;
    --502595 get customer stayid
    select st.stay_id
      into lvcustomerstayid
      from stay st
     where st.staytype = 1
       and st.staynr = 20;
    -- HVH bug fix 1-jun-2009
    if nvl(fpsretransferyn, 'N') = 'N' then
      --this covers also value null
      --End change HVH 1-jun-2009
      lvretransferyn := 'N';
    else
      if vpreviousstay = lvcustomerstayid then
        lvretransferyn := 'N';
      else
        lvretransferyn := 'Y';
      end if;
    end if;
    --end 502595
    inscandif := vinscaninterval -
                 to_number(to_date(to_char(vlastscandatetime,
                                           'YYYYMMDDHH24'),
                                   'YYYYMMDDHH24') -
                           to_date(to_char(vlastinscandate, 'YYYYMMDDHH24'),
                                   'YYYYMMDDHH24')) * 24;
    if scaninterval = 'Y' then
      if accept = 'Y' and vlastinscandate is not null and
         vpreviousstay = stayid and vinscaninterval > 0 and
         vinscaninterval > 0 and inscandif > 0 and lvretransferyn = 'N' then
        --21-09-2005
        scaninterval := 'N';
        pack_sort.write_logging('! > idcode ' || idcode ||
                                ' was scanned less then ' ||
                                vinscaninterval || ' before',
                                debuglevel,
                                'PROCESSINSCAN',
                                plantid_param,
                                3,
                                1);
      else
        scaninterval := 'Y';
      end if;
    end if;
    if scaninterval = 'Y' then
      --for scaninterval
      --if status is not incirc or assigned then doesn't scan
      if statusid not in (assigned, incirc) then
        accept := 'N';
        pack_sort.write_logging('!>' || idcode ||
                                ' not in circulation or assigned ',
                                debuglevel,
                                'PROCESSINSCAN',
                                plantid_param,
                                3,
                                1);
      end if;
      --put flags and update wearerinventory
      if accept = 'Y' then
        begin
          --plpc
          pack_sort.findplpcinfo(customerid,
                                 productid,
                                 sizeid,
                                 finishingmethodid,
                                 deliverymethod,
                                 deedeliveryschemeid,
                                 plpcid,
                                 vmaxwashes,
                                 plpcfinishingcode,
                                 plpcustomcode,
                                 plpcustomdescription,
                                 pchargewashesonlyforcog,
                                 pbillingmethod,
                                 lv_treatmentcheckschemeid);
          if plpcid is null then
            if pool = 2 then
              deliverymethod := 1;
            else
              deliverymethod := 0;
            end if;
          end if;
          -- vmaxwashes:=0;--should be commented for 7.26
          --deliverypoint
          begin
            if deliverypointid is null and pool = 2 then
              if lockerid is not null then
                select l.deliverypoint_id
                  into deliverypointid
                  from locker l
                 where l.locker_id = lockerid;
              elsif garmentdispenserid is not null then
                select g.deliverypoint_id
                  into deliverypointid
                  from garmentdispenser g
                 where g.garmentdispenser_id = garmentdispenserid;
              end if;
            end if;
            if pool = 1 then
              begin
                select d.deliverypoint_id
                  into deliverypointid
                  from distributionpoint d
                 where d.distributionpoint_id = distributionpointid;
              exception
                when no_data_found then
                  null;
              end;
            end if;
          end;
          --502595
          select p.typeofmerchandise, p.maxwashes
            into vtypeofmerch, productmaxwashes
            from product p
           where p.product_id = productid;
          -- get last in route
          select count(u.uniqueitem_id)
            into cnt
            from uniqueitemroute u
           where u.uniqueitem_id = uniqueitemid;
          --get_routeinfo_inscan
          get_routeinfo_inscan;
          --countwashes
          if countwashesat = 'I' or
             (countwashesat = 'O' and to_number(vinscaninterval) > 0 and
             vpreviousstay = stayid) then
            begin
              vwashestotal := vwashestotal + 1;
              if pool = 2 then
                vwashesthisissue := vwashesthisissue + 1;
              end if;
            end;
          end if;
          --502595
          if lvretransferyn = 'N' then
            begin
              --assigned
              -- 20011868.50
              -- get value of system setting BRINGINCIRCATINSCAN
              begin
                select s.value
                  into vbringincircatinscan
                  from systemsetting s
                 where s.name = 'BRINGINCIRCATINSCAN'
                   and s.plant_id = plantid_param;
              exception
                when no_data_found then
                  vbringincircatinscan := 0;
              end;
              if statusid = assigned and vfirstissuedate is null and vbringincircatinscan = 1 then
                select count(1)
                into cntdelivered
                from deliveryscan ds join uniqueitem ui  on ds.uniqueitem_link_id = ui.uniqueitem_id
                where ds.packingnote_id is not null
                and ui.uniqueitem_id = uniqueitemid
                and ds.weareremployment_link_id = weareremployment_link_id
                and ui.startRentFrom = 3;
              end if;
              if statusid = assigned and ( vbringincircatinscan = 0 or cntdelivered > 0 )then
                begin
                  statusid          := incirc;
                  vstatuschangedate := vlastscandatetime; --21-09-2005
                  vstartrentfrom    := 1;
                  vtransactiontype  := 24;
                  --scan record
                  begin
                    insert into scan
                      (scan_id,
                       businessunit_id,
                       scantimestamp,
                       primaryid,
                       customer_link_id,
                       weareremployment_link_id,
                       distributionpoint_link_id,
                       product_link_id,
                       sizedefinition_link_id,
                       stay_id,
                       status_id,
                       scanstation,
                       issuedate,
                       route_id,
                       reasoncode_id,
                       customerowned,
                       year,
                       week,
                       dayno,
                       qualitygrade_id,
                       systemuser_id,
                       timestamp,
                       prevstay_id,
                       transactiontype_id,
                       dayslate,
                       uniqueitem_link_id,
                       secondaryid)
                    values
                      (seq_scan.nextval,
                       businessunitid,
                       vlastscandatetime - 0.00001,
                       --21-09-2005
                       idcode,
                       customerid,
                       weareremploymentid,
                       distributionpointid,
                       productid,
                       sizeid,
                       stayid,
                       statusid,
                       workstationcode,
                       vissuedate,
                       lastinroute,
                       null,
                       vcustomerowned,
                       vyear,
                       vweek,
                       vdayno,
                       qualitygradeid,
                       systemuserid,
                       sysdate,
                       vpreviousstay,
                       vtransactiontype,
                       0,
                       uniqueitemid,
                       secondaryid)
                    returning scan_id into vscanid;
                    if debuglevel > 0 then
                      pack_sort.write_logging(' insert scan for assigned ' ||
                                              idcode,
                                              debuglevel,
                                              'PROCESSINSCAN',
                                              plantid_param,
                                              1,
                                              1);
                    end if;
                    --todo3602
                    if vmaxwashes = 0 then
                      vmaxwashes := productmaxwashes;
                    end if;
                    if lv_use_treatmentcheck = '0' then
                      if vmaxwashes != 0 and vmaxwashes <= vwashestotal then
                        begin
                          select flag_id
                            into flagid
                            from automaticflag a
                           where a.automaticflag_id = 1;
                          flaginserted := pack_sort.create_uniqueitemflag('PACK_SORT.PROCESSINSCAN',
                                                                          debuglevel,
                                                                          systemuserid,
                                                                          uniqueitemid,
                                                                          flagid,
                                                                          vlastscandate,
                                                                          vscanid,
                                                                          null,
                                                                          null,
                                                                          plantid_param);
                        end;
                      end if;
                    else
                      add_treatmentcheck_flags(debuglevel,
                                               systemuserid,
                                               uniqueitemid,
                                               vlastscandate,
                                               vscanid,
                                               null,
                                               lv_treatmentcheckschemeid,
                                               vwashestotal,
                                               plantid_param,
                                               productid,
                                               plpcid);
                    end if;
                  exception
                    when others then
                      accept := 'N';
                      pack_sort.write_logging('!> ' || idcode || ' ' ||
                                              sqlerrm,
                                              debuglevel,
                                              'PROCESSINSCAN',
                                              plantid_param,
                                              3,
                                              1);
                  end;
                  --update uniqueitemfixedinfo for firstissuedate
                  if vfirstissuedate is null then
                    vfirstissuedate := vlastscandate;
                  end if;
                  if vlastonstockdate is not null then
                    vdaysinstockprevious := vdaysinstockprevious +
                                            (vlastscandate -
                                            vlastonstockdate);
                  end if;
                  venddatefullrent := getenddatefullrent(vlastscandate,
                                                         customerid,
                                                         productid,
                                                         sizeid,
                                                         finishingmethodid,
                                                         vdaysincircprevissue);
                  if venddatefullrent is null then
                    venddatefullrent := getenddatefullrent(vlastscandate,
                                                           customerid,
                                                           productid,
                                                           gv_specialsizeid,
                                                           finishingmethodid,
                                                           vdaysincircprevissue);
                  end if;
                  begin
                    update uniqueitemfixedinfo u
                       set u.firstissuedate      = vfirstissuedate,
                           u.lastissuedate       = vlastscandate,
                           u.numberofissues      = vnumberofissues + 1,
                           u.daysinstockprevious = vdaysinstockprevious,
                           u.enddatefullrent     = venddatefullrent,
                           u.systemuser_id       = systemuserid,
                           u.timestamp           = sysdate
                     where u.uniqueitem_id = uniqueitemid;
                    if debuglevel > 0 then
                      pack_sort.write_logging(' update uniqueitemfixedinfo ' ||
                                              uniqueitemid,
                                              debuglevel,
                                              'PROCESSINSCAN',
                                              plantid_param,
                                              1,
                                              1);
                    end if;
                  exception
                    when others then
                      accept := 'N';
                      pack_sort.write_logging('!> ' || idcode || ' ' ||
                                              sqlerrm,
                                              debuglevel,
                                              'PROCESSINSCAN',
                                              plantid_param,
                                              3,
                                              1);
                  end;
                  begin
                    update issuehistory
                       set incircdate    = vlastscandate,
                           incircyear    = vyear,
                           incircweek    = vweek,
                           incircday     = vdayno,
                           systemuser_id = systemuserid,
                           timestamp     = sysdate
                     where uniqueitem_link_id = uniqueitemid
                       and incircdate is null;
                    if debuglevel > 0 then
                      pack_sort.write_logging(' update issuehistory ' ||
                                              uniqueitemid,
                                              debuglevel,
                                              'PROCESSINSCAN',
                                              plantid_param,
                                              1,
                                              1);
                    end if;
                  exception
                    when others then
                      accept := 'N';
                      pack_sort.write_logging('!> ' || idcode || ' ' ||
                                              sqlerrm,
                                              debuglevel,
                                              'PROCESSINSCAN',
                                              plantid_param,
                                              3,
                                              1);
                  end;
                end;
              end if; --assigned
              -- unrelated loan
              if unrelatedloanid is not null then
                begin
                  update unrelatedloan u
                     set u.returnedqty   = u.returnedqty + 1,
                         u.returndate    = vlastscandate,
                         u.systemuser_id = systemuserid,
                         u.timestamp     = sysdate
                   where u.unrelatedloan_id = unrelatedloanid;
                  if debuglevel > 0 then
                    pack_sort.write_logging('ID code ' || idcode ||
                                            ' update unrelatedloan ' ||
                                            unrelatedloanid,
                                            debuglevel,
                                            'PROCESSINSCAN',
                                            plantid_param,
                                            1,
                                            1);
                  end if;
                  unrelatedloanid := null;
                exception
                  when others then
                    accept := 'N';
                    pack_sort.write_logging('!> ' || idcode || ' ' ||
                                            sqlerrm,
                                            debuglevel,
                                            'PROCESSINSCAN',
                                            plantid_param,
                                            3,
                                            1);
                end;
              end if;
              --deliveryvariations
              if plpcid is not null and deliverymethod > 0 and pool = 1 and
                /* OLD */ --       distributionpointid is not null then
                /* NEW */
                 lastdistributionpointlink is not null then
                begin
                  if cnt > 0 then
                    --exits uniqueitemroute
                    begin
                      select nvl(u.plannedoutdate, vlastscandate)
                        into vdeliverydate
                        from uniqueitemroute u
                       where u.uniqueitem_id = uniqueitemid;
                    exception
                      when others then
                        vdeliverydate := vlastscandate;
                    end;
                  else
                    vdeliverydate := vlastscandate;
                  end if;
                  insert into deliveryvariations
                    (deliveryvariations_id,
                     product_id,
                     packingnote_id,
                     causenote_id,
                     deliverydate,
                     origin,
                     amount,
                     finishingmethod_id,
                     fixedamount,
                     distributionpoint_id,
                     sizedefinition_id,
                     reference,
                     systemuser_id,
                     processed,
                     timestamp,
                     updaterentqty,
                     adjustmentreason_id,
                     soilcountsubtype)
                  values
                    (seq_deliveryvariations.nextval,
                     productid,
                     null,
                     null,
                     /* OLD */
                     --            to_date(vdeliverydate, 'YYYYMMDD'), 2, 1, finishingmethodid, 'N',
                     /* NEW */
                     trunc(vdeliverydate),
                     1,
                     1,
                     finishingmethodid,
                     'N',
                     /* OLD */
                     --            distributionpointid, sizeid, null, systemuserid, 'N', sysdate, 'N', null);
                     /* NEW */
                     lastdistributionpointlink,
                     sizeid,
                     null,
                     systemuserid,
                     'N',
                     sysdate,
                     'N',
                     null,
                     7);
                  if debuglevel > 0 then
                    pack_sort.write_logging('ID code ' || idcode ||
                                            ' insert deliveryvariations - product -size - fm ' ||
                                            productid || ' ' || sizeid || ' ' ||
                                            finishingmethodid,
                                            debuglevel,
                                            'PROCESSINSCAN',
                                            plantid_param,
                                            1,
                                            1);
                  end if;
                  --> TD 20481
                  begin
                    select ui.currentuniquebundle_id
                      into currentuniquebundleid
                      from uniqueitem ui
                     where ui.uniqueitem_id = uniqueitemid;
                  end;
                  if currentuniquebundleid is not null then
                    begin
                      update uniqueitem ui
                         set ui.currentuniquebundle_id = null
                       where ui.uniqueitem_id = uniqueitemid;
                    end;
                  end if;
                  --< TD 20481
                exception
                  when dup_val_on_index then
                    begin
                      update deliveryvariations d
                         set d.amount        = d.amount + 1,
                             d.systemuser_id = systemuserid,
                             d.timestamp     = sysdate,
                             -- Order 20014102
                             d.deliverydate = nvl(planneddate,
                                                  trunc(vdeliverydate))
                       where d.product_id = productid
                         and d.sizedefinition_id = sizeid
                         and d.finishingmethod_id = finishingmethodid
                         and d.packingnote_id is null
                         and d.processed = 'N'
                         and d.soilcountsubtype = 7
                         and d.causenote_id is null
                         and d.updaterentqty = 'N'
                            /* OLD */ --          and    d.origin = 2
                            /* NEW */
                         and d.origin = 1
                            /* OLD */ --           and    trunc(d.deliverydate) = trunc(planneddate)
                            /* NEW */
                         and trunc(d.deliverydate) = trunc(vdeliverydate)
                            /* OLD */ --          and    d.distributionpoint_id = distributionpointid;
                            /* NEW */
                         and d.distributionpoint_id =
                             lastdistributionpointlink;
                      if debuglevel > 0 then
                        pack_sort.write_logging('ID code ' || idcode ||
                                                ' update deliveryvariations - product -size - fm ' ||
                                                productid || ' ' || sizeid || ' ' ||
                                                finishingmethodid,
                                                debuglevel,
                                                'PROCESSINSCAN',
                                                plantid_param,
                                                1,
                                                1);
                      end if;
                    end;
                end;
              end if;
            end;
          end if; --if fpRetransferYN = 'N' then
          --uniqueitemroute
          if scanbyroute = 'Y' then

            -- Order 20014102 add lastoutstop_id
            begin
              ---- create RouteControl
              cnt := createroutecontrol(plannedroute,
                                        planneddate,
                                        plantid_garment,
                                        systemuserid,
                                        debuglevel,
                                        idcode);
              if cnt is not null and debuglevel > 0 then
                pack_sort.write_logging('ID code ' || idcode ||
                                        ' create/select routecontrol count ' || cnt,
                                        debuglevel,
                                        'PROCESSINSCAN',
                                        plantid_param,
                                        1,
                                        1);
              end if;
              -- order 20014102
              if (plannedroute > 0 and planneddate is not null and
                 planneddate <> to_date('31-12-2099', 'dd/mm/yyyy') and
                 (stopid is null or stopid = 0) and outroutecontrol_id = 0) then
                begin
                  select s.stop_id
                    into stopid
                    from stop s
                   where s.customer_link_id = customerid
                     and s.routecontrol_id = cnt
                     and s.routestop_id = routestopid;
                exception
                  when no_data_found then
                    null;
                end;
              end if;

              begin
                insert into uniqueitemroute
                  (uniqueitem_id,
                   lastinroute_id,
                   lastoutroute_id,
                   plannedoutroute_id,
                   lastindate,
                   lastoutdate,
                   plannedoutdate,
                   systemuser_id,
                   timestamp,
                   plannedoutstop_id)
                values
                  (uniqueitemid,
                   lastinroute,
                   null,
                   plannedroute,
                   lastdatein,
                   null,
                   planneddate,
                   systemuserid,
                   sysdate,
                   stopid);
                if debuglevel > 0 then
                  pack_sort.write_logging('ID code ' || idcode ||
                                          ' insert uniqueitemroute uniqueitemid ' ||
                                          uniqueitemid,
                                          debuglevel,
                                          'PROCESSINSCAN',
                                          plantid_param,
                                          1,
                                          1);
                end if;
              exception
                when dup_val_on_index then
                  begin
                    update uniqueitemroute u
                       set u.lastinroute_id     = lastinroute,
                           u.plannedoutroute_id = plannedroute,
                           u.lastindate         = to_date(lastdatein),
                           u.plannedoutdate     = to_date(planneddate),
                           u.systemuser_id      = systemuserid,
                           u.timestamp          = sysdate,
                           plannedoutstop_id    = stopid
                     where u.uniqueitem_id = uniqueitemid;
                    if debuglevel > 0 then
                      pack_sort.write_logging('ID code ' || idcode ||
                                              ' update uniqueitemroute uniqueitemid ' ||
                                              uniqueitemid,
                                              debuglevel,
                                              'PROCESSINSCAN',
                                              plantid_param,
                                              1,
                                              1);
                    end if;
                  end;
              end; -- end order 20014102
            end;
          end if; --scan by route
          begin
            --502595
            if lvretransferyn = 'N' then
              begin
                --21-09-2005 - line was moved in the begining
                update uniqueitem u
                   set u.statuschangedate = vstatuschangedate,
                       u.lastinscandate   = vlastscandatetime,
                       --21-09-2005
                       u.lastscandate = vlastscandatetime,
                       --21-09-2005
                       u.washestotal    = vwashestotal,
                       u.status_id      = statusid,
                       u.prevstatus_id  = vpreviousstatus,
                       u.prevstay_id    = vpreviousstay,
                       u.stay_id        = stayid,
                       u.staychangedate = vlastscandatetime,
                       --21-09-2005
                       u.distributionpoint_id         =
                       (case u.poolitem
                         when 2 then
                          null
                         else
                          distributionpointid
                       end),
                       u.lastdistributionpoint_link_id = lastdistributionpointlink,
                       u.systemuser_id                 = systemuserid,
                       u.timestamp                     = sysdate,
                       u.planneddeliverydate           = planneddate,
                       u.startrentfrom                 = vstartrentfrom,
                       u.unrelatedloan_id              = unrelatedloanid
                 where u.uniqueitem_id = uniqueitemid;
              end;
            else
              begin
                update uniqueitem u
                   set u.systemuser_id       = systemuserid,
                       u.timestamp           = sysdate,
                       u.planneddeliverydate = planneddate
                 where u.uniqueitem_id = uniqueitemid;
              end;
            end if; --if fpRetransferYN <> 'Y' then
            if debuglevel > 0 then
              pack_sort.write_logging('ID code ' || idcode ||
                                      ' update uniqueitem uniqueitemid ' ||
                                      uniqueitemid,
                                      debuglevel,
                                      'PROCESSINSCAN',
                                      plantid_param,
                                      1,
                                      1);
            end if;
          exception
            when others then
              accept := 'N';
              pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                      debuglevel,
                                      'PROCESSINSCAN',
                                      plantid_param,
                                      3,
                                      1);
          end;
          --502595
          if lvretransferyn = 'N' then
            begin
              --update uniqueitem non pool
              if pool = 2 then
                begin
                  update uniqueitemnonpool u
                     set u.washesthisissue = vwashesthisissue,
                         u.systemuser_id   = systemuserid,
                         u.timestamp       = sysdate
                   where u.uniqueitem_id = uniqueitemid;
                  if debuglevel > 0 then
                    pack_sort.write_logging('ID code ' || idcode ||
                                            ' update uniqueitemnonpool uniqueitemid ' ||
                                            uniqueitemid,
                                            debuglevel,
                                            'PROCESSINSCAN',
                                            plantid_param,
                                            1,
                                            1);
                  end if;
                exception
                  when others then
                    accept := 'N';
                    pack_sort.write_logging('!> ' || idcode || ' ' ||
                                            sqlerrm,
                                            debuglevel,
                                            'PROCESSINSCAN',
                                            plantid_param,
                                            3,
                                            1);
                end;
              end if;
              --scan record
              begin
                insert into scan
                  (scan_id,
                   businessunit_id,
                   scantimestamp,
                   primaryid,
                   customer_link_id,
                   weareremployment_link_id,
                   distributionpoint_link_id,
                   product_link_id,
                   sizedefinition_link_id,
                   stay_id,
                   status_id,
                   scanstation,
                   issuedate,
                   route_id,
                   reasoncode_id,
                   customerowned,
                   year,
                   week,
                   dayno,
                   qualitygrade_id,
                   systemuser_id,
                   timestamp,
                   prevstay_id,
                   transactiontype_id,
                   dayslate,
                   uniqueitem_link_id,
                   secondaryid)
                values
                  (seq_scan.nextval,
                   businessunitid,
                   vlastscandatetime,
                   --21-09-2005
                   idcode,
                   customerid,
                   weareremploymentid,
                   distributionpointid,
                   productid,
                   sizeid,
                   stayid,
                   statusid,
                   workstationcode,
                   vissuedate,
                   lastinroute,
                   null,
                   vcustomerowned,
                   vyear,
                   vweek,
                   vdayno,
                   qualitygradeid,
                   systemuserid,
                   sysdate,
                   vpreviousstay,
                   transactiontp,
                   0,
                   uniqueitemid,
                   secondaryid)
                returning scan_id into vscanid;
                if debuglevel > 0 then
                  pack_sort.write_logging('ID code ' || idcode ||
                                          ' insert scan uniqueitemid ' ||
                                          uniqueitemid,
                                          debuglevel,
                                          'PROCESSINSCAN',
                                          plantid_param,
                                          1,
                                          1);
                end if;
              exception
                when others then
                  accept := 'N';
                  pack_sort.write_logging('!> ' || idcode || ' ' ||
                                          sqlerrm,
                                          debuglevel,
                                          'PROCESSINSCAN',
                                          plantid_param,
                                          3,
                                          1);
              end;
              --//decrease on site inventory if applicable
              select s.value
                into reconsiteinv
                from systemsetting s
               where s.plant_id = plantid_garment
                 and s.name = 'RECORDONSITEINVENTORY';
              -- td 9545: decrease of WearerInventory.QtyToBeReturnedDecreaseMax if > 0 and automatic flag 7
              -- (Return to stock because of decrease max inventory) not on the item
              if (pool = 2 and accept = 'Y') then
                begin
                  select a.wearerinventory_id, a.qtytobereturneddecreasemax
                    into wearerinventoryid, vqtytobereturneddecreasemax
                    from wearerinventory a
                   where a.weareremployment_id = weareremploymentid
                     and a.product_id = productid
                     and a.sizedefinition_id = sizeid
                     and a.finishingmethod_id = finishingmethodid
                     for update of a.qtytobereturneddecreasemax;
                exception
                  when no_data_found then
                    wearerinventoryid := null;
                end;
                if wearerinventoryid is not null then
                  if vqtytobereturneddecreasemax > 0 then
                    begin
                      select a.flag_id
                        into flagid
                        from automaticflag a
                       where a.automaticflag_id = 7;
                      flaginserted := pack_sort.create_uniqueitemflag('PACK_SORT.PROCESSINSCAN',
                                                                      debuglevel,
                                                                      systemuserid,
                                                                      uniqueitemid,
                                                                      flagid,
                                                                      sysdate,
                                                                      vscanid,
                                                                      null,
                                                                      null,
                                                                      plantid_param);
                      if flaginserted then
                        update wearerinventory w
                           set w.qtytobereturneddecreasemax = qtytobereturneddecreasemax - 1
                         where w.wearerinventory_id = wearerinventoryid;
                        if debuglevel > 0 then
                          pack_sort.write_logging('ID code ' || idcode ||
                                                  ' update wearerinventory ' ||
                                                  wearerinventoryid,
                                                  debuglevel,
                                                  'PROCESSINSCAN',
                                                  plantid_param,
                                                  1,
                                                  1);
                        end if;
                      end if;
                    exception
                      when others then
                        pack_sort.write_logging('!> ' || idcode || ' ' ||
                                                sqlerrm,
                                                debuglevel,
                                                'PROCESSINSCAN',
                                                plantid_param,
                                                3,
                                                1);
                    end;
                  end if; -- end if qtytobereturneddecrease
                end if; -- end if wearerinventory is not null
              end if; -- end if pool = 2
              -- end todo 9545
            exception
              when no_data_found then
                null;
            end;
            begin
              if reconsiteinv = 'Y' then
                if pool = 1 and lastdistributionpointlink is not null then
                  distributionpointid := lastdistributionpointlink;
                end if;
                if distributionpointid is not null then
                  begin
                    select p.productlistperdistribpoint_id
                      into prodlistid
                      from productlistperdistribpoint p
                     where p.distributionpoint_id = distributionpointid
                       and p.product_id = productid
                       and p.sizedefinition_id = sizeid
                       and p.finishingmethod_id = finishingmethodid;
                  exception
                    when no_data_found then
                      pack_sort.write_logging('!> ' || idcode || ' ' ||
                                              sqlerrm,
                                              debuglevel,
                                              'PROCESSINSCAN',
                                              plantid_param,
                                              2,
                                              1);
                      --should be accept:='N'?????
                  end;
                  begin
                    begin
                      update onsiteinventoryadjustment o
                         set o.quantity      = o.quantity - 1,
                             o.systemuser_id = systemuserid,
                             o.timestamp     = sysdate
                       where o.productlistperdistribpoint_id = prodlistid
                         and trunc(o.inventorydate) = trunc(vlastscandate)
                         and o.origin = 5
                         and o.reference is null;
                      if sql%rowcount = 0 then
                        begin
                          insert into onsiteinventoryadjustment
                            (onsiteinventoryadjustment_id,
                             productlistperdistribpoint_id,
                             origin,
                             inventorydate,
                             quantity,
                             reference,
                             systemuser_id,
                             timestamp)
                          values
                            (seq_onsiteinventoryadjustment.nextval,
                             prodlistid,
                             5,
                             trunc(vlastscandate),
                             -1,
                             null,
                             systemuserid,
                             sysdate);
                          if debuglevel > 0 then
                            pack_sort.write_logging('ID code ' || idcode ||
                                                    ' insert onsiteinventory ' ||
                                                    prodlistid,
                                                    debuglevel,
                                                    'PROCESSINSCAN',
                                                    plantid_param,
                                                    1,
                                                    1);
                          end if;
                        end;
                      else
                        if debuglevel > 0 then
                          pack_sort.write_logging('ID code ' || idcode ||
                                                  ' update onsiteinventory ' ||
                                                  prodlistid,
                                                  debuglevel,
                                                  'PROCESSINSCAN',
                                                  plantid_param,
                                                  1,
                                                  1);
                        end if;
                      end if;
                    exception
                      when others then
                        null; --should be accept:='N'?????
                    end;
                  end;
                end if;
              end if;
            end;
          end if; --if fpRetransferYN = 'N' then
        end; --for accept='Y'
        -- MBA td 9345 - insert also scanflag if flag1/2/3/4 is provided
        if (vscanid > 0 and (flagcode1 is not null or flagcode2 is not null or
           flagcode3 is not null or flagcode4 is not null)) then
          createscanflag(vscanid,
                         systemuserid,
                         debuglevel,
                         flagcode1,
                         flagcode2,
                         flagcode3,
                         flagcode4,
                         plantid_param);
        end if;
        if (vscanid > 0) then
          add_scanflag(vscanid,
                       uniqueitemid,
                       'InScan',
                       plantid_garment,
                       systemuserid);
        end if;
        -- end td 9345
      end if; --for accept='Y'
    end if; ---If scaninterval = 'Y' then
  end processinscan;
  --create or replace
  function getinternalbusinessunit(customerid               customer.customer_id%type,
                                   productid                product.product_id%type,
                                   processingbusinessunitid businessunit.businessunit_id%type)
    return number is
    internalbusinessunitid businessunit.businessunit_id%type;
  begin
    begin
      internalbusinessunitid := null;
      if (processingbusinessunitid is not null and
         processingbusinessunitid > 0) then
        for vcursor in (select ca.internalprocessingbu_id
                          from product            p,
                               productgroup       pg,
                               customeractivities ca
                         where p.productgroup_id = pg.productgroup_id
                           and pg.activity_id = ca.activity_id
                           and ca.customer_id = customerid
                           and p.product_id = productid
                           and ca.processbusinessunit_id =
                               processingbusinessunitid) loop
          begin
            internalbusinessunitid := vcursor.internalprocessingbu_id;
            exit when internalbusinessunitid is not null and internalbusinessunitid > 0;
          end;
        end loop;
      else
        for vcursor in (select ca.internalprocessingbu_id
                          from product            p,
                               productgroup       pg,
                               customeractivities ca
                         where p.productgroup_id = pg.productgroup_id
                           and pg.activity_id = ca.activity_id
                           and ca.customer_id = customerid
                           and p.product_id = productid) loop
          begin
            internalbusinessunitid := vcursor.internalprocessingbu_id;
            exit when internalbusinessunitid is not null and internalbusinessunitid > 0;
          end;
        end loop;
      end if;
    exception
      when no_data_found then
        internalbusinessunitid := null;
    end;
    return internalbusinessunitid;
  end getinternalbusinessunit;
  procedure processoutscan(transactiontp in sortingimportdefinition.transactiontype%type,
                           idcode        in uniqueitem.primaryid%type,
                           --pool              in   integer,
                           secondaryid     in secondaryuniqueitem.secondaryid%type,
                           plantid_garment in plant.plant_id%type,
                           plantid_param   in plant.plant_id%type,
                           businessunitid  in businessunit.businessunit_id%type,
                           uniqueitemid    in uniqueitem.uniqueitem_id%type,
                           workstationid   in workstation.workstation_id%type,
                           workstationcode in workstation.code%type,
                           datep           in number,
                           timep           in varchar2, --number,
                           countwashesat   in varchar2,
                           scanbyroute     in varchar2,
                           systemuserid    in systemuser.systemuser_id%type,
                           debuglevel      in integer,
                           accept          out varchar2,
                           scaninterval    out varchar2,
                           packingnoteid   in integer,
                           statusout       out integer,
                           flagcode1       in sortaddressperflag.sortaddress%type default null,
                           flagcode2       in sortaddressperflag.sortaddress%type default null,
                           flagcode3       in sortaddressperflag.sortaddress%type default null,
                           flagcode4       in sortaddressperflag.sortaddress%type default null,
                           m_deliveryscan  in varchar2 default 'Y') is
    stayid               stay.stay_id%type;
    vpreviousstay        stay.stay_id%type;
    stayoutscan          stay.stay_id%type;
    statusid             status.status_id%type;
    vpreviousstatus      status.status_id%type;
    assigned             status.status_id%type;
    incirc               status.status_id%type;
    productid            product.product_id%type;
    sizeid               sizedefinition.sizedefinition_id%type;
    finishingmethodid    finishingmethod.finishingmethod_id%type;
    vplanneddeliverydate date;
    vplannedoutdate      date;
    vlastscandate        date;
    vlastindate          date;
    routedate            date;
    vlastscandatetime    timestamp(0);
    vlastoutscandate     date;
    weareremploymentid   weareremployment.weareremployment_id%type;
    customerid           customer.customer_id%type;
    distributionpointid  distributionpoint.distributionpoint_id%type;
    outscaninterv        integer;
    lockerid             locker.locker_id%type;
    garmentdispenserid   garmentdispenser.garmentdispenser_id%type;
    deliverypointid      deliverypoint.deliverypoint_id%type;
    vlastoutroute        route.route_id%type;
    vmaxwashes           integer;
    productmaxwashes     integer;
    vwashestotal         integer;
    vwashesthisissue     integer;
    vyear                integer;
    vweek                integer;
    vdayno               integer;
    vcustomerowned       varchar2(1);
    typeofmerch          product.typeofmerchandise%type;
    plpcid               productlistpercustomer.productlistpercustomer_id%type;
    deliverymethod       productlistpercustomer.delayedevenexchange%type;
    flagid               flag.flag_id%type;
    qualitygradeid       qualitygrade.qualitygrade_id%type;
    vlastissuedate       date;
    routestopid          routestop.routestop_id%type;
    routestopin          routestop.routestop_id%type;
    lastinroute          route.route_id%type;
    routecontrolid       routecontrol.routecontrol_id%type;
    plantdep             plantdepartment.plantdepartment_id%type;
    vdayslate            integer;
    deedeliveryschemeid  deliveryscheme.deliveryscheme_id%type;
    outscandif           number(28);
    plpcfinishingcode    productlistpercustomer.finishingcode_id%type;
    --501857
    productoptimafactor     product.optimafactor%type;
    optimafigure            number(28, 3);
    customercode            databasesettings.code%type;
    minplantdep             varchar2(1);
    countoptimahistory      integer;
    plpcustomcode           productlistpercustomer.customcode%type;
    plpcustomdescription    productlistpercustomer.customdescription%type;
    pchargewashesonlyforcog varchar2(1);
    pbillingmethod          integer;
    minpackingnotelineid    packingnoteline.packingnoteline_id%type;
    chargewashcogchg        varchar2(1);
    --502489
    pnumberwashesspecialtreatment productlistpercustomer.numberwashesspecialtreatment%type;
    lvcountwashesat               systemsetting.value%type;
    --todo8492
    lvplannedoutrouteid       uniqueitemroute.plannedoutroute_id%type;
    lvplannedoutdate          uniqueitemroute.plannedoutdate%type;
    vscanid                   scan.scan_id%type; -- MBA td 9345
    lv_treatmentcheckschemeid treatmentcheckscheme.treatmentcheckscheme_id%type;
    lv_use_treatmentcheck     systemsetting.value%type;
    --BF20012930 & BF20012965
    lv_fromstock            uniqueitem.deliveryfromstock%type;
    lv_reasoncodeid         uniqueitemfixedinfo.reasoncode_id%type;
    lv_chargewashfirstissue customer.chargewashfirstissue%type;
    lv_chargewashing        deliveryscan.chargewashing%type;
    --TD-20013349.20
    internalbusinessunitid businessunit.businessunit_id%type;
    flaginserted           boolean;
    -- Order 20014102
    deliverydetermination    integer;
    outroutecontrol_id       number;
    stopid                   number;
    department_id            number := null;
    lv_log                   varchar2(1) := 'N';
    vplannedoutstop          number;
    lv_poolitem              number;
    lv_pn_statuscode         status.code%type;
    v_QtyWithflagDecreaseMax integer;
    lvcounter                integer := 0;
    lv_dummyforpool          varchar2(1);
    wearerinventoryid        wearerinventory.wearerinventory_id%type;
    lv_outofseasoncode       season.code%type;
  begin
    lv_pn_statuscode  := '0';
    statusout         := 0;
    accept            := 'Y';
    vlastscandate     := to_date(to_char(datep), 'YYYYMMDD'); --21-09-2005
    vlastscandatetime := to_timestamp(to_char(datep) || to_char(timep),
                                      'YYYYMMDDHH24MISS');
    vyear             := getyearofweek(vlastscandate); --to_number(to_char(vlastscandate, 'IYYY'));
    vweek             := getisoweek(vlastscandate); --to_char(vlastscandate, 'IW');
    vdayno            := getabsdaynumber(vlastscandate);
    begin
      select s.value
        into outscaninterv
        from systemsetting s
       where s.name = 'OUTSCANALLOWHOURINTERVAL'
         and s.plant_id = plantid_param;
    exception
      when no_data_found then
        outscaninterv := 0;
    end;
    begin
      -- USETREATMENTCHECK
      select s.value
        into lv_use_treatmentcheck
        from systemsetting s
       where s.name = 'USETREATMENTCHECK'
         and s.plant_id = plantid_param;
    exception
      when no_data_found then
        lv_use_treatmentcheck := '0';
    end;
    --502489
    begin
      select s.value
        into lvcountwashesat
        from systemsetting s
       where s.name = 'COUNTWASHESAT'
         and s.plant_id = plantid_param;
    exception
      when no_data_found then
        lvcountwashesat := ' ';
    end;
    -- Order 20014102
    begin
      select s.value
        into deliverydetermination
        from systemsetting s
       where s.plant_id = plantid_garment
         and s.name = 'DELIVERYDETERMINATION';
    exception
      when others then
        null;
    end;
    --uniqueitem info BF20012930 & BF20012965 also read deliveryfromstock. reasoncode
    select u.planneddeliverydate,
           u.product_id,
           u.sizedefinition_id,
           u.finishingmethod_id,
           u.stay_id,
           u.status_id,
           u.washestotal,
           u.customerowned,
           u.lastoutscandate,
           f.qualitygrade_id,
           f.lastissuedate,
           n.weareremployment_id,
           n.washesthisissue,
           e.distributionpoint_id,
           w.customer_id,
           e.locker_id,
           e.garmentdispenser_id,
           e.deliverypoint_id,
           --todo8492
           ur.plannedoutroute_id,
           ur.plannedoutdate,
           u.deliveryfromstock,
           f.reasoncode_id,
           u.poolitem,
           nvl(w.dummyforpool, 'N')
      into vplanneddeliverydate,
           productid,
           sizeid,
           finishingmethodid,
           stayid,
           statusid,
           vwashestotal,
           vcustomerowned,
           vlastoutscandate,
           qualitygradeid,
           vlastissuedate,
           weareremploymentid,
           vwashesthisissue,
           distributionpointid,
           customerid,
           lockerid,
           garmentdispenserid,
           deliverypointid,
           --todo8492
           lvplannedoutrouteid,
           lvplannedoutdate,
           lv_fromstock,
           lv_reasoncodeid,
           lv_poolitem,
           lv_dummyforpool
      from uniqueitem u
      left outer join uniqueitemroute ur
        on (ur.uniqueitem_id = u.uniqueitem_id)
      join uniqueitemfixedinfo f
        on (f.uniqueitem_id = u.uniqueitem_id)
      left outer join(uniqueitemnonpool n
      join weareremployment e
        on e.weareremployment_id = n.weareremployment_id
      join wearer w
        on w.wearer_id = e.wearer_id) on (n.uniqueitem_id = u.uniqueitem_id)
     where u.uniqueitem_id = uniqueitemid;
    --BF20012930 & BF20012965 also read deliveryfromstock. reasoncode
    if lv_fromstock <> 'Y' then
      lv_reasoncodeid := null;
    end if;
    --501875
    if packingnoteid is not null then
      begin
        if debuglevel > 0 then
          pack_sort.write_logging('ID code ' || idcode ||
                                  ' Passed PackingnoteID to ProcessOutscan: ' ||
                                  packingnoteid,
                                  debuglevel,
                                  'PROCESSOUTSCAN',
                                  plantid_param,
                                  1,
                                  1);
        end if;
        select min(p.packingnoteline_id)
          into minpackingnotelineid
          from packingnoteline p
         where p.packingnote_id = packingnoteid
           and p.product_id = productid
           and p.sizedefinition_id = sizeid
           and p.finishingmethod_id = finishingmethodid; --?????????????
        if minpackingnotelineid is null then
          statusout := 4;
          pack_sort.write_logging('ID code ' || idcode ||
                                  ' Not found Packingnoteline for product with PN ID:' ||
                                  packingnoteid,
                                  debuglevel,
                                  'PROCESSOUTSCAN',
                                  plantid_param,
                                  3,
                                  1);
        end if;
      end;
    end if;
    if statusout = 0 then
      --501875
      --stay,status
      vpreviousstatus := statusid;
      vpreviousstay   := stayid;
      select s.status_id
        into assigned
        from status s
       where s.statustype = 'UI'
         and s.code = '30';
      select s.status_id
        into incirc
        from status s
       where s.statustype = 'UI'
         and s.code = '20';
      if statusid not in (assigned, incirc) then
        accept := 'N';
      end if;
      select stay.stay_id
        into stayoutscan
        from stay
       where stay.staytype = 1
         and stay.staynr = 20; --outscan/at customer
      outscandif := outscaninterv -
                    to_number(to_date(to_char(vlastscandatetime,
                                              'YYYYMMDDHH24'),
                                      'YYYYMMDDHH24') -
                              to_date(to_char(vlastoutscandate,
                                              'YYYYMMDDHH24'),
                                      'YYYYMMDDHH24')) * 24;
      if accept = 'Y' and vlastoutscandate is not null and
         stayid = stayoutscan and outscaninterv > 0 and outscandif > 0 then
        --21-09-2005
        scaninterval := 'N';
        pack_sort.write_logging('!> ID code ' || idcode ||
                                ' was scanned less then ' || outscaninterv ||
                                ' before',
                                debuglevel,
                                'PROCESSOUTSCAN',
                                plantid_param,
                                3,
                                1);
      else
        scaninterval := 'Y';
      end if;
      if scaninterval = 'Y' then
        --for scaninterval
        --deliverypoint
        begin
          if deliverypointid is null then
            if lockerid is not null then
              select l.deliverypoint_id
                into deliverypointid
                from locker l
               where l.locker_id = lockerid;
            elsif garmentdispenserid is not null then
              select g.deliverypoint_id
                into deliverypointid
                from garmentdispenser g
               where g.garmentdispenser_id = garmentdispenserid;
            end if;
          end if;
          --exception
          --when no_data_found then
          if deliverypointid is null then
            if packingnoteid is not null then
              select pk.deliverypoint_id,
                     dp.customer_id,
                     pk.distributionpoint_id,
                     st.code
                into deliverypointid,
                     customerid,
                     distributionpointid,
                     lv_pn_statuscode
                from packingnote pk
                join status st
                  on st.status_id = pk.status_id
                join deliverypoint dp
                  on dp.deliverypoint_id = pk.deliverypoint_id
               where pk.packingnote_id = packingnoteid;
            else
              begin
                select d.deliverypoint_id
                  into deliverypointid
                  from distributionpoint d
                 where d.distributionpoint_id = distributionpointid;
              exception
                when no_data_found then
                  begin
                    deliverypointid := null;
                  end;
              end;
            end if;
          end if;
        end;
        --put flags and update wearerinventory
        if accept = 'Y' then
          --plpc
          pack_sort.findplpcinfo(customerid,
                                 productid,
                                 sizeid,
                                 finishingmethodid,
                                 deliverymethod,
                                 deedeliveryschemeid,
                                 plpcid,
                                 vmaxwashes,
                                 plpcfinishingcode,
                                 plpcustomcode,
                                 plpcustomdescription,
                                 pchargewashesonlyforcog,
                                 pbillingmethod,
                                 lv_treatmentcheckschemeid);
          --max washes
          select product.maxwashes,
                 product.typeofmerchandise,
                 product.optimafactor
            into productmaxwashes, typeofmerch, productoptimafactor --501857
            from product
           where product_id = productid;
          if vmaxwashes = 0 or vmaxwashes is null then
            --should be uncommented for 7.26
            vmaxwashes := productmaxwashes;
          end if;
          --todo3602
          if countwashesat = 'O' or
             (countwashesat = 'I' and to_number(outscaninterv) > 0 and
             stayoutscan = stayid) then
            begin
              vwashestotal     := vwashestotal + 1;
              vwashesthisissue := vwashesthisissue + 1;
              --update unique item non pool
              update uniqueitemnonpool u
                 set u.washesthisissue = vwashesthisissue,
                     u.systemuser_id   = systemuserid,
                     u.timestamp       = sysdate
               where u.uniqueitem_id = uniqueitemid;
              if debuglevel > 0 then
                pack_sort.write_logging('ID code ' || idcode ||
                                        ' update uniqueitemnonpool ' ||
                                        uniqueitemid,
                                        debuglevel,
                                        'PROCESSOUTSCAN',
                                        plantid_param,
                                        1,
                                        1);
              end if;
            exception
              when others then
                accept := 'N';
                -- if debuglevel>0 then
                pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                        debuglevel,
                                        'PROCESSOUTSCAN',
                                        plantid_param,
                                        3,
                                        1);
                -- end if;
            end;
          end if; --washes total
          if lv_use_treatmentcheck = '0' then
            begin
              if vmaxwashes = vwashestotal and vmaxwashes != 0 then
                select flag_id
                  into flagid
                  from automaticflag a
                 where a.automaticflag_id = 1;
                if accept = 'Y' then
                  begin
                    flaginserted := pack_sort.create_uniqueitemflag('PACK_SORT.PROCESSOUTSCAN',
                                                                    debuglevel,
                                                                    systemuserid,
                                                                    uniqueitemid,
                                                                    flagid,
                                                                    vlastscandate,
                                                                    null,
                                                                    null,
                                                                    null,
                                                                    plantid_param);
                  end;
                end if;
              end if; --maxwashes
            end;
          end if; --lv_use_treatmentcheck
          --AUTOMATICFLAG_RETURNTOSTOCK_DECREASE_MAX_INV
          begin
            if lv_poolitem = 2 then
            select a.qtytobereturneddecreasemax,
                   (select ss.code --show season when NOT in the season!!
                     from   season ss
                     where  ss.season_id = a.season_id
                     and    not exists (select 1
                             from   seasonweek sw
                             where  sw.season_id = ss.season_id
                             and    sw.weeknumber = getisoweek(vlastscandatetime))
                     and    exists
                      (select 1 from seasonweek sw where sw.season_id = ss.season_id)) outofseasoncode,
                      wearerinventoryid
            into   v_qtywithflagdecreasemax, lv_outofseasoncode, wearerinventoryid
            from   wearerinventory a
            join   uniqueitemnonpool un
            on     un.wearerinventory_id = a.wearerinventory_id
            where  un.uniqueitem_id = uniqueitemid;
            select flag_id
            into   flagid
            from   automaticflag a
             where a.automaticflag_id = AUTOMATICFLAG_DECREASE_MAX_INV;
            else
              v_QtyWithflagDecreaseMax := 0;
              flagid := -1;
              lv_outofseasoncode := null;
              wearerinventoryid := null;
            end if;
            if (v_QtyWithflagDecreaseMax > 0) then
              flaginserted := create_uniqueitemflag('PACK_SORT.CREATE_UNIQUEITEMFLAG Insert uniqueitemflag for uniqueitemid ',
                                        debuglevel,
                                        systemuserid,
                                        uniqueitemid,
                                        flagid,
                                        vlastscandate,
                                        vscanid,
                                        to_char(vwashestotal) ||
                                        'Return to stock!');
                       if flaginserted then
                             update wearerinventory w
                             set    w.qtytobereturneddecreasemax = qtytobereturneddecreasemax - 1
                             where  w.wearerinventory_id = wearerinventoryid;
                          if debuglevel > 0 then
                             pack_sort.write_logging('ID code ' || idcode ||
                                                  ' update wearerinventory ' || wearerinventoryid,
                                                  debuglevel, 'PROCESSOUTSCAN', plantid_param, 1, 1);
                          end if;
                          if customercode <> 'AMM' then
                             lvcounter := 1;
                          else
                             lvcounter := 0;
                          end if;
                       end if;
            else
              select count(u.flag_id)
                into lvcounter
                from uniqueitemflag u
               where u.uniqueitem_id = uniqueitemid
                 and u.flag_id = flagid;
            end if;
            if (lvcounter > 0) then
              accept := 'N';
              if debuglevel > 0 then
                pack_sort.write_logging(' AUTOMATICFLAG_RETURNTOSTOCK_DECREASE_MAX_INV ' ||
                                        uniqueitemid,
                                        debuglevel,
                                        'PROCESSOUTSCAN',
                                        plantid_param,
                                        1,
                                        1);
              end if;
            end if;
          exception
            when others then
              -- ASD-16383 CLO: Missing deliveries, do accept when weird error, but report error
              -- if debuglevel>0 then
              lv_outofseasoncode := null;
              pack_sort.write_logging(' error doing check AUTOMATICFLAG_RETURNTOSTOCK_DECREASE_MAX_INV ' ||
                                      uniqueitemid || ' ' || sqlerrm,
                                      debuglevel,
                                      'PROCESSOUTSCAN',
                                      plantid_param,
                                      1,
                                      1);
              -- end if;
          end;
          --scanbyroute
          if scanbyroute = 'Y' then
            --begin
            begin
              select u.plannedoutdate, u.plannedoutstop_id
                into vplannedoutdate, vplannedoutstop
                from uniqueitemroute u
               where u.uniqueitem_id = uniqueitemid;
            exception
              when no_data_found then
                vplannedoutdate := null;
              when others then
                null;
            end;
            -- Order 20014102
            if deliverydetermination = 1 then
              pack_deliverybasics.determinedeldaterouteclean(plantid_garment,
                                                             customerid,
                                                             deliverypointid,
                                                             department_id,
                                                             typeofmerch,
                                                             vlastscandate,
                                                             plpcid,
                                                             distributionpointid,
                                                             lv_log,
                                                             routestopid,
                                                             vlastoutroute,
                                                             stopid,
                                                             outroutecontrol_id,
                                                             routedate);
            end if;
            --todo8492, added if then else
            if (lvplannedoutdate >= trunc(sysdate) and
               lvplannedoutdate is not null) and
               (lvplannedoutrouteid is not null) and
               (vplannedoutstop is not null) then
              begin
                vlastoutroute := lvplannedoutrouteid;
                routedate     := lvplannedoutdate;
                if routestopid is null then
                  routestopid := 1; --dummy route stop so route record is made
                end if;
                stopid := vplannedoutstop;
              end;
            else
              begin
                if deliverydetermination <> 1 then
                  --start added for order501026
                  pack_sort.getlastinroute(customerid,
                                           vlastscandate,
                                           deliverypointid,
                                           typeofmerch,
                                           lastinroute,
                                           routestopin,
                                           vlastindate);
                  pack_sort.fillplannedoutroute(plantid_garment,
                                                vlastscandate,
                                                typeofmerch,
                                                deliverymethod,
                                                deedeliveryschemeid,
                                                plpcid,
                                                customerid,
                                                deliverypointid,
                                                lastinroute,
                                                vlastindate,
                                                routestopin,
                                                routestopid,
                                                vlastoutroute,
                                                routedate,
                                                scanbyroute);
                end if;
              end;
            end if;
            if routestopid is not null and lv_outofseasoncode is null then
              --begin
              vlastoutscandate := vlastscandate;
              if accept = 'Y' then
                begin
                  insert into uniqueitemroute --21-09-2005 - put insert before update
                    (uniqueitem_id,
                     lastinroute_id,
                     lastoutroute_id,
                     plannedoutroute_id,
                     lastindate,
                     lastoutdate,
                     plannedoutdate,
                     plannedoutstop_id,
                     systemuser_id,
                     timestamp,
                     lastoutstop_id)
                  values
                    (uniqueitemid,
                     null,
                     vlastoutroute,
                     null,
                     null,
                     routedate,
                     null,
                     null,
                     systemuserid,
                     sysdate,
                     stopid);
                  if debuglevel > 0 then
                    pack_sort.write_logging('ID code ' || idcode ||
                                            ' insert uniqueitemroute ' ||
                                            uniqueitemid,
                                            debuglevel,
                                            'PROCESSOUTSCAN',
                                            plantid_param,
                                            1,
                                            1);
                  end if;
                exception
                  when dup_val_on_index then
                    update uniqueitemroute u --21-09-2005
                       set u.lastoutroute_id = vlastoutroute,
                           u.lastoutdate     = routedate,
                           ---here should be routedate not lastscandate?
                           u.plannedoutroute_id = null,
                           u.plannedoutdate     = null,
                           u.plannedoutstop_id  = null,
                           u.systemuser_id      = systemuserid,
                           u.timestamp          = sysdate,
                           lastoutstop_id       = stopid
                     where u.uniqueitem_id = uniqueitemid;
                    if debuglevel > 0 then
                      pack_sort.write_logging('ID code ' || idcode ||
                                              ' update uniqueitemroute ' ||
                                              uniqueitemid,
                                              debuglevel,
                                              'PROCESSOUTSCAN',
                                              plantid_param,
                                              1,
                                              1);
                    end if;
                  when others then
                    accept := 'N';
                    pack_sort.write_logging('!> ' || idcode || ' ' ||
                                            sqlerrm,
                                            debuglevel,
                                            'PROCESSOUTSCAN',
                                            plantid_param,
                                            3,
                                            1);
                end;
              end if; --accept='Y'
              --routecontrolid
              routecontrolid := createroutecontrol(vlastoutroute,
                                                   routedate,
                                                   plantid_garment,
                                                   systemuserid,
                                                   debuglevel,
                                                   idcode);
              --20014102
              if (vlastoutroute > 0 and routedate is not null and
                 routedate <> to_date('31-12-2099', 'dd/mm/yyyy') and
                 (stopid is null or stopid = 0) and
                 (outroutecontrol_id is null or outroutecontrol_id = 0)) then
                begin
                  select s.stop_id
                    into stopid
                    from stop s
                   where s.customer_link_id = customerid
                     and s.routecontrol_id = routecontrolid
                     and s.routestop_id = routestopid;

                exception
                  when no_data_found then
                    null;
                end;
                begin
                  update uniqueitemroute u
                     set u.lastoutroute_id = vlastoutroute,
                         u.lastoutdate     = routedate,
                         u.lastoutstop_id  = stopid,
                         u.timestamp       = sysdate
                   where u.uniqueitem_id = uniqueitemid;

                  if debuglevel > 0 then
                    pack_sort.write_logging('ID code ' || idcode ||
                                            ' update uniqueitemroute ' ||
                                            uniqueitemid,
                                            debuglevel,
                                            'PROCESSOUTSCAN',
                                            plantid_param,
                                            1,
                                            1);
                  end if;
                end;
              end if; -- end order 20014102
            end if; --routestopid is not null
          end if; --scan by route
          --plantdepartmentid
          begin
            select w.plantdepartment_id
              into plantdep
              from workstation w
             where w.workstation_id = workstationid
               and w.plant_id = plantid_param;
            minplantdep := 'N';
          exception
            when no_data_found then
              select min(x.plantdepartment_id)
                into plantdep
                from plantdepartment x
               where x.plant_id = plantid_param;
              minplantdep := 'Y';
          end;
          --501875
          --delivery scan
          if (accept = 'Y' and nvl(m_deliveryscan, 'Y') <> 'N' and lv_outofseasoncode is null) then
            begin
              internalbusinessunitid := getinternalbusinessunit(customerid,
                                                                productid,
                                                                businessunitid);
              select c.chargewashfirstissue
                into lv_chargewashfirstissue
                from customer c
               where c.customer_id = customerid;
              if ((lv_fromstock = 'Y' and lv_chargewashfirstissue = 'N') or
                 (m_deliveryscan = 'F' and lv_dummyforpool = 'Y')) then
                lv_chargewashing := 'N';
              else
                lv_chargewashing := 'Y';
              end if;
              insert into deliveryscan
                (businessunit_id,
                 uniqueitem_link_id,
                 scantimestamp,
                 customer_link_id,
                 weareremployment_link_id,
                 distributionpoint_link_id,
                 deliverypoint_link_id,
                 product_link_id,
                 sizedefinition_link_id,
                 finishingmethod_id,
                 routecontrol_id,
                 packingnote_id,
                 fromstock,
                 previousstay_id,
                 systemuser_id,
                 timestamp,
                 reasoncode_id,
                 plantdepartment_id,
                 chargewashing,
                 locker_id,
                 internalprocessingbu_id,
                 scanstation)
              values
                (businessunitid,
                 uniqueitemid,
                 vlastscandatetime,
                 customerid,
                 weareremploymentid,
                 distributionpointid,
                 deliverypointid,
                 productid,
                 sizeid,
                 finishingmethodid,
                 routecontrolid,
                 case when lv_pn_statuscode in ('30', '40') then null else
                 packingnoteid end,
                 --501875 --BF20012930 & BF20012965
                 lv_fromstock,
                 vpreviousstay,
                 systemuserid,
                 sysdate,
                 lv_reasoncodeid,
                 plantdep,
                 lv_chargewashing,
                 lockerid,
                 internalbusinessunitid,
                 workstationcode);
              if debuglevel > 0 then
                pack_sort.write_logging('ID code ' || idcode ||
                                        ' insert deliveryscan ' ||
                                        uniqueitemid || ' PackingnoteID:' ||
                                        packingnoteid,
                                        debuglevel,
                                        'PROCESSOUTSCAN',
                                        plantid_param,
                                        1,
                                        1);
              end if;
            exception
              when others then
                accept := 'N';
                pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                        debuglevel,
                                        'PROCESSOUTSCAN',
                                        plantid_param,
                                        3,
                                        1);
            end;
          end if;
          if accept = 'Y' then
            begin
              select s.value
                into chargewashcogchg
                from systemsetting s
               where s.plant_id = plantid_param
                 and s.name = 'CHARGEWASHCOGCHG/WEEK';
            exception
              when others then
                chargewashcogchg := 'N';
            end;
            if vcustomerowned = 'Y' and pchargewashesonlyforcog = 'Y' and
               ((pbillingmethod = 1 and chargewashcogchg = 'Y') or
               (pbillingmethod = 3) or
               (pbillingmethod = 4 and typeofmerch in (1, 2)) or
               (pbillingmethod = 5)) then
              update packingnoteline p
                 set p.deliveredamount = p.deliveredamount + 1,
                     p.deliveredcogqty = p.deliveredcogqty + 1
               where p.packingnoteline_id = minpackingnotelineid;
            else
              update packingnoteline p
                 set p.deliveredamount = p.deliveredamount + 1
               where p.packingnoteline_id = minpackingnotelineid;
            end if;
          end if;
          if accept = 'Y' then
            begin
              if lv_poolitem = 1 then
                --update uniqueitem -- BF20012930 & BF20012965 make deliverfrom stock = 'N'
                update uniqueitem u
                   set u.lastoutscandate               = vlastscandatetime,
                       u.lastscandate                  = vlastscandatetime,
                       u.washestotal                   = vwashestotal,
                       u.status_id                     = statusid,
                       u.prevstatus_id                 = vpreviousstatus,
                       u.prevstay_id                   = vpreviousstay,
                       u.stay_id                       = stayoutscan,
                       u.staychangedate                = vlastscandatetime,
                       u.systemuser_id                 = systemuserid,
                       u.timestamp                     = sysdate,
                       u.planneddeliverydate           = null,
                       u.deliveryfromstock             = 'N',
                       u.distributionpoint_id          = distributionpointid,
                       u.lastdistributionpoint_link_id = u.distributionpoint_id
                 where u.uniqueitem_id = uniqueitemid;
              else
                update uniqueitem u
                   set u.lastoutscandate     = case when lv_outofseasoncode is null
                                                    then vlastscandatetime
                                                    else u.lastoutscandate end,
                       u.lastscandate        = vlastscandatetime,
                       u.washestotal         = vwashestotal,
                       u.status_id           = statusid,
                       u.prevstatus_id       = vpreviousstatus,
                       u.prevstay_id         = case when lv_outofseasoncode is null
                                                    then vpreviousstay
                                                    else u.prevstay_id end,
                       u.stay_id             = case when lv_outofseasoncode is null
                                                    then stayoutscan
                                                    else u.stay_id end,
                       u.staychangedate      = case when lv_outofseasoncode is null
                                                    then vlastscandatetime
                                                    else u.staychangedate end,
                       u.systemuser_id       = systemuserid,
                       u.timestamp           = sysdate,
                       u.planneddeliverydate = null,
                       u.deliveryfromstock   = 'N'
                where  u.uniqueitem_id = uniqueitemid;
              end if;
              if debuglevel > 0 then
                pack_sort.write_logging('ID code ' || idcode ||
                                        ' update uniqueitem ' ||
                                        uniqueitemid,
                                        debuglevel,
                                        'PROCESSOUTSCAN',
                                        plantid_param,
                                        1,
                                        1);
              end if;
            exception
              when others then
                accept := 'N';
                pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                        debuglevel,
                                        'PROCESSOUTSCAN',
                                        plantid_param,
                                        3,
                                        1);
            end;
          end if;
          if accept = 'Y' then
            begin
              --scan record
              vdayslate := 0;
              if scanbyroute = 'Y' and vplannedoutdate is not null then
                if vplannedoutdate - vlastoutscandate < 0 then
                  vdayslate := trunc(vlastoutscandate) -
                               trunc(vplannedoutdate);
                end if;
              end if;
              if scanbyroute = 'N' and vplanneddeliverydate is not null then
                if vplanneddeliverydate - vlastscandate < 0 then
                  vdayslate := trunc(vlastscandate) -
                               trunc(vplanneddeliverydate);
                end if;
              end if;
              -- BF20012930 & BF20012965 also use reasoncode when it came from stock
              insert into scan
                (scan_id,
                 businessunit_id,
                 scantimestamp,
                 primaryid,
                 customer_link_id,
                 weareremployment_link_id,
                 distributionpoint_link_id,
                 product_link_id,
                 sizedefinition_link_id,
                 stay_id,
                 status_id,
                 scanstation,
                 issuedate,
                 route_id,
                 reasoncode_id,
                 customerowned,
                 year,
                 week,
                 dayno,
                 qualitygrade_id,
                 systemuser_id,
                 timestamp,
                 prevstay_id,
                 transactiontype_id,
                 dayslate,
                 uniqueitem_link_id,
                 secondaryid)
              values
                (seq_scan.nextval,
                 businessunitid,
                 vlastscandatetime,
                 idcode,
                 customerid,
                 weareremploymentid,
                 distributionpointid,
                 productid,
                 sizeid,
                 stayoutscan,
                 statusid,
                 workstationcode,
                 vlastissuedate,
                 vlastoutroute,
                 lv_reasoncodeid,
                 vcustomerowned,
                 vyear,
                 vweek,
                 vdayno,
                 qualitygradeid,
                 systemuserid,
                 sysdate,
                 vpreviousstay,
                 case when lv_outofseasoncode is null
                   then transactiontp
                   else 56 end, --Season Scan
                 vdayslate,
                 uniqueitemid,
                 secondaryid)
              returning scan_id into vscanid;
              if debuglevel > 0 then
                pack_sort.write_logging('ID code ' || idcode ||
                                        ' insert outscan uniqueitem ' ||
                                        uniqueitemid,
                                        debuglevel,
                                        'PROCESSOUTSCAN',
                                        plantid_param,
                                        1,
                                        1);
              end if;
              -- MBA - td 9357
              if lv_use_treatmentcheck = '0' then
                begin
                  --begin 502489
                  select p.numberwashesspecialtreatment
                    into pnumberwashesspecialtreatment
                    from productlistpercustomer p
                   where p.productlistpercustomer_id = plpcid;
                  if lvcountwashesat = 'O' and
                     pnumberwashesspecialtreatment <> 0 then
                    begin
                      if mod(vwashestotal, pnumberwashesspecialtreatment) = 0 then
                        begin
                          select flag_id
                            into flagid
                            from automaticflag a
                           where a.automaticflag_id = 6;
                          flaginserted := create_uniqueitemflag('PACK_SORT.PROCESSOUTSCAN',
                                                                debuglevel,
                                                                systemuserid,
                                                                uniqueitemid,
                                                                flagid,
                                                                vlastscandate,
                                                                vscanid,
                                                                to_char(vwashestotal) ||
                                                                ' washes reached',
                                                                null,
                                                                plantid_param);
                        end;
                      end if;
                    end;
                  end if; --end 502489
                exception
                  when no_data_found then
                    null;
                end;
              else
                add_treatmentcheck_flags(debuglevel,
                                         systemuserid,
                                         uniqueitemid,
                                         vlastscandate,
                                         vscanid,
                                         null,
                                         lv_treatmentcheckschemeid,
                                         vwashestotal,
                                         plantid_param,
                                         productid,
                                         plpcid);
              end if;
              -- end MBA td 9357
            exception
              when others then
                accept := 'N';
                pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                        debuglevel,
                                        'PROCESSOUTSCAN',
                                        plantid_param,
                                        3,
                                        1);
            end;
            -- MBA td 9345 - insert also scanflag if flag1/2/3/4 is provided
            if (vscanid > 0 and
               (flagcode1 is not null or flagcode2 is not null or
               flagcode3 is not null or flagcode4 is not null)) then
              createscanflag(vscanid,
                             systemuserid,
                             debuglevel,
                             flagcode1,
                             flagcode2,
                             flagcode3,
                             flagcode4,
                             plantid_param);
            end if;
            if (vscanid > 0) then
              add_scanflag(vscanid,
                           uniqueitemid,
                           'OutScan',
                           plantid_garment,
                           systemuserid);
            end if;
            -- end td 9345
          end if; --accept='Y'
        end if; --accept='Y'
        --order 501857
        begin
          select a.code into customercode from databasesettings a;
          if customercode = 'BNL' then
            if minplantdep = 'N' then
              if productoptimafactor = 0 then
                optimafigure := 0;
              else
                optimafigure := 1 / productoptimafactor;
              end if;
              select count(*)
                into countoptimahistory
                from optimahistory o
               where o.workstation_id = workstationid
                 and o.plantdepartment_id = plantdep
                 and o.deliverydate = trunc(sysdate);
              if countoptimahistory > 0 then
                update optimahistory o
                   set o.quantity      = o.quantity + optimafigure,
                       o.systemuser_id = systemuserid,
                       o.timestamp     = sysdate
                 where o.workstation_id = workstationid
                   and o.plantdepartment_id = plantdep
                   and o.deliverydate = trunc(sysdate);
              else
                insert into optimahistory
                  (plantdepartment_id,
                   deliverydate,
                   workstation_id,
                   quantity,
                   systemuser_id,
                   timestamp)
                values
                  (plantdep,
                   trunc(sysdate),
                   workstationid,
                   optimafigure,
                   systemuserid,
                   sysdate);
              end if;
            else
              pack_sort.write_logging('!> Optima history is not created/updated for unique item' ||
                                      idcode ||
                                      ' plantdepartmentID is not filled in workstation ' ||
                                      workstationcode,
                                      debuglevel,
                                      'PROCESSOUTSCAN',
                                      plantid_param,
                                      2,
                                      1);
            end if;
          end if;
        exception
          when others then
            pack_sort.write_logging('!> For unique item' || idcode ||
                                    ' optima history is not created/updated ',
                                    debuglevel,
                                    'PROCESSOUTSCAN',
                                    plantid_param,
                                    3,
                                    1);
        end;

      end if; ----If scaninterval = 'Y' then
    end if; --501875
  end processoutscan;
  ---create or replace
  procedure processrepairscan(transactiontp   in sortingimportdefinition.transactiontype%type,
                              idcode          in uniqueitem.primaryid%type,
                              pool            in integer,
                              secondaryid     in secondaryuniqueitem.secondaryid%type,
                              businessunitid  in businessunit.businessunit_id%type,
                              uniqueitemid    in uniqueitem.uniqueitem_id%type,
                              workstationcode in workstation.code%type,
                              datep           in number,
                              timep           in varchar2, --number,
                              repairsdone     in varchar2,
                              systemuserid    in systemuser.systemuser_id%type,
                              debuglevel      in integer,
                              accept          out varchar2,
                              flagcode1       in sortaddressperflag.sortaddress%type default null,
                              flagcode2       in sortaddressperflag.sortaddress%type default null,
                              flagcode3       in sortaddressperflag.sortaddress%type default null,
                              flagcode4       in sortaddressperflag.sortaddress%type default null) is
    statusid              status.status_id%type;
    assigned              status.status_id%type;
    incirc                status.status_id%type;
    stayid                stay.stay_id%type;
    vpreviousstay         stay.stay_id%type;
    stayrepair            stay.stay_id%type;
    productid             product.product_id%type;
    sizeid                sizedefinition.sizedefinition_id%type;
    finishingmethodid     finishingmethod.finishingmethod_id%type;
    vlastscandate         date;
    vlastscandatetime     timestamp;
    weareremploymentid    weareremployment.weareremployment_id%type;
    customerid            customer.customer_id%type;
    distributionpointid   distributionpoint.distributionpoint_id%type;
    lastdistribpointid    distributionpoint_link.distributionpoint_link_id%type;
    vrepairstotal         integer;
    vrepairsthisissue     integer;
    vyear                 integer;
    vweek                 integer;
    vdayno                integer;
    auxstring             varchar2(7);
    repairstring          varchar2(7);
    vchargerepairs        customer.chargerepairs%type;
    repairtypeid          repairtype.repairtype_id%type;
    vdefaulttime          repairtype.defaulttime%type;
    cnt                   integer;
    i                     integer;
    vcustomerowned        varchar2(1);
    qualitygradeid        qualitygrade.qualitygrade_id%type;
    vlastissuedate        date;
    lastinroute           route.route_id%type;
    vdayslate             integer;
    primaryid             uniqueitem.primaryid%type;
    vpool                 repairhistory.pool%type;
    invoicebusinessunitid businessunit.businessunit_id%type;
    deliverypointid       deliverypoint.deliverypoint_id%type;
    lockerid              locker.locker_id%type;
    garmentdispenserid    garmentdispenser.garmentdispenser_id%type;
    vtypeofmerch          product.typeofmerchandise%type;
    routestopin           routestop.routestop_id%type;
    lastdatein            date;
    --begin 502317
    lvsdbcode        databasesettings.code%type;
    lvnrepairlength  number := 1;
    vchargerepaircog customer.chargerepaircog%type;
    vscanid          scanflag.scan_id%type; -- MBA td 9345
    lvplantid        plant.plant_id%type;
    -- Order 20014102
    deliverydetermination     integer;
    inroutecontrol_id         number;
    instop_id                 number := null;
    outroutecontrol_id        number;
    stopid                    number := null;
    scanbyroute               varchar2(1);
    plantid                   plant.plant_id%type;
    routeid                   route.route_id%type;
    plannedrouteid            route.route_id%type;
    planneddate               date;
    plannedroute              route.route_id%type;
    deliverymethod            integer;
    deedeliveryschemeid       deliveryscheme.deliveryscheme_id%type;
    plpcid                    productlistpercustomer.productlistpercustomer_id%type;
    routestopid               routestop.routestop_id%type;
    vmaxwashes                integer;
    plpcfinishingcode         productlistpercustomer.finishingcode_id%type;
    plpcustomcode             productlistpercustomer.customcode%type;
    plpcustomdescription      productlistpercustomer.customdescription%type;
    pchargewashesonlyforcog   varchar2(1);
    pbillingmethod            integer;
    lv_treatmentcheckschemeid treatmentcheckscheme.treatmentcheckscheme_id%type;
    department_id             number := null;
    lv_log                    varchar2(1) := 'N';
    lv_lastoutdate            date;
    lv_lastoutstopid          number;
    lv_lastoutrouteid         number;
    -- end Order 20014102

  begin
    select b.plant_id
      into lvplantid
      from businessunit b
     where b.businessunit_id = businessunitid;

    select code into lvsdbcode from databasesettings;
    if lvsdbcode = 'VEN' then
      lvnrepairlength := 2;
    end if;
    --end 502317
    accept            := 'Y';
    vlastscandate     := to_timestamp(to_char(datep) || to_char(timep),
                                      'YYYYMMDDHH24MISS');
    vlastscandatetime := to_timestamp(to_char(datep) || to_char(timep),
                                      'YYYYMMDDHH24MISS');
    vyear             := getyearofweek(vlastscandate);
    vweek             := getisoweek(vlastscandate);
    vdayno            := getabsdaynumber(vlastscandate);
    vscanid           := 0;
    -- Order 20014102
    begin
      select s.value, p.plant_id
        into scanbyroute, plantid
        from systemsetting s, uniqueitem u, plant p, businessunit bu
       where s.name = 'SCANBYROUTE'
         and s.plant_id = bu.plant_id
         and bu.plant_id = p.plant_id
         and bu.businessunit_id = u.businessunit_id
         and u.uniqueitem_id = uniqueitemid;
    exception
      when others then
        null;
    end;
    begin
      select s.value
        into deliverydetermination
        from systemsetting s
       where s.plant_id = plantid
         and s.name = 'DELIVERYDETERMINATION';
    exception
      when others then
        null;
    end;
    -- end Order 20014102
    if pool = 2 then
      --nonpool
      begin
        vpool := 'N';
        select u.primaryid,
               u.product_id,
               u.sizedefinition_id,
               u.finishingmethod_id,
               n.weareremployment_id,
               w.customer_id,
               u.stay_id,
               u.status_id,
               e.distributionpoint_id,
               f.lastissuedate,
               u.repairstotal,
               u.customerowned,
               f.qualitygrade_id,
               n.repairsthisissue,
               e.deliverypoint_id,
               e.garmentdispenser_id,
               e.locker_id
          into primaryid,
               productid,
               sizeid,
               finishingmethodid,
               weareremploymentid,
               customerid,
               stayid,
               statusid,
               distributionpointid,
               vlastissuedate,
               vrepairstotal,
               vcustomerowned,
               qualitygradeid,
               vrepairsthisissue,
               deliverypointid,
               garmentdispenserid,
               lockerid
          from uniqueitem          u,
               uniqueitemnonpool   n,
               uniqueitemfixedinfo f,
               weareremployment    e,
               wearer              w
         where u.uniqueitem_id = uniqueitemid
           and u.uniqueitem_id = n.uniqueitem_id
           and n.weareremployment_id = e.weareremployment_id
           and e.wearer_id = w.wearer_id
           and u.uniqueitem_id = f.uniqueitem_id;
      exception
        when no_data_found then
          accept := 'N';
          pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                  debuglevel,
                                  'PROCESSREPAIRSCAN',
                                  lvplantid,
                                  3,
                                  1);
      end;
    else
      --pool
      begin
        vpool := 'Y';
        select u.primaryid,
               u.relatedcustomer_id,
               u.product_id,
               u.sizedefinition_id,
               u.finishingmethod_id,
               u.distributionpoint_id,
               u.lastdistributionpoint_link_id,
               u.stay_id,
               u.status_id,
               u.repairstotal,
               u.customerowned,
               f.qualitygrade_id,
               f.lastissuedate
          into primaryid,
               customerid,
               productid,
               sizeid,
               finishingmethodid,
               distributionpointid,
               lastdistribpointid,
               stayid,
               statusid,
               vrepairstotal,
               vcustomerowned,
               qualitygradeid,
               vlastissuedate
          from uniqueitem u, uniqueitemfixedinfo f
         where u.uniqueitem_id = uniqueitemid
           and u.uniqueitem_id = f.uniqueitem_id;
        if customerid is null then
          if distributionpointid is not null then
            select e.customer_id
              into customerid
              from distributionpoint d, department e
             where distributionpointid = d.distributionpoint_id
               and d.department_id = e.department_id;
          elsif lastdistribpointid is not null then
            select e.customer_link_id
              into customerid
              from distributionpoint_link d, department_link e
             where lastdistribpointid = d.distributionpoint_id
               and d.department_link_id = e.department_link_id;
          end if;
        end if;
      exception
        when no_data_found then
          accept := 'N';
          pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                  debuglevel,
                                  'PROCESSREPAIRSCAN',
                                  lvplantid,
                                  3,
                                  1);
      end;
    end if;
    -- Order 20014102 - scan record
    routeid := -1;
    begin
      select u.plannedoutroute_id,
             u.plannedoutdate,
             u.lastoutdate,
             u.lastoutstop_id,
             u.lastoutroute_id
        into plannedrouteid,
             planneddate,
             lv_lastoutdate,
             lv_lastoutstopid,
             lv_lastoutrouteid
        from uniqueitemroute u
       where u.uniqueitem_id = uniqueitemid;
    exception
      when no_data_found then
        routeid        := null;
        plannedrouteid := null;
    end;
    --stay,status
    vpreviousstay := stayid;
    select s.status_id
      into assigned
      from status s
     where s.statustype = 'UI'
       and s.code = '30';
    select s.status_id
      into incirc
      from status s
     where s.statustype = 'UI'
       and s.code = '20';
    if statusid not in (assigned, incirc) then
      accept := 'N';
      pack_sort.write_logging('!> ' || idcode ||
                              ' status not assigned or incirc',
                              debuglevel,
                              'PROCESSREPAIRSCAN',
                              lvplantid,
                              3,
                              1);
    end if;
    select stay.stay_id
      into stayrepair
      from stay
     where stay.staytype = 1
       and stay.staynr = 32; --repair stay
    -- HVH order 502317 also look at charge repaircog
    if accept = 'Y' then
      begin
        if customerid is not null then
          select customer.chargerepairs, customer.chargerepaircog
            into vchargerepairs, vchargerepaircog
            from customer
           where customer.customer_id = customerid;
        else
          begin
            vchargerepairs   := 0;
            vchargerepaircog := 0;
          end;
        end if;
        if vcustomerowned = 'Y' then
          begin
            if vchargerepaircog = 0 or vchargerepaircog = 1 then
              vchargerepairs := 1; --freeofcharge for field Status in RepairHistory table
            else
              vchargerepairs := 0; --charge field Status In RepairHistory;
            end if;
          end;
        else
          begin
            if vchargerepairs = 0 or vchargerepairs = 1 then
              vchargerepairs := 1; --freeofcharge for field Status in RepairHistory table
            else
              vchargerepairs := 0; --charge field Status In RepairHistory;
            end if;
          end;
        end if;
        -- HVH order 502317 also look at charge repaircog - end of change
        if customerid is not null then
          begin
            select customeractivities.invoicebusinessunit_id
              into invoicebusinessunitid
              from customeractivities, productgroup, product
             where customeractivities.customer_id = customerid
               and customeractivities.activity_id =
                   productgroup.activity_id
               and product.productgroup_id = productgroup.productgroup_id
               and product.product_id = productid;
          exception
            when others then
              null;
          end;
        end if;
        if repairsdone is null or repairsdone = ' ' then
          cnt := 0;
        else
          --502317 used lvnrepairlength
          cnt := round(length(repairsdone) / lvnrepairlength);
        end if;
        if (cnt * lvnrepairlength) > 7 then
          repairstring := substr(repairsdone, 1, 7);
          --502317 used lvnrepairlength
          cnt := trunc(7 / lvnrepairlength);
        else
          repairstring := repairsdone;
        end if;
        if cnt > 0 then
          for i in 1 .. cnt loop
            --502317 used lvnrepairlength
            auxstring := substr(repairstring,
                                (i * lvnrepairlength) -
                                (lvnrepairlength - 1),
                                lvnrepairlength);
            /*
            (i * lvnrepairlength) - (lvnrepairlength - 1)
            For length 2
                        (1 * 2) - (2-1)=1
                        (2 * 2) - (2-1)=3
                        (3 * 2) - (2-1)=5
            For length 1
                        (1 * 1) - (1-1)=1
                        (2 * 1) - (1-1)=2
                        (3 * 1) - (1-1)=3
            */
            if auxstring <> ' ' and auxstring <> '0' then
              begin
                vrepairstotal := vrepairstotal + 1;
                if pool = 2 then
                  vrepairsthisissue := vrepairsthisissue + 1;
                end if;
                --502317 new if then else
                if lvsdbcode = 'VEN' then
                  select r.repairtype_id, r.defaulttime
                    into repairtypeid, vdefaulttime
                    from repairtype r
                   where r.code = trim(auxstring);
                else
                  select r.repairtype_id, r.defaulttime
                    into repairtypeid, vdefaulttime
                    from repairtype r
                   where r.defaultfor = auxstring;
                end if;
                insert into repairhistory
                  (repairhistory_id,
                   supplier_id,
                   currency_id,
                   product_link_id,
                   distributionpoint_link_id,
                   weareremployment_link_id,
                   customer_link_id,
                   repairtype_id,
                   uniqueitem_link_id,
                   businessunit_id,
                   repairdate,
                   minutes,
                   year,
                   week,
                   day,
                   pool,
                   unitprice,
                   priceperminute,
                   systemuser_id,
                   timestamp,
                   status,
                   invoicebusinessunit_id,
                   invoiceheader_id,
                   primaryid,
                   amount)
                values
                  (seq_repairhistory.nextval,
                   null,
                   null,
                   productid,
                   distributionpointid,
                   weareremploymentid,
                   customerid,
                   repairtypeid,
                   uniqueitemid,
                   businessunitid,
                   vlastscandate,
                   vdefaulttime,
                   vyear,
                   vweek,
                   vdayno,
                   vpool,
                   null,
                   null,
                   systemuserid,
                   sysdate,
                   vchargerepairs,
                   invoicebusinessunitid,
                   null,
                   primaryid,
                   0);
              exception
                when no_data_found then
                  null;
                when others then
                  accept := 'N';
                  pack_sort.write_logging('!> ' || idcode || ' ' ||
                                          sqlerrm,
                                          debuglevel,
                                          'PROCESSREPAIRSCAN',
                                          lvplantid,
                                          3,
                                          1);
              end;
            end if;
          end loop;
        end if;
        -- RVI ToDo 21124 Also look at defined repairtypes for business unit, BEGIN
        if (lvsdbcode = 'NAF') then
          begin
            --only starting with 7.26 - according with order 874
            if cnt = 0 and accept = 'Y' then
              for vcursor in (select a.repairtype_id, a.defaulttime
                                from repairtype a, repairtypesperbu rb
                               where rb.repairtype_id = a.repairtype_id
                                 and rb.businessunit_id = businessunitid
                                 and a.autoaddonrepairscan = 'Y'
                                 and a.active = 'Y') loop
                begin
                  vrepairstotal := vrepairstotal + 1;
                  if pool = 2 then
                    vrepairsthisissue := vrepairsthisissue + 1;
                  end if; ---comment here end if
                  insert into repairhistory
                    (repairhistory_id,
                     supplier_id,
                     currency_id,
                     product_link_id,
                     distributionpoint_link_id,
                     weareremployment_link_id,
                     customer_link_id,
                     repairtype_id,
                     uniqueitem_link_id,
                     businessunit_id,
                     repairdate,
                     minutes,
                     year,
                     week,
                     day,
                     pool,
                     unitprice,
                     priceperminute,
                     systemuser_id,
                     timestamp,
                     status,
                     invoicebusinessunit_id,
                     invoiceheader_id,
                     primaryid,
                     amount)
                  values
                    (seq_repairhistory.nextval,
                     null,
                     null,
                     productid,
                     distributionpointid,
                     weareremploymentid,
                     customerid,
                     vcursor.repairtype_id,
                     uniqueitemid,
                     businessunitid,
                     vlastscandate,
                     vcursor.defaulttime,
                     vyear,
                     vweek,
                     vdayno,
                     vpool,
                     null,
                     null,
                     systemuserid,
                     sysdate,
                     vchargerepairs,
                     invoicebusinessunitid,
                     null,
                     primaryid,
                     0);
                exception
                  when others then
                    accept := 'N';
                    pack_sort.write_logging('!> ' || idcode || ' ' ||
                                            sqlerrm,
                                            debuglevel,
                                            'PROCESSREPAIRSCAN',
                                            lvplantid,
                                            3,
                                            1);
                    ---- end if;-
                end;
              end loop;
            end if;
          end;
        else
          begin
            -- RVI ToDo 21124 Also look at defined repairtypes for business unit, END
            --only starting with 7.26 - according with order 874
            if cnt = 0 and accept = 'Y' then
              for vcursor in (select a.repairtype_id, a.defaulttime
                                from repairtype a
                               where a.autoaddonrepairscan = 'Y'
                                 and a.active = 'Y') loop
                begin
                  vrepairstotal := vrepairstotal + 1;
                  if pool = 2 then
                    vrepairsthisissue := vrepairsthisissue + 1;
                  end if; ---comment here end if
                  insert into repairhistory
                    (repairhistory_id,
                     supplier_id,
                     currency_id,
                     product_link_id,
                     distributionpoint_link_id,
                     weareremployment_link_id,
                     customer_link_id,
                     repairtype_id,
                     uniqueitem_link_id,
                     businessunit_id,
                     repairdate,
                     minutes,
                     year,
                     week,
                     day,
                     pool,
                     unitprice,
                     priceperminute,
                     systemuser_id,
                     timestamp,
                     status,
                     invoicebusinessunit_id,
                     invoiceheader_id,
                     primaryid,
                     amount)
                  values
                    (seq_repairhistory.nextval,
                     null,
                     null,
                     productid,
                     distributionpointid,
                     weareremploymentid,
                     customerid,
                     vcursor.repairtype_id,
                     uniqueitemid,
                     businessunitid,
                     vlastscandate,
                     vcursor.defaulttime,
                     vyear,
                     vweek,
                     vdayno,
                     vpool,
                     null,
                     null,
                     systemuserid,
                     sysdate,
                     vchargerepairs,
                     invoicebusinessunitid,
                     null,
                     primaryid,
                     0);
                exception
                  when others then
                    accept := 'N';
                    pack_sort.write_logging('!> ' || idcode || ' ' ||
                                            sqlerrm,
                                            debuglevel,
                                            'PROCESSREPAIRSCAN',
                                            lvplantid,
                                            3,
                                            1);
                    ---- end if;-
                end;
              end loop;
            end if;
            -- RVI ToDo 21124 Also look at defined repairtypes for business unit, BEGIN
          end;
        end if;
        -- RVI ToDo 21124 Also look at defined repairtypes for business unit, END
        --update uniqueitem
        if accept = 'Y' then
          begin
            update uniqueitem u
               set u.lastscandate   = vlastscandatetime,
                   u.repairstotal   = vrepairstotal,
                   u.prevstay_id    = vpreviousstay,
                   u.stay_id        = stayrepair,
                   u.staychangedate = vlastscandatetime,
                   u.systemuser_id  = systemuserid,
                   u.timestamp      = sysdate
             where u.uniqueitem_id = uniqueitemid;
            if debuglevel > 0 then
              pack_sort.write_logging('Id code ' || idcode ||
                                      ' update uniqueitem ' ||
                                      uniqueitemid || ' Repairstotal' ||
                                      vrepairstotal,
                                      debuglevel,
                                      'PROCESSREPAIRSCAN',
                                      lvplantid,
                                      1,
                                      1);
            end if;
          exception
            when others then
              begin
                accept := 'N';
                pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                        debuglevel,
                                        'PROCESSREPAIRSCAN',
                                        lvplantid,
                                        3,
                                        1);
              end;
          end;
        end if;
        --update uniqueitemnonpool
        if pool = 2 and accept = 'Y' then
          begin
            update uniqueitemnonpool n
               set n.repairsthisissue = vrepairsthisissue
             where n.uniqueitem_id = uniqueitemid;
            if debuglevel > 0 then
              pack_sort.write_logging('Id code ' || idcode ||
                                      ' update uniqueitemnonpool ' ||
                                      uniqueitemid ||
                                      ' Repairs this issue' ||
                                      vrepairsthisissue,
                                      debuglevel,
                                      'PROCESSREPAIRSCAN',
                                      lvplantid,
                                      1,
                                      1);
            end if;
          exception
            when others then
              accept := 'N';
              pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                      debuglevel,
                                      'PROCESSREPAIRSCAN',
                                      lvplantid,
                                      3,
                                      1);
          end;
        end if;
        ----scan record
        if accept = 'Y' then
          vdayslate := 0;
          if deliverypointid is null and pool = 2 then
            if lockerid is not null then
              select l.deliverypoint_id
                into deliverypointid
                from locker l
               where l.locker_id = lockerid;
            elsif garmentdispenserid is not null then
              select g.deliverypoint_id
                into deliverypointid
                from garmentdispenser g
               where g.garmentdispenser_id = garmentdispenserid;
            end if;
          end if;
          select p.typeofmerchandise
            into vtypeofmerch
            from product p
           where p.product_id = productid;
          if customerid is not null and pool = 2 then
            pack_sort.getlastinroute(customerid,
                                     vlastscandate,
                                     deliverypointid,
                                     vtypeofmerch,
                                     lastinroute,
                                     routestopin,
                                     lastdatein);
          end if;
          begin
            insert into scan
              (scan_id,
               businessunit_id,
               scantimestamp,
               primaryid,
               customer_link_id,
               weareremployment_link_id,
               distributionpoint_link_id,
               product_link_id,
               sizedefinition_link_id,
               stay_id,
               status_id,
               scanstation,
               issuedate,
               route_id,
               reasoncode_id,
               customerowned,
               year,
               week,
               dayno,
               qualitygrade_id,
               systemuser_id,
               timestamp,
               prevstay_id,
               transactiontype_id,
               dayslate,
               uniqueitem_link_id,
               secondaryid)
            values
              (seq_scan.nextval,
               businessunitid,
               vlastscandate,
               idcode,
               customerid,
               weareremploymentid,
               distributionpointid,
               productid,
               sizeid,
               stayrepair,
               statusid,
               workstationcode,
               vlastissuedate,
               lastinroute,
               null,
               vcustomerowned,
               vyear,
               vweek,
               vdayno,
               qualitygradeid,
               systemuserid,
               sysdate,
               vpreviousstay,
               transactiontp,
               vdayslate,
               uniqueitemid,
               secondaryid)
            returning scan_id into vscanid;
            if debuglevel > 0 then
              pack_sort.write_logging('Id code ' || idcode ||
                                      'insert scan for uniqueitemid ' ||
                                      uniqueitemid,
                                      debuglevel,
                                      'PROCESSREPAIRSCAN',
                                      lvplantid,
                                      1,
                                      1);
            end if;
            -- MBA td 9345
          exception
            when others then
              begin
                accept := 'N';
                pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                        debuglevel,
                                        'PROCESSREPAIRSCAN',
                                        lvplantid,
                                        3,
                                        1);
              end;
          end;

          -- Order 20014102
          if scanbyroute = 'Y' then
            begin
              ------------
              pack_sort.findplpcinfo(customerid,
                                     productid,
                                     sizeid,
                                     finishingmethodid,
                                     deliverymethod,
                                     deedeliveryschemeid,
                                     plpcid,
                                     vmaxwashes,
                                     plpcfinishingcode,
                                     plpcustomcode,
                                     plpcustomdescription,
                                     pchargewashesonlyforcog,
                                     pbillingmethod,
                                     lv_treatmentcheckschemeid);
              if plpcid is null then
                if pool = 2 then
                  deliverymethod := 1;
                else
                  deliverymethod := 0;
                end if;
              end if;
              --deliverypoint
              begin
                if deliverypointid is null and pool = 2 then
                  if lockerid is not null then
                    select l.deliverypoint_id
                      into deliverypointid
                      from locker l
                     where l.locker_id = lockerid;
                  elsif garmentdispenserid is not null then
                    select g.deliverypoint_id
                      into deliverypointid
                      from garmentdispenser g
                     where g.garmentdispenser_id = garmentdispenserid;
                  end if;
                end if;
                if pool = 1 then
                  begin
                    select d.deliverypoint_id
                      into deliverypointid
                      from distributionpoint d
                     where d.distributionpoint_id = distributionpointid;
                  exception
                    when no_data_found then
                      null;
                  end;
                end if;
              end;
              ------------
              -----
              if deliverydetermination <> 1 then
                if customerid is not null then
                  select p.typeofmerchandise
                    into vtypeofmerch
                    from product p
                   where p.product_id = productid;
                  pack_sort.getlastinroute(customerid,
                                           vlastscandate,
                                           deliverypointid,
                                           vtypeofmerch,
                                           lastinroute,
                                           routestopin,
                                           lastdatein);
                end if;

                if pool = 1 then
                  plannedroute := null;
                  planneddate  := null;
                elsif pool = 2 then
                  pack_sort.fillplannedoutroute(plantid,
                                                vlastscandate,
                                                vtypeofmerch,
                                                deliverymethod,
                                                deedeliveryschemeid,
                                                plpcid,
                                                customerid,
                                                deliverypointid,
                                                lastinroute,
                                                lastdatein,
                                                routestopin,
                                                routestopid,
                                                plannedroute,
                                                planneddate,
                                                scanbyroute);
                end if;
              end if;
              ------------------------------
              if routeid is null and deliverydetermination <> 1 then
                insert into uniqueitemroute
                  (uniqueitem_id,
                   lastinroute_id,
                   lastoutroute_id,
                   plannedoutroute_id,
                   lastindate,
                   lastoutdate,
                   plannedoutdate,
                   systemuser_id,
                   timestamp)
                values
                  (uniqueitemid,
                   lastinroute,
                   null,
                   plannedroute,
                   lastdatein,
                   null,
                   planneddate,
                   systemuserid,
                   sysdate);
                if debuglevel > 0 then
                  pack_sort.write_logging('Id code ' || idcode ||
                                          'insert uniqueitemroute for uniqueitemid ' ||
                                          uniqueitemid,
                                          debuglevel,
                                          'PROCESSREPAIRSCAN',
                                          lvplantid,
                                          1,
                                          1);
                end if;
              elsif plannedrouteid is null and deliverydetermination <> 1 then
                update uniqueitemroute u
                   set u.lastinroute_id     = lastinroute,
                       u.plannedoutroute_id = plannedroute,
                       u.lastindate         = to_date(lastdatein),
                       u.plannedoutdate     = to_date(planneddate),
                       u.systemuser_id      = systemuserid,
                       u.timestamp          = sysdate
                 where u.uniqueitem_id = uniqueitemid;
                if debuglevel > 0 then
                  pack_sort.write_logging('Id code ' || idcode ||
                                          'update uniqueitemroute for uniqueitemid ' ||
                                          uniqueitemid,
                                          debuglevel,
                                          'PROCESSREPAIRSCAN',
                                          lvplantid,
                                          1,
                                          1);
                end if;
                -- order 20014102
              elsif planneddate is null and deliverydetermination = 1 then
                if (lv_lastoutdate is not null and
                   lv_lastoutdate >= trunc(sysdate)) and
                   (lv_lastoutrouteid is not null and
                   lv_lastoutstopid is not null) then
                  select uir.lastindate,
                         uir.lastinroute_id,
                         uir.lastinstop_id,
                         uir.lastoutdate,
                         uir.lastoutroute_id,
                         uir.lastoutstop_id
                    into lastdatein,
                         lastinroute,
                         instop_id,
                         planneddate,
                         plannedroute,
                         stopid
                    from uniqueitemroute uir
                   where uir.uniqueitem_id = uniqueitemid;
                  ---
                  update uniqueitem ui
                     set ui.planneddeliverydate = planneddate
                   where ui.uniqueitem_id = uniqueitemid;
                else
                  pack_deliverybasics.determinedeldateroutesoil(plantid,
                                                                customerid,
                                                                deliverypointid,
                                                                department_id,
                                                                vtypeofmerch,
                                                                vlastscandate,
                                                                plpcid,
                                                                distributionpointid,
                                                                lv_log,
                                                                lastinroute,
                                                                routestopin,
                                                                inroutecontrol_id,
                                                                instop_id,
                                                                lastdatein,
                                                                plannedroute,
                                                                routestopid,
                                                                outroutecontrol_id,
                                                                stopid,
                                                                planneddate);
                end if;

                update uniqueitemroute u
                   set u.lastinroute_id     = lastinroute,
                       u.plannedoutroute_id = plannedroute,
                       u.lastindate         = to_date(lastdatein),
                       u.plannedoutdate     = to_date(planneddate),
                       u.systemuser_id      = systemuserid,
                       u.timestamp          = sysdate,
                       lastinstop_id        = instop_id,
                       plannedoutstop_id    = stopid
                 where u.uniqueitem_id = uniqueitemid;
                if debuglevel > 0 then
                  pack_sort.write_logging('Id code ' || idcode ||
                                          'update uniqueitemroute for uniqueitemid ' ||
                                          uniqueitemid,
                                          debuglevel,
                                          'PROCESSREPAIRSCAN',
                                          lvplantid,
                                          1,
                                          1);

                end if;
              elsif planneddate < trunc(sysdate) and
                    deliverydetermination = 1 then
                pack_deliverybasics.determinedeldaterouteclean(plantid,
                                                               customerid,
                                                               deliverypointid,
                                                               department_id,
                                                               vtypeofmerch,
                                                               vlastscandate,
                                                               plpcid,
                                                               distributionpointid,
                                                               lv_log,
                                                               routestopid,
                                                               plannedroute,
                                                               stopid,
                                                               outroutecontrol_id,
                                                               planneddate);
                update uniqueitemroute u
                   set u.plannedoutroute_id = plannedroute,
                       u.plannedoutdate     = to_date(planneddate),
                       u.systemuser_id      = systemuserid,
                       u.timestamp          = sysdate,
                       plannedoutstop_id    = stopid
                 where u.uniqueitem_id = uniqueitemid;
                if debuglevel > 0 then
                  pack_sort.write_logging('Id code ' || idcode ||
                                          'update uniqueitemroute for uniqueitemid ' ||
                                          uniqueitemid,
                                          debuglevel,
                                          'PROCESSREPAIRSCAN',
                                          lvplantid,
                                          1,
                                          1);
                end if;
                -- end order 20014102
              end if;
            end;
          end if; --end scanbyroute='Y'
          -- end Order 20014102
          -- MBA td 9345 - insert also scanflag if flag1/2/3/4 is provided
          if (vscanid > 0 and
             (flagcode1 is not null or flagcode2 is not null or
             flagcode3 is not null or flagcode4 is not null)) then
            createscanflag(vscanid,
                           systemuserid,
                           debuglevel,
                           flagcode1,
                           flagcode2,
                           flagcode3,
                           flagcode4,
                           lvplantid);
          end if;
          if (vscanid > 0) then
            add_scanflag(vscanid,
                         uniqueitemid,
                         'RepairScan',
                         lvplantid,
                         systemuserid);
          end if;
          -- end td 9345

          addmaxrepairflag(uniqueitemid,
                           systemuserid,
                           debuglevel,
                           businessunitid,
                           pool,
                           vlastscandate,
                           vrepairstotal,
                           productid,
                           sizeid,
                           finishingmethodid,
                           distributionpointid);

        end if;
      end;
    end if;
  end processrepairscan;

  procedure addmaxrepairflag(uniqueitemid        in uniqueitem.uniqueitem_id%type,
                             systemuserid        in systemuser.systemuser_id%type,
                             debuglevel          in integer,
                             businessunitid      in businessunit.businessunit_id%type,
                             pool                in integer,
                             vlastscandate       in date,
                             repairstotal        in integer,
                             productid           in product.product_id%type,
                             sizeid              in sizedefinition.sizedefinition_id%type,
                             finishingmethodid   in finishingmethod.finishingmethod_id%type,
                             distributionpointid in distributionpoint.distributionpoint_id%type) is

    maxrepairsproduct  number;
    maxrepairsplpc     number;
    maxrepflagattached number;
    maxrepairsflagid   number;
    plantid            plant.plant_id%type;

  begin

    select b.plant_id
      into plantid
      from businessunit b
     where b.businessunit_id = businessunitid;

    select af.flag_id
      into maxrepairsflagid
      from automaticflag af
     where af.event = 'Maximum Number of Repairs';

    select count(*)
      into maxrepflagattached
      from uniqueitemflag uif
     where uif.uniqueitem_id = uniqueitemid
       and uif.flag_id = maxrepairsflagid;

    if (maxrepflagattached = 0 and maxrepairsflagid is not null) then

      if (pool = 2) then
        select nvl(max(plpc.maximumnumberofrepairs), 0),
               nvl(max(p.maximumnumberofrepairs), 0)
          into maxrepairsplpc, maxrepairsproduct
          from productlistpercustomer plpc,
               uniqueitemnonpool      uinp,
               wearerinventory        wi,
               weareremployment       we,
               wearer                 w,
               product                p
         where plpc.product_id = productid
           and (plpc.sizedefinition_id = sizeid or
               plpc.sizedefinition_id =
               (select sd.sizedefinition_id
                   from sizedefinition sd
                  where sd.code = '*'))
           and plpc.finishingmethod_id = finishingmethodid
           and uinp.uniqueitem_id = uniqueitemid
           and uinp.wearerinventory_id = wi.wearerinventory_id
           and wi.weareremployment_id = we.weareremployment_id
           and we.wearer_id = w.wearer_id
           and w.customer_id = plpc.customer_id
           and plpc.product_id = p.product_id
           and plpc.dateactive < vlastscandate
           and plpc.dateinactive > vlastscandate;

        if (maxrepairsplpc > 0 and repairstotal > maxrepairsplpc) or
           (maxrepairsproduct > 0 and repairstotal > maxrepairsproduct and
           maxrepairsplpc = 0) then

          insert into uniqueitemflag
            (uniqueitem_id, flag_id, startdate, systemuser_id, timestamp)
          values
            (uniqueitemid,
             maxrepairsflagid,
             sysdate,
             systemuserid,
             sysdate);
          commit;

        end if;

      else
        select nvl(max(plpc.maximumnumberofrepairs), 0),
               nvl(max(p.maximumnumberofrepairs), 0)
          into maxrepairsplpc, maxrepairsproduct
          from productlistpercustomer plpc,
               distributionpoint      dp,
               department             d,
               product                p
         where plpc.product_id = productid
           and (plpc.sizedefinition_id = sizeid or
               plpc.sizedefinition_id =
               (select sd.sizedefinition_id
                   from sizedefinition sd
                  where sd.code = '*'))
           and plpc.finishingmethod_id = finishingmethodid
           and dp.distributionpoint_id = distributionpointid
           and dp.department_id = d.department_id
           and d.customer_id = plpc.customer_id
           and plpc.product_id = p.product_id
           and plpc.dateactive < vlastscandate
           and plpc.dateinactive > vlastscandate;

        if (maxrepairsplpc > 0 and repairstotal > maxrepairsplpc) or
           (maxrepairsproduct > 0 and repairstotal > maxrepairsproduct and
           maxrepairsplpc = 0) then
          insert into uniqueitemflag
            (uniqueitem_id, flag_id, startdate, systemuser_id, timestamp)
          values
            (uniqueitemid,
             maxrepairsflagid,
             sysdate,
             systemuserid,
             sysdate);
          commit;
        end if;

      end if;

    end if;
  exception
    when others then
      begin
        pack_sort.write_logging('!> ' || uniqueitemid || ' ' || sqlerrm,
                                debuglevel,
                                'addmaxrepairflag',
                                plantid,
                                3,
                                1);
      end;

  end addmaxrepairflag;

  procedure processrewash(transactiontp   in sortingimportdefinition.transactiontype%type,
                          idcode          in uniqueitem.primaryid%type,
                          pool            in integer,
                          secondaryid     in secondaryuniqueitem.secondaryid%type,
                          plantid_garment in plant.plant_id%type,
                          plantid_param   in plant.plant_id%type,
                          businessunitid  in businessunit.businessunit_id%type,
                          uniqueitemid    in uniqueitem.uniqueitem_id%type,
                          workstationcode in workstation.code%type,
                          datep           in number,
                          timep           in varchar2,
                          scanbyroute     in varchar2,
                          systemuserid    in systemuser.systemuser_id%type,
                          debuglevel      in integer,
                          accept          out varchar2,
                          flagcode1       in sortaddressperflag.sortaddress%type default null,
                          flagcode2       in sortaddressperflag.sortaddress%type default null,
                          flagcode3       in sortaddressperflag.sortaddress%type default null,
                          flagcode4       in sortaddressperflag.sortaddress%type default null) is
    stayid                    stay.stay_id%type;
    statusid                  status.status_id%type;
    assigned                  status.status_id%type;
    incirc                    status.status_id%type;
    productid                 product.product_id%type;
    sizeid                    sizedefinition.sizedefinition_id%type;
    weareremploymentid        weareremployment.weareremployment_id%type;
    customerid                customer.customer_id%type;
    vissuedate                date;
    finishingmethodid         finishingmethod.finishingmethod_id%type;
    distributionpointid       distributionpoint.distributionpoint_id%type;
    lastdistribpointid        distributionpoint_link.distributionpoint_link_id%type;
    vlastscandate             date;
    vlastscandatetime         timestamp;
    vpreviousstay             stay.stay_id%type;
    vmaxwashes                integer;
    productmaxwashes          integer;
    vwashestotal              integer;
    vwashesthisissue          integer;
    vrewashthisissue          integer;
    vyear                     integer;
    vweek                     integer;
    vdayno                    integer;
    cnt                       integer;
    vcustomerowned            varchar2(1);
    flagid                    flag.flag_id%type;
    qualitygradeid            qualitygrade.qualitygrade_id%type;
    vrewashtotal              integer;
    lastinroute               route.route_id%type;
    deliverypointid           deliverypoint.deliverypoint_id%type;
    lockerid                  locker.locker_id%type;
    garmentdispenserid        garmentdispenser.garmentdispenser_id%type;
    vtypeofmerch              product.typeofmerchandise%type;
    routestopin               routestop.routestop_id%type;
    routestopid               routestop.routestop_id%type;
    lastdatein                date;
    plannedroute              route.route_id%type;
    planneddate               date;
    plpcid                    productlistpercustomer.productlistpercustomer_id%type;
    deliverymethod            integer;
    discardcompletecheck      varchar2(1);
    deedeliveryschemeid       deliveryscheme.deliveryscheme_id%type;
    plpcfinishingcode         productlistpercustomer.finishingcode_id%type;
    plpcustomcode             productlistpercustomer.customcode%type;
    plpcustomdescription      productlistpercustomer.customdescription%type;
    pchargewashesonlyforcog   varchar2(1);
    pbillingmethod            integer;
    vscanid                   scanflag.scan_id%type; -- MBA td 9345
    lv_treatmentcheckschemeid treatmentcheckscheme.treatmentcheckscheme_id%type;
    lv_use_treatmentcheck     systemsetting.value%type;
    flaginserted              boolean;
    -- Order 20014102
    deliverydetermination integer;
    inroutecontrol_id     number;
    instop_id             number;
    outroutecontrol_id    number := null;
    stopid                number := null;
    department_id         number := null;
    lv_log                varchar2(1) := 'N';
    lv_lastoutdate        date;
    lv_lastoutrouteid     number;
    lv_lastoutstopid      number;
  begin
    accept            := 'Y';
    vlastscandate     := to_timestamp(to_char(datep) || to_char(timep),
                                      'YYYYMMDDHH24MISS');
    vlastscandatetime := to_timestamp(to_char(datep) || to_char(timep),
                                      'YYYYMMDDHH24MISS');
    vyear             := getyearofweek(vlastscandate);
    vweek             := getisoweek(vlastscandate);
    vdayno            := getabsdaynumber(vlastscandate);
    vscanid           := 0;
    begin
      -- USETREATMENTCHECK
      select s.value
        into lv_use_treatmentcheck
        from systemsetting s
       where s.name = 'USETREATMENTCHECK'
         and s.plant_id = plantid_param;
    exception
      when no_data_found then
        lv_use_treatmentcheck := '0';
    end;
    -- Order 20014102
    begin
      select s.value
        into deliverydetermination
        from systemsetting s
       where s.plant_id = plantid_garment
         and s.name = 'DELIVERYDETERMINATION';
    exception
      when others then
        null;
    end;
    if pool = 2 then
      --nonpool
      begin
        select u.rewashtotal,
               u.product_id,
               u.sizedefinition_id,
               u.finishingmethod_id,
               n.weareremployment_id,
               w.customer_id,
               f.lastissuedate,
               u.stay_id,
               u.status_id,
               u.washestotal,
               u.customerowned,
               f.qualitygrade_id,
               e.locker_id,
               e.garmentdispenser_id,
               n.washesthisissue,
               n.rewashthisissue,
               e.distributionpoint_id,
               e.deliverypoint_id,
               u.planneddeliverydate
          into vrewashtotal,
               productid,
               sizeid,
               finishingmethodid,
               weareremploymentid,
               customerid,
               vissuedate,
               stayid,
               statusid,
               vwashestotal,
               vcustomerowned,
               qualitygradeid,
               lockerid,
               garmentdispenserid,
               vwashesthisissue,
               vrewashthisissue,
               distributionpointid,
               deliverypointid,
               planneddate
          from uniqueitem          u,
               uniqueitemnonpool   n,
               uniqueitemfixedinfo f,
               weareremployment    e,
               wearer              w
         where u.uniqueitem_id = uniqueitemid
           and u.uniqueitem_id = n.uniqueitem_id
           and n.weareremployment_id = e.weareremployment_id
           and e.wearer_id = w.wearer_id
           and u.uniqueitem_id = f.uniqueitem_id;
      exception
        when no_data_found then
          accept := 'N';
          pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                  debuglevel,
                                  'PROCESSREWASSCAN',
                                  plantid_param,
                                  3,
                                  1);
      end;
    else
      --pool
      begin
        select u.relatedcustomer_id,
               u.rewashtotal,
               u.product_id,
               u.sizedefinition_id,
               u.finishingmethod_id,
               f.lastissuedate,
               u.distributionpoint_id,
               u.lastdistributionpoint_link_id,
               u.stay_id,
               u.status_id,
               u.washestotal,
               u.customerowned,
               f.qualitygrade_id
          into customerid,
               vrewashtotal,
               productid,
               sizeid,
               finishingmethodid,
               vissuedate,
               distributionpointid,
               lastdistribpointid,
               stayid,
               statusid,
               vwashestotal,
               vcustomerowned,
               qualitygradeid
          from uniqueitem u, uniqueitemfixedinfo f
         where u.uniqueitem_id = uniqueitemid
           and u.uniqueitem_id = f.uniqueitem_id;
        if customerid is null then
          if distributionpointid is not null then
            select e.customer_id
              into customerid
              from distributionpoint d, department e
             where distributionpointid = d.distributionpoint_id
               and d.department_id = e.department_id;
          elsif lastdistribpointid is not null then
            select e.customer_link_id
              into customerid
              from distributionpoint_link d, department_link e
             where lastdistribpointid = d.distributionpoint_id
               and d.department_link_id = e.department_link_id;
          end if;
        end if;
      exception
        when no_data_found then
          accept := 'N';
          pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                  debuglevel,
                                  'PROCESSREWASSCAN',
                                  plantid_param,
                                  3,
                                  1);
      end;
    end if;
    --stay, status
    vpreviousstay := stayid;
    select stay_id
      into stayid
      from stay
     where stay.staytype = 1
       and stay.staynr = 31; --rewash
    select status_id
      into assigned
      from status
     where status.statustype = 'UI'
       and status.code = '30'; --assigned
    select status_id
      into incirc
      from status
     where status.statustype = 'UI'
       and status.code = '20'; --in circulation
    --if status is not incirc or assigned then doesn't scan
    if statusid not in (assigned, incirc) then
      accept := 'N';
      pack_sort.write_logging('!> ' || idcode ||
                              ' not in circulation or assigned',
                              debuglevel,
                              'PROCESSREWASSCAN',
                              plantid_param,
                              3,
                              1);
    end if;
    if accept = 'Y' then
      begin
        vwashestotal := vwashestotal + 1;
        vrewashtotal := vrewashtotal + 1;
        if pool = 2 then
          vwashesthisissue := vwashesthisissue + 1;
          vrewashthisissue := vrewashthisissue + 1;
        end if;
        --plpc
        pack_sort.findplpcinfo(customerid,
                               productid,
                               sizeid,
                               finishingmethodid,
                               deliverymethod,
                               deedeliveryschemeid,
                               plpcid,
                               vmaxwashes,
                               plpcfinishingcode,
                               plpcustomcode,
                               plpcustomdescription,
                               pchargewashesonlyforcog,
                               pbillingmethod,
                               lv_treatmentcheckschemeid);
        --deliverypoint
        begin
          if deliverypointid is null and pool = 2 then
            if lockerid is not null then
              select l.deliverypoint_id
                into deliverypointid
                from locker l
               where l.locker_id = lockerid;
            elsif garmentdispenserid is not null then
              select g.deliverypoint_id
                into deliverypointid
                from garmentdispenser g
               where g.garmentdispenser_id = garmentdispenserid;
            end if;
          end if;
          if pool = 1 then
            begin
              select d.deliverypoint_id
                into deliverypointid
                from distributionpoint d
               where d.distributionpoint_id = distributionpointid;
            exception
              when no_data_found then
                null;
            end;
          end if;
        end;
        --  planned out date, planned out route
        -- HVH From here starts my change
        if pool = 1 then
          plannedroute := null;
          planneddate  := null;
        end if;
        if pool = 2 then
          if scanbyroute = 'Y' then
            -- only if planneddate was not determined yet then determine here
            discardcompletecheck := 'N';
            for vcursor in (select f.includeincompletnesscheck
                              from uniqueitemflag u, flag f
                             where u.uniqueitem_id = uniqueitemid
                               and u.flag_id = f.flag_id) loop
              if vcursor.includeincompletnesscheck = 'N' then
                begin
                  discardcompletecheck := 'Y';
                  exit;
                end;
              end if;
            end loop;
            if discardcompletecheck = 'N' then
              --uniqueitemroute
              select count(u.uniqueitem_id),
                     max(u.lastoutdate),
                     max(u.lastoutstop_id),
                     max(u.lastoutroute_id)
                into cnt,
                     lv_lastoutdate,
                     lv_lastoutstopid,
                     lv_lastoutrouteid
                from uniqueitemroute u
               where u.uniqueitem_id = uniqueitemid;
              if cnt > 0 and customerid is not null then
                -- SO 20014102
                ---maxwashes
                select p.typeofmerchandise
                  into vtypeofmerch
                  from product p
                 where p.product_id = productid;

                select uir.lastindate,
                       uir.lastinroute_id,
                       uir.lastinstop_id,
                       uir.lastoutdate,
                       uir.lastoutroute_id,
                       uir.lastoutstop_id
                  into lastdatein,
                       lastinroute,
                       instop_id,
                       planneddate,
                       plannedroute,
                       stopid
                  from uniqueitemroute uir
                 where uir.uniqueitem_id = uniqueitemid;

                if planneddate is null then
                  if deliverydetermination = 1 then
                    if (lv_lastoutdate is not null and
                       lv_lastoutdate >= trunc(sysdate)) and
                       (lv_lastoutstopid is not null) and
                       (lv_lastoutrouteid is not null) then

                      update uniqueitem ui
                         set ui.planneddeliverydate = planneddate
                       where ui.uniqueitem_id = uniqueitemid;

                    else
                      pack_deliverybasics.determinedeldateroutesoil(plantid_garment,
                                                                    customerid,
                                                                    deliverypointid,
                                                                    department_id,
                                                                    vtypeofmerch,
                                                                    vlastscandate,
                                                                    plpcid,
                                                                    distributionpointid,
                                                                    lv_log,
                                                                    lastinroute,
                                                                    routestopin,
                                                                    inroutecontrol_id,
                                                                    instop_id,
                                                                    lastdatein,
                                                                    plannedroute,
                                                                    routestopid,
                                                                    outroutecontrol_id,
                                                                    stopid,
                                                                    planneddate);
                    end if;
                  else
                    --get last in route
                    pack_sort.getlastinroute(customerid,
                                             vlastscandate,
                                             deliverypointid,
                                             vtypeofmerch,
                                             lastinroute,
                                             routestopin,
                                             lastdatein);
                    --planned out route
                    pack_sort.fillplannedoutroute(plantid_garment,
                                                  vlastscandate,
                                                  vtypeofmerch,
                                                  deliverymethod,
                                                  deedeliveryschemeid,
                                                  plpcid,
                                                  customerid,
                                                  deliverypointid,
                                                  lastinroute,
                                                  lastdatein,
                                                  routestopin,
                                                  routestopid,
                                                  plannedroute,
                                                  planneddate,
                                                  scanbyroute);
                  end if;
                elsif planneddate < trunc(sysdate) then
                  if deliverydetermination = 1 then
                    pack_deliverybasics.determinedeldaterouteclean(plantid_garment,
                                                                   customerid,
                                                                   deliverypointid,
                                                                   department_id,
                                                                   vtypeofmerch,
                                                                   vlastscandate,
                                                                   plpcid,
                                                                   distributionpointid,
                                                                   lv_log,
                                                                   routestopid,
                                                                   plannedroute,
                                                                   stopid,
                                                                   outroutecontrol_id,
                                                                   planneddate);

                  else
                    --planned out route
                    pack_sort.fillplannedoutroute(plantid_garment,
                                                  vlastscandate,
                                                  vtypeofmerch,
                                                  deliverymethod,
                                                  deedeliveryschemeid,
                                                  plpcid,
                                                  customerid,
                                                  deliverypointid,
                                                  lastinroute,
                                                  lastdatein,
                                                  routestopin,
                                                  routestopid,
                                                  plannedroute,
                                                  planneddate,
                                                  scanbyroute);
                  end if;
                end if;
                begin
                  insert into uniqueitemroute
                    (uniqueitem_id,
                     lastinroute_id,
                     lastoutroute_id,
                     plannedoutroute_id,
                     lastindate,
                     lastoutdate,
                     plannedoutdate,
                     systemuser_id,
                     timestamp,
                     lastinstop_id,
                     plannedoutstop_id)
                  values
                    (uniqueitemid,
                     lastinroute,
                     null,
                     plannedroute,
                     lastdatein,
                     null,
                     planneddate,
                     systemuserid,
                     sysdate,
                     instop_id,
                     stopid);
                  if debuglevel > 0 then
                    pack_sort.write_logging('IDCode ' || idcode ||
                                            ' insert into uniqueitem route uniqueitemid ' ||
                                            uniqueitemid,
                                            debuglevel,
                                            'PROCESSREWASSCAN',
                                            plantid_param,
                                            3,
                                            1);
                  end if;
                exception
                  when dup_val_on_index then
                    begin
                      update uniqueitemroute u
                         set u.lastinroute_id     = lastinroute,
                             u.plannedoutroute_id = plannedroute,
                             u.lastindate         = lastdatein,
                             u.plannedoutdate     = planneddate,
                             u.systemuser_id      = systemuserid,
                             u.timestamp          = sysdate,
                             lastinstop_id        = instop_id,
                             plannedoutstop_id    = stopid
                       where u.uniqueitem_id = uniqueitemid;
                      if debuglevel > 0 then
                        pack_sort.write_logging('IDCode ' || idcode ||
                                                ' update uniqueitem route uniqueitemid ' ||
                                                uniqueitemid,
                                                debuglevel,
                                                'PROCESSREWASSCAN',
                                                plantid_param,
                                                3,
                                                1);
                      end if;
                    end;
                end;
              end if; -- if scanbyroute=Y
            end if; -- if discardcompletecheck
          end if; -- if planneddate=null
        end if; -- if pool=2
        -- HVH End change
        --uniqueitem
        begin
          update uniqueitem u
             set u.lastscandate   = vlastscandatetime,
                 u.washestotal    = vwashestotal,
                 u.rewashtotal    = vrewashtotal,
                 u.prevstay_id    = vpreviousstay,
                 u.stay_id        = stayid,
                 u.staychangedate = vlastscandatetime,
                 u.systemuser_id  = systemuserid,
                 u.timestamp      = sysdate
           where u.uniqueitem_id = uniqueitemid;
          if debuglevel > 0 then
            pack_sort.write_logging('IDCode ' || idcode ||
                                    ' update uniqueitem uniqueitemid ' ||
                                    uniqueitemid,
                                    debuglevel,
                                    'PROCESSREWASSCAN',
                                    plantid_param,
                                    3,
                                    1);
          end if;
        exception
          when others then
            accept := 'N';
            pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                    debuglevel,
                                    'PROCESSREWASSCAN',
                                    plantid_param,
                                    3,
                                    1);
        end;
        --update uniqueitem non pool
        begin
          update uniqueitemnonpool u
             set u.washesthisissue = vwashesthisissue,
                 u.rewashthisissue = vrewashthisissue,
                 u.systemuser_id   = systemuserid,
                 u.timestamp       = sysdate
           where u.uniqueitem_id = uniqueitemid;
          if debuglevel > 0 then
            pack_sort.write_logging('IDCode ' || idcode ||
                                    ' update uniqueitem nonpool uniqueitemid ' ||
                                    uniqueitemid,
                                    debuglevel,
                                    'PROCESSREWASSCAN',
                                    plantid_param,
                                    3,
                                    1);
          end if;
        exception
          when others then
            accept := 'N';
            pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                    debuglevel,
                                    'PROCESSREWASSCAN',
                                    plantid_param,
                                    3,
                                    1);
        end;
        --scan record
        begin
          insert into scan
            (scan_id,
             businessunit_id,
             scantimestamp,
             primaryid,
             customer_link_id,
             weareremployment_link_id,
             distributionpoint_link_id,
             product_link_id,
             sizedefinition_link_id,
             stay_id,
             status_id,
             scanstation,
             issuedate,
             route_id,
             reasoncode_id,
             customerowned,
             year,
             week,
             dayno,
             qualitygrade_id,
             systemuser_id,
             timestamp,
             prevstay_id,
             transactiontype_id,
             dayslate,
             uniqueitem_link_id,
             secondaryid)
          values
            (seq_scan.nextval,
             businessunitid,
             vlastscandate,
             idcode,
             customerid,
             weareremploymentid,
             distributionpointid,
             productid,
             sizeid,
             stayid,
             statusid,
             workstationcode,
             vissuedate,
             lastinroute,
             null,
             vcustomerowned,
             vyear,
             vweek,
             vdayno,
             qualitygradeid,
             systemuserid,
             sysdate,
             vpreviousstay,
             transactiontp,
             0,
             uniqueitemid,
             secondaryid)
          returning scan_id into vscanid;
          if debuglevel > 0 then
            pack_sort.write_logging('IDCode ' || idcode ||
                                    ' insert scan for uniqueitemid ' ||
                                    uniqueitemid,
                                    debuglevel,
                                    'PROCESSREWASSCAN',
                                    plantid_param,
                                    3,
                                    1);
          end if;
          if lv_use_treatmentcheck = '0' then
            begin
              ---maxwashes
              select p.maxwashes, p.typeofmerchandise
                into productmaxwashes, vtypeofmerch
                from product p
               where p.product_id = productid;
              if vmaxwashes = 0 then
                vmaxwashes := productmaxwashes;
              end if;
              select flag_id
                into flagid
                from automaticflag a
               where a.automaticflag_id = 1;
              if vmaxwashes <= vwashestotal and vmaxwashes != 0 then
                flaginserted := pack_sort.create_uniqueitemflag('PACK_SORT.PROCESSREWASH',
                                                                debuglevel,
                                                                systemuserid,
                                                                uniqueitemid,
                                                                flagid,
                                                                vlastscandate,
                                                                null,
                                                                null,
                                                                null,
                                                                plantid_param);
              end if;
            end;
          else
            add_treatmentcheck_flags(debuglevel,
                                     systemuserid,
                                     uniqueitemid,
                                     vlastscandate,
                                     vscanid,
                                     null,
                                     lv_treatmentcheckschemeid,
                                     vwashestotal,
                                     plantid_param,
                                     productid,
                                     plpcid);
          end if;
        exception
          when others then
            accept := 'N';
            pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                    debuglevel,
                                    'PROCESSREWASSCAN',
                                    plantid_param,
                                    3,
                                    1);
        end;
        -- MBA td 9345 - insert also scanflag if flag1/2/3/4 is provided
        if (vscanid > 0 and (flagcode1 is not null or flagcode2 is not null or
           flagcode3 is not null or flagcode4 is not null)) then
          createscanflag(vscanid,
                         systemuserid,
                         debuglevel,
                         flagcode1,
                         flagcode2,
                         flagcode3,
                         flagcode4,
                         plantid_param);
        end if;
        if (vscanid > 0) then
          add_scanflag(vscanid,
                       uniqueitemid,
                       'RewashScan',
                       plantid_garment,
                       systemuserid);
        end if;
        -- end td 9345
      end; --for accept='Y'
    end if; --for accept='Y'
  end processrewash;
  procedure processsortscan(transactiontp   in sortingimportdefinition.transactiontype%type,
                            idcode          in uniqueitem.primaryid%type,
                            pool            in integer,
                            secondaryid     in secondaryuniqueitem.secondaryid%type,
                            businessunitid  in businessunit.businessunit_id%type,
                            uniqueitemid    in uniqueitem.uniqueitem_id%type,
                            workstationcode in workstation.code%type,
                            datep           in number,
                            timep           in varchar2,
                            systemuserid    in systemuser.systemuser_id%type,
                            debuglevel      in integer,
                            accept          out varchar2,
                            flagcode1       in sortaddressperflag.sortaddress%type default null,
                            flagcode2       in sortaddressperflag.sortaddress%type default null,
                            flagcode3       in sortaddressperflag.sortaddress%type default null,
                            flagcode4       in sortaddressperflag.sortaddress%type default null) is
    stayid              stay.stay_id%type;
    statusid            status.status_id%type;
    assigned            status.status_id%type;
    incirc              status.status_id%type;
    productid           product.product_id%type;
    sizeid              sizedefinition.sizedefinition_id%type;
    weareremploymentid  weareremployment.weareremployment_id%type;
    customerid          customer.customer_id%type;
    vissuedate          date;
    finishingmethodid   finishingmethod.finishingmethod_id%type;
    distributionpointid distributionpoint.distributionpoint_id%type;
    lastdistribpointid  distributionpoint_link.distributionpoint_link_id%type;
    vlastscandate       date;
    vlastscandatetime   timestamp;
    vpreviousstay       stay.stay_id%type;
    vwashestotal        integer;
    vyear               integer;
    vweek               integer;
    vdayno              integer;
    vcustomerowned      varchar2(1);
    routeid             route.route_id%type;
    vscanid             scanflag.scan_id%type; -- MBA td 9345
    lvplantid           plant.plant_id%type;
  begin
    select b.plant_id
      into lvplantid
      from businessunit b
     where b.businessunit_id = businessunitid;

    accept            := 'Y';
    vlastscandate     := to_timestamp(to_char(datep) || to_char(timep),
                                      'YYYYMMDDHH24MISS');
    vlastscandatetime := to_timestamp(to_char(datep) || to_char(timep),
                                      'YYYYMMDDHH24MISS');
    vyear             := getyearofweek(vlastscandate);
    vweek             := getisoweek(vlastscandate);
    vdayno            := getabsdaynumber(vlastscandate);
    vscanid           := 0;
    if pool = 2 then
      --nonpool
      begin
        select u.product_id,
               u.sizedefinition_id,
               u.finishingmethod_id,
               n.weareremployment_id,
               w.customer_id,
               f.lastissuedate,
               u.stay_id,
               u.status_id,
               u.washestotal,
               u.customerowned,
               e.distributionpoint_id
          into productid,
               sizeid,
               finishingmethodid,
               weareremploymentid,
               customerid,
               vissuedate,
               stayid,
               statusid,
               vwashestotal,
               vcustomerowned,
               distributionpointid
          from uniqueitem          u,
               uniqueitemnonpool   n,
               uniqueitemfixedinfo f,
               weareremployment    e,
               wearer              w
         where u.uniqueitem_id = uniqueitemid
           and u.uniqueitem_id = n.uniqueitem_id
           and n.weareremployment_id = e.weareremployment_id
           and e.wearer_id = w.wearer_id
           and u.uniqueitem_id = f.uniqueitem_id;
      exception
        when no_data_found then
          accept := 'N';
          pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                  debuglevel,
                                  'PROCESSSORTSCAN',
                                  null,
                                  3,
                                  1);
      end;
    else
      --pool
      begin
        select u.relatedcustomer_id,
               u.product_id,
               u.sizedefinition_id,
               u.finishingmethod_id,
               f.lastissuedate,
               u.distributionpoint_id,
               u.stay_id,
               u.status_id,
               u.washestotal,
               u.customerowned
          into customerid,
               productid,
               sizeid,
               finishingmethodid,
               vissuedate,
               distributionpointid,
               stayid,
               statusid,
               vwashestotal,
               vcustomerowned
          from uniqueitem u, uniqueitemfixedinfo f
         where u.uniqueitem_id = uniqueitemid
           and u.uniqueitem_id = f.uniqueitem_id;
        if customerid is null then
          if distributionpointid is not null then
            select e.customer_id
              into customerid
              from distributionpoint d, department e
             where distributionpointid = d.distributionpoint_id
               and d.department_id = e.department_id;
          elsif lastdistribpointid is not null then
            select e.customer_link_id
              into customerid
              from distributionpoint_link d, department_link e
             where lastdistribpointid = d.distributionpoint_id
               and d.department_link_id = e.department_link_id;
          end if;
        end if;
      exception
        when no_data_found then
          accept := 'N';
          pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                  debuglevel,
                                  'PROCESSSORTSCAN',
                                  lvplantid,
                                  3,
                                  1);
      end;
    end if;
    --stay, status
    vpreviousstay := stayid;
    select stay_id
      into stayid
      from stay
     where stay.staytype = 1
       and stay.staynr = 34; --Sorted
    select status_id
      into assigned
      from status
     where status.statustype = 'UI'
       and status.code = '30'; --assigned
    select status_id
      into incirc
      from status
     where status.statustype = 'UI'
       and status.code = '20'; --in circulation
    --if status is not incirc or assigned then doesn't scan
    if statusid not in (assigned, incirc) then
      accept := 'N';
      pack_sort.write_logging('!> ' || idcode || ' ' ||
                              ' Status not in circulation or assigned for IDcode ',
                              debuglevel,
                              'PROCESSSORTSCAN',
                              lvplantid,
                              3,
                              1);
    end if;
    if accept = 'Y' then
      begin
        begin
          update uniqueitem u
             set u.lastscandate   = vlastscandatetime,
                 u.prevstay_id    = vpreviousstay,
                 u.stay_id        = stayid,
                 u.staychangedate = vlastscandatetime,
                 u.systemuser_id  = systemuserid,
                 u.timestamp      = sysdate
           where u.uniqueitem_id = uniqueitemid;
          if debuglevel > 0 then
            pack_sort.write_logging('ID code ' || idcode ||
                                    ' update uniqueitem ' || uniqueitemid,
                                    debuglevel,
                                    'PROCESSSORTSCAN',
                                    lvplantid,
                                    1,
                                    1);
          end if;
        exception
          when others then
            accept := 'N';
            pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                    debuglevel,
                                    'PROCESSSORTSCAN',
                                    lvplantid,
                                    3,
                                    1);
        end;
        --scan record
        begin
          select u.lastoutroute_id
            into routeid
            from uniqueitemroute u
           where u.uniqueitem_id = uniqueitemid;
        exception
          when no_data_found then
            routeid := null;
        end;
        begin
          insert into scan
            (scan_id,
             businessunit_id,
             scantimestamp,
             primaryid,
             customer_link_id,
             weareremployment_link_id,
             distributionpoint_link_id,
             product_link_id,
             sizedefinition_link_id,
             stay_id,
             status_id,
             scanstation,
             issuedate,
             route_id,
             reasoncode_id,
             customerowned,
             year,
             week,
             dayno,
             qualitygrade_id,
             systemuser_id,
             timestamp,
             prevstay_id,
             transactiontype_id,
             dayslate,
             uniqueitem_link_id,
             secondaryid)
          values
            (seq_scan.nextval,
             businessunitid,
             vlastscandate,
             idcode,
             customerid,
             weareremploymentid,
             distributionpointid,
             productid,
             sizeid,
             stayid,
             statusid,
             workstationcode,
             vissuedate,
             routeid,
             null,
             vcustomerowned,
             vyear,
             vweek,
             vdayno,
             null,
             systemuserid,
             sysdate,
             vpreviousstay,
             transactiontp,
             0,
             uniqueitemid,
             secondaryid)
          returning scan_id into vscanid;
          if debuglevel > 0 then
            pack_sort.write_logging('ID code ' || idcode ||
                                    ' insert scan uniqueitem ' ||
                                    uniqueitemid,
                                    debuglevel,
                                    'PROCESSSORTSCAN',
                                    lvplantid,
                                    1,
                                    1);
          end if;
          -- MBA td 9345
        exception
          when others then
            accept := 'N';
            pack_sort.write_logging('!> ' || idcode || ' ' || sqlerrm,
                                    debuglevel,
                                    'PROCESSSORTSCAN',
                                    lvplantid,
                                    3,
                                    1);
        end;
        -- MBA td 9345 - insert also scanflag if flag1/2/3/4 is provided
        if (vscanid > 0 and (flagcode1 is not null or flagcode2 is not null or
           flagcode3 is not null or flagcode4 is not null)) then
          createscanflag(vscanid,
                         systemuserid,
                         debuglevel,
                         flagcode1,
                         flagcode2,
                         flagcode3,
                         flagcode4,
                         lvplantid);
        end if;
        if (vscanid > 0) then
          add_scanflag(vscanid,
                       uniqueitemid,
                       'CheckPointScan',
                       lvplantid,
                       systemuserid);
        end if;
        -- end td 9345
      end; --for accept='Y'
    end if; --for accept='Y'
  end processsortscan;
  function iscustomeractive(customerid   customer.customer_id%type,
                            specificdate date) return boolean is
    activ customer.active%type;
  begin
    select c.active
      into activ
      from customer c
     where c.customer_id = customerid
       and c.active = 'Y'
       and c.dateactive <= specificdate;
    --and    c.dateinactive >= specificdate; TD 25261
    return true;
  exception
    when others then
      return false;
  end iscustomeractive;
  function getstopstatus(customerid   customer.customer_id%type,
                         specificdate date) return number is
    status number;
  begin
    status := -1;
    select decode((c.dateinactive - specificdate) -
                  abs(c.dateinactive - specificdate),
                  0,
                  0,
                  4)
      into status
      from customer c
     where c.customer_id = customerid
       and c.active = 'Y'
       and c.dateactive <= specificdate;
    return status;
  exception
    when others then
      return - 1;
  end getstopstatus;
  procedure importsoilscan(fpnplantid      plant.plant_id%type,
                           fpsreadfilename varchar2) is
    lvnsystemuserid       systemuser.systemuser_id%type;
    lvsplantcode          plant.code%type;
    lvsworkstationcode    workstation.code%type;
    lvninscanhourinterval number;
    lvslogdir             systemsetting.value%type;
    lvsreaddir            systemsetting.value%type;
    lvhreadfile           utl_file.file_type;
    lvsreadline           varchar2(4000);
    lvnposition           number;
    lvserror              varchar2(155);
    lvsbarcode            uniqueitem.primaryid%type;
    lvnuniqueid           uniqueitem.uniqueitem_id%type;
    lvnsecondaryid        secondaryuniqueitem.uniqueitem_id%type;
    lvnbusinessunitid     businessunit.businessunit_id%type;
    lvdtpickupdate        date;
    lvdtscandate          date;
    lvdtlastscandate      uniqueitem.lastscandate%type;
    lvdtlastinscandate    uniqueitem.lastinscandate%type;
    lvsstatuscode         status.code%type;
    lvnstaynr             stay.staynr%type;
    lvsaccept             varchar2(1);
    lvndebuglevel         integer := 0;
    lvsscaninterval       varchar2(1);
    lvsscanbyroute        varchar2(1) := 'Y';
    lvscountwashesat      varchar2(1) := 'Y';
    lvuserexception exception;
  begin
    --get systemuser
    lvserror := 'Error getting the sytem user';
    begin
      select s.systemuser_id
        into lvnsystemuserid
        from systemuser s
       where s.username = 'SORT';
    exception
      when no_data_found then
        select min(systemuser_id) into lvnsystemuserid from systemuser;
    end;
    --get plant id
    lvserror := 'Plant id ' || fpnplantid;
    select p.code
      into lvsplantcode
      from plant p
     where p.plant_id = fpnplantid;
    --get workstation
    lvserror := 'Error getting the inscan workstation for plant ' ||
                lvsplantcode;
    select min(w.code)
      into lvsworkstationcode
      from sortingimportdefinition s, workstation w
     where s.plant_id = fpnplantid
       and s.transactiontype = 1
       and s.workstation_id = w.workstation_id;
    --get inscan hour interval for plant
    lvserror := 'INSCANALLOWHOURINTERVAL for plant ' || lvsplantcode;
    select to_number(trim(s.value))
      into lvninscanhourinterval
      from systemsetting s
     where s.name = 'INSCANALLOWHOURINTERVAL'
       and s.plant_id = fpnplantid;
    --get log file
    lvserror := 'Getting DATABASELOGDIR for plant ' || lvsplantcode;
    select s.value
      into lvslogdir
      from systemsetting s
     where s.name = 'DATABASELOGDIR'
       and s.plant_id = fpnplantid;
    --get soil scan file
    lvserror := 'opening processimportsoilscans.log in directory ' ||
                lvslogdir || ' for plant ' || lvsplantcode;
    lvserror := 'Getting IMPDIRSOILSCANORACLE for plant ' || lvsplantcode;
    select s.value
      into lvsreaddir
      from systemsetting s
     where s.name = 'IMPDIRSOILSCANORACLE'
       and s.plant_id = fpnplantid;
    lvserror    := 'opening ' || fpsreadfilename ||
                   ' for reading in directory ' || lvsreaddir ||
                   ' for plant ' || lvsplantcode;
    lvhreadfile := utl_file.fopen(lvsreaddir, fpsreadfilename, 'r');
    --getting system settings
    lvserror := 'Getting system settings for plant ' || lvsplantcode;
    begin
      select substr(trim(s.value), 1, 1)
        into lvscountwashesat
        from systemsetting s
       where s.name = 'COUNTWASHESAT'
         and s.plant_id = fpnplantid;
    exception
      when no_data_found then
        lvscountwashesat := 'N';
    end;
    begin
      select substr(trim(s.value), 1, 1)
        into lvsscanbyroute
        from systemsetting s
       where s.plant_id = fpnplantid
         and s.name = 'SCANBYROUTE';
    exception
      when no_data_found then
        lvsscanbyroute := 'Y';
    end;
    --process fpsreadfilename file
    lvserror := 'reading ' || fpsreadfilename || ' reading in directory ' ||
                lvsreaddir || ' for plant ' || lvsplantcode;
    loop
      begin
        begin
          -- get line from file.
          utl_file.get_line(lvhreadfile, lvsreadline);
        exception
          when no_data_found then
            exit;
        end;
        --get barcode
        lvnposition := instr(lvsreadline, '''') - 1;
        lvsbarcode  := substr(lvsreadline, 1, lvnposition);
        lvserror    := 'None pool chipcode ' || lvsbarcode || ' for plant ' ||
                       lvsplantcode;
        select u.uniqueitem_id,
               u.businessunit_id,
               st.code,
               sy.staynr,
               u.lastscandate,
               u.lastinscandate
          into lvnuniqueid,
               lvnbusinessunitid,
               lvsstatuscode,
               lvnstaynr,
               lvdtlastscandate,
               lvdtlastinscandate
          from uniqueitem u, businessunit bu, status st, stay sy
         where u.primaryid = lvsbarcode
           and u.poolitem = 2
           and u.businessunit_id = bu.businessunit_id
           and bu.plant_id = fpnplantid
           and u.status_id = st.status_id
           and u.stay_id = sy.stay_id;
        --secondaryID
        begin
          select s.secondaryid
            into lvnsecondaryid
            from secondaryuniqueitem s
           where s.uniqueitem_id = lvnuniqueid;
        exception
          when no_data_found then
            null;
        end;
        --get pickup date
        lvserror       := 'invalid pickupdate for chipcode ' || lvsbarcode;
        lvdtpickupdate := to_date(substr(lvsreadline, lvnposition + 4, 10),
                                  'yyyy-mm-dd');
        --get scan date
        lvserror     := 'invalid scandate/time for chipcode ' || lvsbarcode;
        lvdtscandate := to_date(substr(lvsreadline, lvnposition + 17, 10) ||
                                substr(lvsreadline, lvnposition + 30, 8),
                                'yyyy-mm-dd hh24:mi:ss');
        --check barcode status
        if lvsstatuscode not in ('20', '30') then
          begin
            lvserror := 'Chipcode ' || lvsbarcode || ' has wrong status ' ||
                        lvsstatuscode;
            raise lvuserexception;
          end;
        end if;
        --check barcode last scandate with lastscandate
        if lvdtlastscandate > lvdtscandate then
          begin
            lvserror := 'Chipcode ' || lvsbarcode ||
                        ' has been scanned already';
            raise lvuserexception;
          end;
        end if;
        --check inscan hour interval
        if lvninscanhourinterval > 0 and lvdtlastinscandate is not null and
           lvnstaynr = 30 and (lvdtlastinscandate +
           (lvninscanhourinterval / 24)) > lvdtscandate then
          begin
            lvserror := 'Chipcode ' || lvsbarcode ||
                        ' has been scanned in less then ' ||
                        lvninscanhourinterval || ' hours before';
            raise lvuserexception;
          end;
        end if;
        --barcode is ok to be processed
        lvserror := 'Error during pack_sort.processinscan for barcode ' ||
                    lvsbarcode;
        pack_sort.processinscan(1,
                                lvsbarcode,
                                2,
                                lvnsecondaryid,
                                fpnplantid,
                                fpnplantid,
                                lvnbusinessunitid,
                                lvnuniqueid,
                                lvsworkstationcode,
                                to_number(to_char(lvdtscandate, 'YYYYMMDD')),
                                to_char(lvdtscandate, 'HH24MISS'),
                                lvscountwashesat,
                                lvsscanbyroute,
                                lvnsystemuserid,
                                lvndebuglevel,
                                lvsaccept,
                                lvsscaninterval,
                                lvdtpickupdate);
        commit;
      exception
        when lvuserexception then
          begin
            rollback;
            dbms_output.put_line(lvserror);
          end;
        when no_data_found then
          begin
            rollback;
            lvserror := lvserror || ' does not exist.';
            dbms_output.put_line(lvserror);
          end;
        when others then
          begin
            rollback;
            lvserror := lvserror || ' ' || substr(sqlerrm, 1, 200);
            dbms_output.put_line(lvserror);
          end;
      end;
    end loop;
  exception
    when utl_file.invalid_path then
      begin
        lvserror := lvserror || ' Invalid Path';
        dbms_output.put_line(lvserror);
      end;
    when utl_file.invalid_mode then
      begin
        lvserror := lvserror || ' Invalid Mode';
        dbms_output.put_line(lvserror);
      end;
    when utl_file.invalid_operation then
      begin
        lvserror := lvserror || ' Invalid Operation';
        dbms_output.put_line(lvserror);
      end;
    when utl_file.invalid_filehandle then
      begin
        lvserror := lvserror || ' Invalid Filehandle';
        dbms_output.put_line(lvserror);
      end;
    when utl_file.write_error then
      begin
        lvserror := lvserror || ' Write Error';
        dbms_output.put_line(lvserror);
      end;
    when utl_file.read_error then
      begin
        lvserror := lvserror || ' Read Error';
        dbms_output.put_line(lvserror);
      end;
    when utl_file.internal_error then
      begin
        lvserror := lvserror || ' Internal Error';
        dbms_output.put_line(lvserror);
      end;
    when no_data_found then
      begin
        rollback;
        lvserror := lvserror || ' does not exist.';
        dbms_output.put_line(lvserror);
      end;
    when others then
      begin
        rollback;
        lvserror := lvserror || ' ' || substr(sqlerrm, 1, 200);
        dbms_output.put_line(lvserror);
      end;
  end importsoilscan;
  function getsortstringsupport(plantid      in plant.plant_id%type,
                                customerid   in customer.customer_id%type,
                                routestopid  in routestop.routestop_id%type,
                                uniqueitemid in uniqueitem.uniqueitem_id%type)
    return varchar2 is
    sortstring           varchar2(255);
    productcode          product.code%type;
    sizecode             sizedefinition.code%type;
    customernumber       customer.customernumber%type;
    wearernumber         wearer.wearernumber%type;
    wearername           wearer.searchname%type;
    banklocker           varchar2(12);
    departmentnumber     department.departmentnumber%type;
    customeremployee#    wearer.customeremployeenumber%type;
    gender               wearer.sex%type;
    garmentdispensercode garmentdispenser.code%type;
    deliverypointcode    deliverypoint.code%type;
    lockerid             locker.locker_id%type;
    garmentdispenserid   garmentdispenser.garmentdispenser_id%type;
    deliverypointid      deliverypoint.deliverypoint_id%type;
    stopnumber           routestop.stopnumber%type;
    routenumber          route.routenumber%type;
    packingsequence      product.packingsequence%type;
    vcustomerowned       varchar2(1);
    settingsortroutestop varchar2(1);
  begin
    sortstring := '';
    begin
      begin
        select p.code,
               s.code,
               c.customernumber,
               w.wearernumber,
               w.searchname,
               w.customeremployeenumber,
               w.sex,
               d.departmentnumber,
               e.deliverypoint_id,
               e.locker_id,
               e.garmentdispenser_id,
               p.packingsequence,
               u.customerowned
          into productcode,
               sizecode,
               customernumber,
               wearernumber,
               wearername,
               customeremployee#,
               gender,
               departmentnumber,
               deliverypointid,
               lockerid,
               garmentdispenserid,
               packingsequence,
               vcustomerowned
          from uniqueitem        u,
               uniqueitemnonpool n,
               weareremployment  e,
               wearer            w,
               customer          c,
               department        d,
               distributionpoint di,
               product           p,
               sizedefinition    s
         where u.uniqueitem_id = uniqueitemid
           and u.product_id = p.product_id
           and u.sizedefinition_id = s.sizedefinition_id
           and u.uniqueitem_id = n.uniqueitem_id
           and n.weareremployment_id = e.weareremployment_id
           and e.wearer_id = w.wearer_id
           and w.customer_id = c.customer_id
           and c.customer_id = customerid
           and e.distributionpoint_id = di.distributionpoint_id
           and di.department_id = d.department_id;
      exception
        when no_data_found then
          sortstring := '01';
      end;
      if sortstring is null then
        pack_sort.getgarmentlocation(lockerid,
                                     garmentdispenserid,
                                     deliverypointid,
                                     banklocker,
                                     garmentdispensercode,
                                     deliverypointcode);
        begin
          select rs.stopnumber, r.routenumber
            into stopnumber, routenumber
            from routestop rs, route r
           where rs.routestop_id = routestopid
             and r.route_id = rs.route_id;
        exception
          when no_data_found then
            sortstring := '02';
        end;
      end if;
      --read systemsettings
      if sortstring is null then
        begin
          select s.value
            into settingsortroutestop
            from systemsetting s
           where s.plant_id = plantid
             and s.name = 'SORTROUTESTOP';
          if settingsortroutestop = 'A' then
            sortstring := lpad(to_char(routenumber), 6, 0) ||
                          lpad(to_char(stopnumber), 4, 0);
          elsif settingsortroutestop = 'Z' then
            sortstring := lpad(to_char(stopnumber), 4, 0);
          elsif settingsortroutestop = 'D' then
            sortstring := lpad(to_char(routenumber), 6, 0) ||
                          lpad(to_char(9999 - stopnumber), 6, 0);
          end if;
        end;
      end if;
      sortstring := sortstring || lpad(customernumber, 12, 0);

      if banklocker is null then
        sortstring := sortstring || '            ';
      else
        sortstring := sortstring || banklocker;
      end if;

      sortstring := sortstring || lpad(to_char(wearernumber), 12, 0);

    exception
      when others then
        sortstring := '0';
    end;
    return(sortstring);
  end getsortstringsupport;

  procedure getnextdeliverydatewithstop(currentdate     in date,
                                        plantid         in plant.plant_id%type,
                                        customerid      in customer.customer_id%type,
                                        typeofmerch     in product.typeofmerchandise%type,
                                        deliverypointid in deliverypoint.deliverypoint_id%type,
                                        retvisitdate    out date,
                                        retroute        out route.route_id%type) is
    visitdate   date;
    routestopid number;
  begin

    for vcursor in (select c.day_id, d.deliveryscheme_id, x.frequency
                      from customerdeliveryday    c,
                           customerdeliveryscheme d,
                           deliveryscheme         x
                     where c.customer_id = customerid
                       and c.customer_id = d.customer_id
                       and c.day_id = d.day_id
                       and c.typeofmerchadise = typeofmerch
                       and c.deliverytype in ('B', 'D')
                       and d.deliveryscheme_id = x.deliveryscheme_id
                       and d.active = 'Y') loop
      begin
        visitdate   := pack_sort.getvisitdate(vcursor.deliveryscheme_id,
                                              vcursor.day_id,
                                              currentdate);
        routestopid := pack_sort.getroutestopforcustomer(plantid,
                                                         visitdate,
                                                         customerid,
                                                         deliverypointid);
        if visitdate is not null and routestopid is not null then
          begin
            retvisitdate := visitdate;
            select rs.route_id
              into retroute
              from routestop rs
             where rs.routestop_id = routestopid;
            EXIT;
          end;
        end if;
      end;
    end loop;

  end getnextdeliverydatewithstop;

begin
  i := 0;
  select s.sizedefinition_id
    into gv_specialsizeid
    from sizedefinition s
   where s.code = '*';
end pack_sort;
/
