
/*********************************************\
*   Objects:           CONVERSION PACKAGES    *
*   Database version:  09.10.00               *
*   Date:              17-FEB-2026            *
\*********************************************/
set define off
create or replace package pack_import is
  /*********************************************\
  *   Objects:           CONVERSION PACKAGES    *
  *   Version            2.7                    *
  \*********************************************/
  --External variables
  lvnuserexception exception;
  lvnusergroupid              usergroup.usergroup_id%type;
  lvncurrencydefaultid        currency.currency_id%type;
  lvncountrydefaultid         country.country_id%type;
  lvnregionid                 region.region_id%type;
  lvndivisionid               division.division_id%type;
  lvndefaultqualitygradeid    qualitygrade.qualitygrade_id%type;
  lvnsalesjournalgroupminusid salesjournalgroup.salesjournalgroup_id%type;
  lvnsystemuserid             systemuser.systemuser_id%type;
  lvnlanguageid               languages.language_id%type;
  lvdbcustomercode            databasesettings.code%type;
  lvnlanguagecode             languages.code%type;
  --External procedure functions
  procedure write_log(fpserr_msg varchar2, fpnpriority number default 1);
  procedure cfbimportplantfixedinfo;
  procedure cfbdelete_itables;
  procedure disable_i_constraints;
  procedure enable_i_constraints;
  procedure cfbcreate_activity(fpnactivityid   in out activity.activity_id%type,
                               fpsactivitycode in activity.code%type);
  procedure cfbget_create_budgetunit(fp_budgetunitid   in out budgetunit.budgetunit_id%type,
                                     fp_budgetunitcode in budgetunit.code%type,
                                     fp_budgetunitdesc in budgetunit_desc.description%type default null);
  procedure cfbcreate_color(fpncolor_id      in out color.color_id%type,
                            fpscode          in color.code%type,
                            fpsralcode       in color.ralcode%type,
                            fpsusedforemblem in color.usedforemblem%type);
  procedure cfbcreate_color_desc(fpncolor_id    in color_desc.color_id%type,
                                 fpsdescription in color_desc.description%type);
  procedure cfbcreate_contact(fpncontact_id         in out contact.contact_id%type,
                              fpncustomer_link_id   in contact.customer_link_id%type,
                              fpndepartment_link_id in contact.department_link_id%type,
                              fpnbusinessunit_id    in contact.businessunit_id%type,
                              fpncontactcategory_id in contact.contactcategory_id%type,
                              fpncreatedbyuser_id   in contact.createdbyuser_id%type,
                              fpnfollowupbyuser_id  in contact.followupbyuser_id%type,
                              fpdtnewdate           in contact.newdate%type,
                              fpncallnumber         in contact.callnumber%type,
                              fpdtfollowupdate      in contact.followupdate%type,
                              fpdtinprogressdate    in contact.inprogressdate%type,
                              fpdtclosedate         in contact.closedate%type,
                              fpnstatus             in contact.status%type,
                              fpscontactpersonname  in contact.contactpersonname%type,
                              fpncontactperson_id   in contact.contactperson_id%type,
                              fpsfollowupbyusername in contact.followupbyusername%type,
                              fpscreatedbyusername  in contact.createdbyusername%type,
                              fpscontactnotes       in contact.contactnotes%type,
                              fpsfollowupnotes      in contact.followupnotes%type,
                              fpsattachment         in contact.attachment%type,
                              fpsshowonroutelist    in contact.showonroutelist%type,
                              fp_inprogressbyuserid in contact.inprogressbyuser_id%type,
                              fp_inprogressbyusernm in varchar2,
                              fp_closedbyuserid     in contact.closedbyuser_id%type,
                              fp_closedbyusername   in varchar2,
                              fp_priority           in contact.priority%type,
                              fp_contactcause_code  in varchar2,
                              fp_completeddate      in contact.completeddate%type,
                              fp_completedbyuserid  in contact.completedbyuser_id%type,
                              fp_completedbyuserame in varchar2,
                              fp_reviewdate         in contact.reviewdate%type,
                              fp_reviewedbyuserid   in contact.reviewedbyuser_id%type,
                              fp_reviewedbyusername in varchar2,
                              fp_blockdepartonstop  in contact.blockdepartureonstop%type,
                              fp_followupbyroute    in contact.followupbyroute%type,
                              fp_originalcallnumber in number,
                              fp_checkbefroutestart in contact.checkbeforeroutestart%type);
  procedure cfbcreate_contactcategory(fpncontactcategory_id     in out contactcategory.contactcategory_id%type,
                                      fpscode                   in contactcategory.code%type,
                                      fpsdefaultcontactcategory in contactcategory.defaultcontactcategory%type);
  procedure cfbcreate_contactcategory_desc(fpncontactcategory_id in contactcategory_desc.contactcategory_id%type,
                                           fpsdescription        in contactcategory_desc.description%type);
  procedure cfbcreate_costcenter(fpncostcenter_id     in out costcenter.costcenter_id%type,
                                 fpscode              in costcenter.code%type,
                                 fpsdescription       in costcenter.description%type,
                                 fpncustomer_id       in costcenter.customer_id%type,
                                 fpninvoiceaddress_id in costcenter.invoiceaddress_id%type,
                                 fpncontactperson_id  in costcenter.contactperson_id%type,
                                 fp_ponumber          in costcenter.ponumber%type default null,
                                 fp_requisitionnumber in costcenter.requisitionnumber%type default null,
                                 fp_accountingstring  in costcenter.accountingstring%type default null,
                                 fp_eannumber         in costcenter.eannumber%type default null,
                                 fp_exportedi         in costcenter.exportedi%type default null,
                                 fp_costcentergroupid in costcenter.costcentergroup_id%type default null);
  procedure cfbcreate_customer(fpncustomer_id                in out customer.customer_id%type,
                               fpncustomernumber             in customer.customernumber%type,
                               fpsname                       in customer.name%type,
                               fpsphoneno                    in customer.phoneno%type,
                               fpslegalname                  in customer.legalname%type,
                               fpsfaxno                      in customer.faxno%type,
                               fpsemail                      in customer.email%type,
                               fpdtdateactive                in customer.dateactive%type,
                               fpdtdateinactive              in customer.dateinactive%type,
                               fpsactive                     in customer.active%type,
                               fpsremark                     in customer.remark%type,
                               fpssiccode                    in customer.siccode%type,
                               fpssearchname                 in customer.searchname%type,
                               fpslegacycustomernumber       in customer.legacycustomernumber%type,
                               fpsoccupancyfromstockcount    in customer.occupancyfromstockcount%type,
                               fpndebtor_id                  in out customer.debtor_id%type,
                               fpndefaultbusinessunit_id     in customer.defaultbusinessunit_id%type,
                               fpnmasteraccount_id           in out customer.masteraccount_id%type,
                               fpnmasteraccount              in customer.masteraccount%type,
                               fpnmarketsegment_id           in customer.marketsegment_id%type,
                               fpnsalesarea_id               in customer.salesarea_id%type,
                               fpncurrency_id                in customer.currency_id%type,
                               fpncountry_id                 in customer.country_id%type,
                               fpnvisitaddress_id            in customer.visitaddress_id%type,
                               fpnmailaddress_id             in customer.mailaddress_id%type,
                               fpncommunicationmethod_id     in customer.communicationmethod_id%type,
                               fpssoilcount                  in customer.soilcount%type,
                               fpndeliverynotelayout_id      in customer.deliverynotelayout_id%type,
                               fpnconsignmentnotelayout_id   in customer.consignmentnotelayout_id%type,
                               fpsinternetordering           in customer.internetordering%type,
                               fpsimportoccupancyhht         in customer.importoccupancyhht%type,
                               fpnreturnlinen                in customer.returnlinen%type,
                               fpnreturngarments             in customer.returngarments%type,
                               fpscodegarmentsuniquely       in customer.codegarmentsuniquely%type,
                               fpndaysnoprepcharge           in customer.daysnoprepcharge%type,
                               fpschargerepairs              in customer.chargerepairs%type,
                               fpngarmentrentspecification   in customer.garmentrentspecification%type,
                               fpsswingsuitdelivery          in customer.swingsuitdelivery%type,
                               fpsusesgarmentdispenser       in customer.usesgarmentdispenser%type,
                               fpslockermanagement           in customer.lockermanagement%type,
                               fpnfirstdaysgrade_id          in customer.firstdaysgrade_id%type,
                               fpndaysspecialgrade           in customer.daysspecialgrade%type,
                               fpnfirstissuegrade_id         in customer.firstissuegrade_id%type,
                               fpnqualitygrade_id            in customer.qualitygrade_id%type,
                               fpnserviceteam_id             in customer.serviceteam_id%type,
                               fpnstandardqtydefinition      in customer.standardqtydefinition%type,
                               fpscorrectshortages           in customer.correctshortages%type,
                               fpscorrectoverdeliveries      in customer.correctoverdeliveries%type,
                               fpninvoicelayout_id           in customer.invoicelayout_id%type,
                               fpninvoicecopies              in customer.invoicecopies%type,
                               fpnminimuminvoiceamount       in customer.minimuminvoiceamount%type,
                               fpstaxable                    in customer.taxable%type,
                               fpnpaymentmethod              in customer.paymentmethod%type,
                               fpnpaymenttype                in customer.paymenttype%type,
                               fpnstates_id                  in customer.states_id%type,
                               fpncountytaxauthority_id      in customer.countytaxauthority_id%type,
                               fpncitytaxauthority_id        in customer.citytaxauthority_id%type,
                               fpbisownmasteraccount         in varchar2,
                               fpbisowndebtor                in varchar2,
                               fpsmarkinggarment             in customer.customermarkinggarment%type,
                               fpninvoicefrequency_id        in customer.invoicefrequency_id%type,
                               fpncodelabellayout_id         in customer.codelabellayout_id%type,
                               fpnnamelabellayout_id         in customer.namelabellayout_id%type,
                               fpsallowprepchargepertemplate in customer.allowprepchargepertemplate%type,
                               fpnemblemspecification        in customer.emblemspecification%type,
                               fpnallownegativestockcount    in customer.allownegativestockcount%type,
                               fpnoutscansort                in customer.outscansort%type,
                               fpschargewashfirstissue       in customer.chargewashfirstissue%type,
                               fpsallowautomaticsales        in customer.allowautomaticsales%type,
                               fpncustomerrelated            in customer.customerrelated%type,
                               fpschargeresidualvalue        in customer.chargeresidualvalue%type,
                               fpnrentperiod                 in customer.rentperiod%type,
                               fpnsplitinvoices              in customer.splitinvoices%type,
                               fpsvatnumber                  in customer.vatnumber%type,
                               fpnchain_id                   in customer.chain_id%type,
                               fpngarmentinsurance           in customer.garmentinsurance%type,
                               fpninvoiceaddress_id          in customer.invoiceaddress_id%type,
                               fpnilnnumber                  in customer.ilnnumber%type,
                               fpsusesbundles                in customer.usesbundles%type,
                               fpsextraname1                 in customer.extraname1%type,
                               fpsextraname2                 in customer.extraname2%type,
                               fpnscansondeliverynote        in customer.scansondeliverynote%type,
                               fpnassociationtype            in customer.associationtype%type default 0,
                               fpsdirectinvdeliveries        in customer.directinvdeliveries%type,
                               fpsdirectinvcleanweights      in customer.directinvcleanweights%type,
                               fpsdirectinvsoilweights       in customer.directinvsoilweights%type,
                               fpndirectinvminimumamount     in customer.directinvminimumamount%type,
                               fpsusecoverpage               in customer.usecoverpage%type,
                               fpnsignaturerequired          in customer.signaturerequired%type,
                               fpnnationalaccount_id         in customer.nationalaccount_id%type,
                               fpncocnumber                  in customer.cocnumber%type,
                               fnpnnumber                    in customer.pnnumber%type,
                               fpnserviceemployee_id         in customer.serviceemployee_id%type,
                               fpncommoncustomer_id          in customer.commoncustomer_id%type,
                               fpbbonusagreement             in customer.bonusagreement%type,
                               fpnacquisioncode_id           in customer.acquisioncode_id%type,
                               fpncustomerranking_id         in customer.customerranking_id%type,
                               fpntdccode                    in customer.tdccode%type,
                               fpschargelosscharge           in customer.chargelosscharge%type,
                               fpsedimethod                  in customer.edimethod%type,
                               fpstaxexemptcode              in customer.taxexemptcode%type,
                               fpsinheritmapricelist         in customer.inheritmapricelist%type,
                               fpsrestrictonmaproducts       in customer.restrictonmaproducts%type,
                               fpnsalesemployee1             in customer.salesemployee1_id%type default null,
                               fpnsalesemployee2             in customer.salesemployee2_id%type default null,
                               fpssplitinvoicesperactivity   in customer.splitinvoicesperactivity%type default 'N',
                               fpnchargerepaircog            in customer.chargerepaircog%type default 0,
                               fpninternalbu                 in customer.internalbusinessunit_id%type default null,
                               fpndefaultinvbu               in customer.defaultinvoicebusinessunit_id%type default null,
                               fpbinformpriceupdate          in customer.informpriceupdate %type default 'N',
                               fpbdirectinvallservices       in customer.directinvallservices%type default 'N',
                               fpbdirectinvsalesnotes        in customer.directinvsalesnotes%type default 'N',
                               fpbdepositstockallowed        in customer.depositstockallowed%type default 'N',
                               fpnalternatesorting           in customer.alternatesorting%type default 'N',
                               fpninternalcalcpercentagelog  in customer.internalcalcpercentagelog%type default null,
                               fpninternalcalcpercentagecog  in customer.internalcalcpercentagecog%type default null,
                               fpnmaincustomertype           in customer.maincustomertype%type default 1,
                               fpnlanguageid                 in customer.language_id%type default null,
                               fpnlinenreducefactor          in customer.linenreducefactor%type default 0,
                               fpnusecontractcoefficient     in customer.usecontractcoefficient%type default 'N',
                               fpncontractcoefficient        in customer.contractcoefficient%type default 0,
                               fpnreturnsamecontainer        in customer.returnsamecontainer%type default 'N',
                               fpnownbatch                   in customer.ownbatch%type default 'N',
                               fpninvoicecurrencyid          in customer.invoicecurrency_id%type default null,
                               fpcustomgarmentcharge         in customer.customgarmentcharge%type default 'N',
                               fp_useprodsizesurchargpricing in customer.useprodsizesurchargepricing%type default 'N',
                               fpautosoilpercentage          in customer.autosoilpercentage%type default 0,
                               fptaxexemptcertificatedoc     in customer.taxexemptcertificatedocument%type default null,
                               fpchargerestockingfee         in customer.chargerestockingfee%type default 'N',
                               fpmasteraccountrelation       in customer.masteraccountrelation%type default 0,
                               fpseasonautoflagallowed       in customer.seasonautoflagallowed%type default 'N',
                               fppasserbycustomer            in customer.passerbycustomer%type default 'N',
                               fpfirstservicedate            in customer.firstservicedate%type default null);
  procedure cfbcreate_customeractivities(fpncustomer_id            in customeractivities.customer_id%type,
                                         fpnactivity_id            in customeractivities.activity_id%type,
                                         fpninvoicebusinessunit_id in customeractivities.invoicebusinessunit_id%type,
                                         fpnprocessbusinessunit_id in customeractivities.processbusinessunit_id%type,
                                         fpdtcutoffdate            in customeractivities.cutoffdate%type,
                                         fpsfinalinvoicecreated    in customeractivities.finalinvoicecreated%type,
                                         fpninvoicefrequency       in customeractivities.invoicefrequency_id%type,
                                         fpnsalesemployee1         in customeractivities.salesemployee1_id%type default null,
                                         fpnsalesemployee2         in customeractivities.salesemployee2_id%type default null,
                                         fpninternalbusinessunitid in customeractivities.internalprocessingbu_id%type default null);
  procedure cfbcreate_customerbillinginfo(fpncustomer_id               in out customerbillinginfo.customer_id%type,
                                          fpndelinquentmarkafter       in customerbillinginfo.delinquentmarkafter%type,
                                          fpncreditlimit               in customerbillinginfo.creditlimit%type,
                                          fpnfinancechargeputon        in customerbillinginfo.financechargeputon%type,
                                          fpnfinancechargedays         in customerbillinginfo.financechargedays%type,
                                          fpnstatementcopies           in customerbillinginfo.statementcopies%type,
                                          fpsstatementpercustomer      in customerbillinginfo.statementpercustomer%type,
                                          fpsattachinvoicecopies       in customerbillinginfo.attachinvoicecopies%type,
                                          fpnstatementfrequency_id     in customerbillinginfo.statementfrequency_id%type,
                                          fpnsendstatement             in customerbillinginfo.sendstatement%type,
                                          fpssendstatementbyemail      in customerbillinginfo.sendstatementbyemail%type,
                                          fpncollectionresponsible_id  in customerbillinginfo.collectionresponsible_id%type,
                                          fpnpaymentterms_id           in customerbillinginfo.paymentterms_id%type,
                                          fpnstatementlayout_id        in customerbillinginfo.statementlayout_id%type,
                                          fpnhighestbalance            in customerbillinginfo.highestbalance%type,
                                          fpdthighestbalancedate       in customerbillinginfo.highestbalancedate%type,
                                          fpsconsolidatedinvoice       in customerbillinginfo.consolidatedinvoice%type,
                                          fpsbankaccount               in customerbillinginfo.bankaccount%type,
                                          fpncreditsqueezeperc         in customerbillinginfo.creditsqueezeperc%type,
                                          fpnbankinstitution_id        in customerbillinginfo.bankinstitution_id%type,
                                          fpnconsolidatedreportinv     in customerbillinginfo.consolidatedreportinv%type,
                                          fpnlaundrybankinstitution_id in customerbillinginfo.laundrybankinstitution_id%type,
                                          fpsibanno                    in customerbillinginfo.ibanno%type,
                                          fpnpaybycustomer             in customerbillinginfo.paybycustomer%type,
                                          fpnpaybycustomer_link_id     in customerbillinginfo.paybycustomer_link_id%type,
                                          fpnprintinvoice              in customerbillinginfo.printinvoice%type,
                                          fpnsendinvoiceby             in customerbillinginfo.sendinvoiceby%type,
                                          fpconsolidatedinvlayout_id   in customerbillinginfo.consolidatedinvoicelayout_id%type,
                                          fpgeneratepayment            in customerbillinginfo.generatepayment%type default 0,
										  fpsenddirectinvoicebyemail   in customerbillinginfo.senddirectinvoicebyemail%type);
  procedure cfbcreate_cleanroomcustomertype(fpncleanroomcustomertype_id in out cleanroomcustomertype.cleanroomcustomertype_id%type,
                      fpscode                         in cleanroomcustomertype.code%type,
                      fpsdescription                  in cleanroomcustomertype.description%type,
                      fpsactive                       in cleanroomcustomertype.active%type default 'Y',
                      fpssterile                      in cleanroomcustomertype.sterile%type default 'Y');
  procedure add_check_customerdeliveryday(fpncustomerid        customerdeliveryday.customer_id%type,
                                          fpndayid             customerdeliveryday.day_id%type,
                                          fpsdeliverytype      customerdeliveryday.deliverytype%type,
                                          fpntypeofmerchandise customerdeliveryday.typeofmerchadise%type);
  procedure cfbcreate_customerdelscheme(fpncustomer_id       in number,
                                        fpndeliveryscheme_id in number,
                                        fpnday_id            in number);
  procedure cfbcreate_custspecialcharge(fpncustomer_id      in customerspecialcharge.customer_id%type,
                                        fpnspecialcharge_id in customerspecialcharge.specialcharge_id%type);
  procedure cfbcreate_customerrentprice(fpncustomerrentprice_id      in out customerrentprice.customerrentprice_id%type,
                                        fpnproductlistpercustomer_id in customerrentprice.productlistpercustomer_id%type,
                                        fpnprice                     in customerrentprice.price%type,
                                        fpdtstartdate                in customerrentprice.startdate%type,
                                        fpnchangesperweek            in customerrentprice.changesperweek%type,
                                        fpntypeofrent                in customerrentprice.typeofrent%type,
                                        fpncontractcoefficient       in customerrentprice.contractcoefficient%type default null,
                                        fpnmaxinventory              in customerrentprice.maxinventory%type default 0,
                                        fpnsizebillingroup_id        in customerrentprice.sizebillinggroup_id%type default null
                                        );
  procedure cfbcreate_deliverypoint(fpndeliverypoint_id  in out deliverypoint.deliverypoint_id%type,
                                    fpncustomer_id       in deliverypoint.customer_id%type,
                                    fpscode              in deliverypoint.code%type,
                                    fpsdescription       in deliverypoint.description%type,
                                    fpndeliveryaddressid in deliverypoint.deliveryaddress_id%type,
                                    fpssortaddress       in deliverypoint.sortaddress%type);
  procedure cfbcreate_deliveryvariations(fpndeliveryvariations_id in out deliveryvariations.deliveryvariations_id%type,
                                         fpnproduct_id            in deliveryvariations.product_id%type,
                                         fpdtdeliverydate         in deliveryvariations.deliverydate%type,
                                         fpnorigin                in deliveryvariations.origin%type,
                                         fpnamount                in deliveryvariations.amount%type,
                                         fpnfinishingmethod_id    in deliveryvariations.finishingmethod_id%type,
                                         fpsfixedamount           in deliveryvariations.fixedamount%type,
                                         fpndistributionpoint_id  in deliveryvariations.distributionpoint_id%type,
                                         fpnpackingnote_id        in deliveryvariations.packingnote_id%type,
                                         fpnsizedefinition_id     in deliveryvariations.sizedefinition_id%type,
                                         fpsreference             in deliveryvariations.reference%type,
                                         fpsprocessed             in deliveryvariations.processed%type,
                                         fpncausenote_id          in deliveryvariations.causenote_id%type,
                                         fpsupdaterentqty          in deliveryvariations.updaterentqty%type,
                                         fpnadjustmentreason_id    in deliveryvariations.adjustmentreason_id%type,
                                         fpnprocessbusinessunitid  in deliveryvariations.processbusinessunit_id%type,
                                         fpninternalprocessingbuid in deliveryvariations.internalprocessingbu_id%type);
  procedure cfbcreate_department(fpndepartment_id        in out department.department_id%type,
                                 fpsnumber               in department.departmentnumber%type,
                                 fpsdescription          in department.description%type,
                                 fpncostcenter_id        in department.costcenter_id%type,
                                 fpnoccupancy            in department.occupancy%type,
                                 fpsstandardpackamount   in department.standardpackamount%type,
                                 fpsactive               in department.active%type,
                                 fpncustomer_id          in department.customer_id%type,
                                 fpslegacydepartmentcode in department.legacydepartmentcode%type,
                                 fpncontactperson_id     in department.contactperson_id%type,
                                 fpsdelnotetoemail       in department.delnotetoemail%type);
  procedure cfbcreate_distributionpoint(fpndistributionpoint_id      in out distributionpoint.distributionpoint_id%type,
                                        fpndistributionpointnumber   in distributionpoint.distributionpointnumber%type,
                                        fpsdescription               in distributionpoint.description%type,
                                        fpsremarkonpackingnote       in distributionpoint.remarkonpackingnote%type,
                                        fpsremarkondeliverynote      in distributionpoint.remarkondeliverynote%type,
                                        fpdtpackremarkenddate        in distributionpoint.packremarkenddate%type,
                                        fpdtdeliverremarkenddate     in distributionpoint.deliverremarkenddate%type,
                                        fpsactive                    in distributionpoint.active%type,
                                        fpndepartment_id             in distributionpoint.department_id%type,
                                        fpndeliverypoint_id          in distributionpoint.deliverypoint_id%type,
                                        fpncostcenter_id             in distributionpoint.costcenter_id%type,
                                        fpslegacydistributionpnumber in distributionpoint.legacydistributionpointnumber%type,
                                        fpsproofofvisitbarcode       in distributionpoint.proofofvisitbarcode%type,
                                        fpsdriverinstruction         in distributionpoint.driverinstruction%type,
                                        fp_materialmaintenance       in distribpointbgprotection.materialmaintenance%type default 'N',
                                        fp_garmentsetup              in distribpointbgprotection.garmentsetup%type default 'N',
                                        fp_garmentmaintenance        in distribpointbgprotection.garmentmaintenance%type default 'N',
                                        fp_garmentloss               in distribpointbgprotection.garmentloss %type default 'N',
                                        fp_garmentrepair             in distribpointbgprotection.garmentrepair%type default 'N',
                                        fp_mbyoprotection            in distribpointbgprotection.mbyoprotection%type default 'N',
                                        fp_garmentemblem             in distribpointbgprotection.garmentemblem%type default 'N');
  procedure cfbcreate_deliveryscheme(fpndeliveryscheme_id     in out deliveryscheme.deliveryscheme_id%type,
                                     fpscode                  in deliveryscheme.code%type,
                                     fpsdefaultdeliveryscheme in deliveryscheme.defaultdeliveryscheme%type default 'N',
                                     fpnfrequency             in deliveryscheme.frequency%type default 1,
                                     fpnoffsetweek            in deliveryscheme.offsetweek%type default 0);
  procedure cfbcreate_emblemproduct(fpnproduct_id     in out emblemproduct.product_id%type,
                                    fpnemblemtype     in emblemproduct.emblemtype%type,
                                    fpntextcolor_id   in emblemproduct.textcolor_id%type,
                                    fpnbordercolor_id in emblemproduct.bordercolor_id%type,
                                    fpnemblemfont_id  in emblemproduct.emblemfont_id%type);
  procedure cfbcreate_emblemtemplate(fpnemblemtemplate_id in out emblemtemplate.emblemtemplate_id%type,
                                     fpncustomer_id       in emblemtemplate.customer_id%type,
                                     fpscode              in emblemtemplate.code%type,
                                     fpsdescription       in emblemtemplate.description%type,
                                     fpsprintnamelabel    in emblemtemplate.printnamelabel%type,
                                     fpsactive            in emblemtemplate.active%type,
                                     fpsrentemblem        in emblemtemplate.rentemblem%type);
  procedure cfbcreate_emblemtemplateline(fpnemblemtemplateline_id in out emblemtemplateline.emblemtemplateline_id%type,
                                         fpnemblemtemplate_id     in emblemtemplateline.emblemtemplate_id%type,
                                         fpnproduct_id            in emblemtemplateline.product_id%type,
                                         fpnsizedefinition_id     in emblemtemplateline.sizedefinition_id%type,
                                         fpnfontsize              in emblemtemplateline.fontsize%type,
                                         fpsdescription           in emblemtemplateline.description%type,
                                         fpntextcolor_id          in emblemtemplateline.textcolor_id%type,
                                         fpnbordercolor_id        in emblemtemplateline.bordercolor_id%type,
                                         fpnbkgcolor_id           in emblemtemplateline.bkgcolor_id%type,
                                         fpnfabric_id             in emblemtemplateline.fabric_id%type,
                                         fpnplacement_id          in emblemtemplateline.placement_id%type,
                                         fpnemblemtype            in emblemtemplateline.emblemtype%type,
                                         fpnattachmentby          in emblemtemplateline.attachmentby%type,
                                         fpnqtypergarment         in emblemtemplateline.qtypergarment%type,
                                         fpnemblemimage_id        in emblemtemplateline.emblemimage_id%type,
                                         fpnplacementimage_id     in emblemtemplateline.placementimage_id%type,
                                         fpnemblemfont_id         in emblemtemplateline.emblemfont_id%type);
  procedure cfbcreate_emblemtemplineprice(fpnemblemtemplatelineprice_id in out emblemtemplatelineprice.emblemtemplatelineprice_id%type,
                                          fpnemblemtemplateline_id      in emblemtemplatelineprice.emblemtemplateline_id%type,
                                          fpnprice                      in emblemtemplatelineprice.price%type,
                                          fpdtstartdate                 in emblemtemplatelineprice.startdate%type);
  procedure cfbgetcreate_employee(lvnplant_id            in plant.plant_id%type,
                                  lvnemployee_id         in out employee.employee_id%type,
                                  lvnemployeenumber      in employee.employeenumber%type,
                                  lvsname                in employee.name%type,
                                  lvssearchname          in employee.searchname%type,
                                  lvdtdateactive         in employee.dateactive%type,
                                  lvdtdateinactive       in employee.dateinactive%type,
                                  lvnpdanumber           in employee.pdanumber%type,
                                  lvnmobiledevice_id     in employee.mobiledevice_id%type,
                                  lvnworkspot            in employee.workspot%type,
                                  lvnemployeefunction_id in employee.employeefunction_id%type);
  procedure cfbcreate_fabric(fpnfabric_id     in out fabric.fabric_id%type,
                             fpscode          in fabric.code%type,
                             fpsusedforemblem in fabric.usedforemblem%type);
  procedure cfbcreate_fabric_desc(fpnfabric_id   in fabric_desc.fabric_id%type,
                                  fpsdescription in fabric_desc.description%type);
  procedure cfbcreate_flag(fpnflag_id                   in out flag.flag_id%type,
                           fpnflagtype                  in flag.flagtype%type,
                           fpscode                      in flag.code%type,
                           fpnpriority                  in flag.priority%type,
                           fpscolor                     in flag.color%type,
                           fpsincludeincompletnesscheck in flag.includeincompletnesscheck%type,
                           fpnsound_id                  in flag.sound_id%type,
                           fpsshowalways                in flag.showalways%type,
                           fpsexporttogarmentdispenser  in flag.exporttogarmentdispenser%type,
                           fpnexportgdcode              in flag.exportgdcode%type,
                           fpnuseinwebapplication       in flag.useinwebapplication%type);
  procedure cfbcreate_flag_desc(fpnflag_id     in flag_desc.flag_id%type,
                                fpsdescription in flag_desc.description%type);
  procedure cbcreate_formlayout(fpnformlayout_id in out formlayout.formlayout_id%type,
                                fpsformtype      in formlayout.formtype%type,
                                fpscode          in formlayout.code%type,
                                fpsreportname    in formlayout.reportname%type,
                                fpndefaultlayout in formlayout.defaultlayout%type,
                                fpndescription   in formlayout_desc.description%type);
  procedure cfbcreate_generalemblemprice(fpngeneralemblemprice_id in out generalemblemprice.generalemblemprice_id%type,
                                         fpnproduct_id            in generalemblemprice.product_id%type,
                                         fpnsizedefinition_id     in generalemblemprice.sizedefinition_id%type,
                                         fpnprice                 in generalemblemprice.price%type,
                                         fpdtstartdate            in generalemblemprice.startdate%type,
                                         fpngeneralpricelist_id   in generalemblemprice.generalpricelist_id%type);
  procedure cfbcreate_generalpricelist(fpngeneralpricelist_id in out generalpricelist.generalpricelist_id%type,
                                       fpnpricetype           in generalpricelist.pricetype%type,
                                       fpscode                in generalpricelist.code%type,
                                       fpsdescription         in generalpricelist.description%type,
                                       fpsactive              in generalpricelist.active%type,
                                       fpsautopriceupdate     in generalpricelist.autopriceupdate%type,
                                       fpspriceindexcode      in generalpricelist.priceindexcode%type,
                                       fpncurrency_id         in generalpricelist.currency_id%type,
                                       fpnusage               in generalpricelist.usage%type,
                                       fpchainid              in generalpricelist.chain_id%type default null,
                                       fppriceupdatelockdate  in generalpricelist.priceupdatelockdate%type default null,
                                       fp_salesvolumeprice    in generalpricelist.salesvolumeprice%type default 'N',
                                       fp_defaultpricelist    in generalpricelist.defaultpricelist%type default 'N');
  procedure cfbcreate_generalrentprice(fpngeneralrentprice_id in out generalrentprice.generalrentprice_id%type,
                                       fpngeneralpricelist_id in generalrentprice.generalpricelist_id%type,
                                       fpnproduct_id          in generalrentprice.product_id%type,
                                       fpnsizedefinition_id   in generalrentprice.sizedefinition_id%type,
                                       fpnfinishingmethod_id  in generalrentprice.finishingmethod_id%type,
                                       fpnprice               in generalrentprice.price%type,
                                       fpdtstartdate          in generalrentprice.startdate%type,
                                       fpnchangesperweek      in generalrentprice.changesperweek%type,
                                       fpntypeofrent          in generalrentprice.typeofrent%type,
                                       fpnsizebillinggroup_id in generalrentprice.sizebillinggroup_id%type,
                                       fpnmaxinventory        in generalrentprice.maxinventory%type default 0);
  procedure cfbcreate_generalrepairprice(fpngeneralrepairprice_id in out generalrepairprice.generalrepairprice_id%type,
                                         fpngeneralpricelist_id   in generalrepairprice.generalpricelist_id%type,
                                         fpnrepairtype_id         in generalrepairprice.repairtype_id%type,
                                         fpnprice                 in generalrepairprice.price%type,
                                         fpdtstartdate            in generalrepairprice.startdate%type,
                                         fpnpriceperminute        in generalrepairprice.priceperminute%type);
  procedure cfbcreate_genreplacementprice(fpngeneralreplacementprice_id in out generalreplacementprice.generalreplacementprice_id%type,
                                          fpngeneralpricelist_id        in generalreplacementprice.generalpricelist_id%type,
                                          fpnproduct_id                 in generalreplacementprice.product_id%type,
                                          fpnsizedefinition_id          in generalreplacementprice.sizedefinition_id%type,
                                          fpnprice                      in generalreplacementprice.price%type,
                                          fpdtstartdate                 in generalreplacementprice.startdate%type,
                                          fpnsizebillinggroup_id        in generalreplacementprice.sizebillinggroup_id%type);
  procedure cfbcreate_generalsalesprice(fpngeneralsalesprice_id in out generalsalesprice.generalsalesprice_id%type,
                                        fpngeneralpricelist_id  in generalsalesprice.generalpricelist_id%type,
                                        fpnproduct_id           in generalsalesprice.product_id%type,
                                        fpnsizedefinition_id    in generalsalesprice.sizedefinition_id%type,
                                        fpnprice                in generalsalesprice.price%type,
                                        fpdtstartdate           in generalsalesprice.startdate%type,
                                        fpnvolumeprice          in generalsalesprice.volumeprice%type default 1,
                                        fpnsizebillinggroup_id  in generalsalesprice.sizebillinggroup_id%type);
  procedure cfbcreate_generalwashprice(fpngeneralwashprice_id in out generalwashprice.generalwashprice_id%type,
                                       fpngeneralpricelist_id in generalwashprice.generalpricelist_id%type,
                                       fpnproduct_id          in generalwashprice.product_id%type,
                                       fpnsizedefinition_id   in generalwashprice.sizedefinition_id%type,
                                       fpnfinishingmethod_id  in generalwashprice.finishingmethod_id%type,
                                       fpnprice               in generalwashprice.price%type,
                                       fpdtstartdate          in generalwashprice.startdate%type,
                                       fpnpricetype           in generalwashprice.pricetype%type);
  procedure cfbcreate_generalweightprice(fpngeneralweightprice_id in out generalweightprice.generalweightprice_id%type,
                                         fpngeneralpricelist_id   in generalweightprice.generalpricelist_id%type,
                                         fpnweighingcategory_id   in generalweightprice.weighingcategory_id%type,
                                         fpssoil                  in generalweightprice.soil%type,
                                         fpnprice                 in generalweightprice.price%type,
                                         fpdtstartdate            in generalweightprice.startdate%type);
  procedure cfbcreate_invoiceheader(fpninvoiceheader_id       in out invoiceheader.invoiceheader_id%type,
                                    fpdtinvoicedate           in invoiceheader.invoicedate%type,
                                    fpninvoicenumber          in invoiceheader.invoicenumber%type,
                                    fpndocumenttype           in invoiceheader.documenttype%type,
                                    fpninvoicebusinessunit_id in invoiceheader.invoicebusinessunit_id%type,
                                    fpnbilltocustomer_link_id in invoiceheader.billtocustomer_link_id%type,
                                    fpndeltocustomer_link_id  in invoiceheader.deltocustomer_link_id%type,
                                    fpnendweek                in invoiceheader.endweek%type,
                                    fpnstartweek              in invoiceheader.startweek%type,
                                    fpnendmonth               in invoiceheader.endmonth%type,
                                    fpnstartmonth             in invoiceheader.startmonth%type,
                                    fpscounty                 in invoiceheader.county%type,
                                    fpsstate                  in invoiceheader.state%type,
                                    fpscity                   in invoiceheader.city%type,
                                    fpszipcode                in invoiceheader.zipcode%type,
                                    fpsstreet2                in invoiceheader.street2%type,
                                    fpsstreet                 in invoiceheader.street%type,
                                    fpsdeltocustomername      in invoiceheader.deltocustomername%type,
                                    fpndeltocustomernumber    in invoiceheader.deltocustomernumber%type,
                                    fpsbilltocustomername     in invoiceheader.billtocustomername%type,
                                    fpnbilltocustomernumber   in invoiceheader.billtocustomernumber%type,
                                    fpnroutecontrol_id        in invoiceheader.routecontrol_id%type,
                                    fpnroute_id               in invoiceheader.route_id%type,
                                    fpscontactpersonphone     in invoiceheader.contactpersonphone%type,
                                    fpsemailstatus            in invoiceheader.emailstatus%type,
                                    fpsemailaddress           in invoiceheader.emailaddress%type,
                                    fpscontactpersonname      in invoiceheader.contactpersonname%type,
                                    fpnstopnumber             in invoiceheader.stopnumber%type,
                                    fpnstatus_id              in invoiceheader.status_id%type,
                                    fpnrealcollectiontype     in invoiceheader.realcollectiontype%type,
                                    fpnoriginalcollectiontype in invoiceheader.originalcollectiontype%type,
                                    fpninvoicetype            in invoiceheader.invoicetype%type,
                                    fpnadjustmentreason_id    in invoiceheader.adjustmentreason_id%type,
                                    fpsexported               in invoiceheader.exported%type,
                                    fpspurchaseorder          in invoiceheader.purchaseorder%type,
                                    fpsdeliverinstructions    in invoiceheader.deliverinstructions%type,
                                    fpsinvoicecomments        in invoiceheader.invoicecomments%type,
                                    fpntotalminusadjustment   in invoiceheader.totalminusadjustment%type,
                                    fpntotalplusadjustment    in invoiceheader.totalplusadjustment%type,
                                    fpncashcollected          in invoiceheader.cashcollected%type,
                                    fpnpaythisamount          in invoiceheader.paythisamount%type,
                                    fpnprebillamount          in invoiceheader.prebillamount%type,
                                    fpninvoicefrequency_id    in invoiceheader.invoicefrequency_id%type,
                                    fpncurrency_id            in invoiceheader.currency_id%type,
                                    fpnroutenumber            in invoiceheader.routenumber%type,
                                    fpnstartyear              in invoiceheader.startyear%type,
                                    fpnendyear                in invoiceheader.endyear%type,
                                    fpscontractcode           in invoiceheader.contractcode%type,
                                    fpsdepotcode              in invoiceheader.depotcode%type,
                                    fpdtstartdate             in invoiceheader.startdate%type,
                                    fpdtenddate               in invoiceheader.enddate%type,
                                    fpncreditsqueezeperc      in invoiceheader.creditsqueezeperc%type,
                                    fpsconvertedfromlegacy    in invoiceheader.convertedfromlegacy%type,
                                    fpntotalamontexclvat      in invoiceheader.totalamountexclvat%type,
                                    fpnclusterid              in invoiceheader.cluster_id%type,
                                    fpncreditsqueezeamount    in invoiceheader.creditsqueezeamount%type,
                                    fpnsplitupcode            in invoiceheader.splitupcode%type,
                                    fpnsplitupdesc            in invoiceheader.splitupdescription%type,
                                    fpnstop_id                in invoiceheader.stop_id%type,
                                    fpninvoiceyear            in invoiceheader.invoiceyear%type,
                                    fpninvoiceweek            in invoiceheader.invoiceweek%type,
                                    fpninvoicedaynumber       in invoiceheader.invoicedaynumber%type,
                                    fpsextraname1             in invoiceheader.extraname1%type,
                                    fpsextraname2             in invoiceheader.extraname2%type,
                                    fpnparentinvoiceheaderid  in invoiceheader.parentinvoiceheader_id%type,
                                    fpdtcontractstartdate     in invoiceheader.contractstartdate%type,
                                    fpdtcontractenddate       in invoiceheader.contractenddate%type,
                                    fpnpaymentdiscountdays    in invoiceheader.paymentdiscountdays%type,
                                    fpnnetpaymentdays         in invoiceheader.netpaymentdays%type,
                                    fpsdeltostreet            in invoiceheader.deltostreet%type,
                                    fpsdeltostreet2           in invoiceheader.deltostreet2%type,
                                    fpsdeltocounty            in invoiceheader.deltocounty%type,
                                    fpsdeltostate             in invoiceheader.deltostate%type,
                                    fpsdeltocity              in invoiceheader.deltocity%type,
                                    fpsdeltozipcode           in invoiceheader.deltozipcode%type,
                                    fpsstreet3                in invoiceheader.street3%type);
  procedure cfbcreate_invoiceheaderus(fpninvoiceheader_id in out invoiceheaderus.invoiceheader_id%type,
                                      fpntaxstates_id     in invoiceheaderus.taxstates_id%type,
                                      fpnstatestaxrate    in invoiceheaderus.statestaxrate%type,
                                      fpntaxcity_id       in invoiceheaderus.taxcity_id%type,
                                      fpncitytaxrate      in invoiceheaderus.citytaxrate%type,
                                      fpntaxcounty_id     in invoiceheaderus.taxcounty_id%type,
                                      fpncountytaxrate    in invoiceheaderus.countytaxrate%type);
  procedure cfbcreate_miscellaneouscharge(fpnmiscellaneouscharge_id in out miscellaneouscharge.miscellaneouscharge_id%type,
                                          fpninvoicebusinessunit_id in miscellaneouscharge.invoicebusinessunit_id%type,
                                          fpncustomer_link_id       in miscellaneouscharge.customer_link_id%type,
                                          fpdtcreationdate          in miscellaneouscharge.creationdate%type,
                                          fpsdescription            in miscellaneouscharge.description%type,
                                          fpnturnovergroup_id       in miscellaneouscharge.turnovergroup_id%type,
                                          fpninvoiceheader_id       in miscellaneouscharge.invoiceheader_id%type,
                                          fpnquantity               in miscellaneouscharge.quantity%type,
                                          fpnprice                  in miscellaneouscharge.price%type,
                                          fpndiscountpercentage     in miscellaneouscharge.discountpercentage%type,
                                          fpnamount                 in miscellaneouscharge.amount%type,
                                          fpnchargestatus           in miscellaneouscharge.chargestatus%type,
                                          fpntaxgroup_id            in miscellaneouscharge.taxgroup_id%type,
                                          fpncostcenterid           in miscellaneouscharge.costcenter_link_id%type);
  procedure cfbcreate_modification(fpnmodification_id        in out modification.modification_id%type,
                                   fpscode                   in modification.code%type,
                                   fpsstockwithstandardsize  in modification.stockwithstandardsize%type,
                                   fpslegacymodificationcode in modification.legacymodificationcode%type,
                                   fpsuseinwebapplication    in modification.useinwebapplication%type);
  procedure cfbcreate_modification_desc(fpnmodification_id in modification_desc.modification_id%type,
                                        fpsdescription     in modification_desc.description%type);
  procedure cfbcreate_placement(fpnplacement_id in out placement.placement_id%type,
                                fpscode         in placement.code%type);
  procedure cfbcreate_placement_desc(fpnplacement_id in placement_desc.placement_id%type,
                                     fpsdescription  in placement_desc.description%type);
  procedure cfbcreate_plpdistribpoint(fpnprodlistperdistribpoint_id in out productlistperdistribpoint.productlistperdistribpoint_id%type,
                                      fpndistributionpoint_id       in productlistperdistribpoint.distributionpoint_id%type,
                                      fpnproduct_id                 in productlistperdistribpoint.product_id%type,
                                      fpnsizedefinition_id          in productlistperdistribpoint.sizedefinition_id%type,
                                      fpnfinishingmethod_id         in productlistperdistribpoint.finishingmethod_id%type,
                                      fpncountsequence              in productlistperdistribpoint.countsequence%type,
                                      fpnorderingmethod             in productlistperdistribpoint.orderingmethod%type,
                                      fpnholidayusagefactor         in productlistperdistribpoint.holidayusagefactor%type,
                                      fpncontractperiod             in productlistperdistribpoint.contractperiod%type default 0,
                                      fpnprolongationperiod         in productlistperdistribpoint.prolongationperiod%type default 0,
                                      fpncanceladvanceperiod        in productlistperdistribpoint.canceladvanceperiod%type default 0,
                                      fpdeliverypercentage          in productlistperdistribpoint.deliverypercentage%type default null,
                                      fpbillingpercentage           in productlistperdistribpoint.billingpercentage%type default null);
  procedure cfbcreate_pricelistpercustomer(fpnpricelistpercustomer_id in out pricelistpercustomer.pricelistpercustomer_id%type,
                                           fpncustomer_id             in pricelistpercustomer.customer_id%type,
                                           fpnpricetype               in pricelistpercustomer.pricetype%type,
                                           fpngeneralpricelist_id     in pricelistpercustomer.generalpricelist_id%type,
                                           fpnpriority                in pricelistpercustomer.priority%type default null,
                                           fpdtdateactive             in pricelistpercustomer.dateactive%type,
                                           fpdtdateinactive           in pricelistpercustomer.dateinactive%type,
                                           fpspriceindexcode          in pricelistpercustomer.priceindexcode%type,
                                           fpdpriceupdatelockdate     in pricelistpercustomer.priceupdatelockdate%type,
                                           fpnotfound_prioritydefault in pricelistpercustomer.priority%type default null);
  procedure cfbcreate_product(fpnproduct_id                  in out product.product_id%type,
                              fpscode                        in product.code%type,
                              fpnpackingsequence             in product.packingsequence%type,
                              fpnpackingamount               in product.packingamount%type,
                              fpsactive                      in product.active%type,
                              fpsgarmentset                  in product.garmentset%type,
                              fpspack                        in product.pack%type,
                              fpsmodel                       in product.model%type,
                              fpsoccupancyrelated            in product.occupancyrelated%type,
                              fpsspecialsize                 in product.specialsize%type,
                              fpnvolumeunits                 in product.volumeunits%type,
                              fpntheoreticalweight           in product.theoreticalweight%type,
                              fpslegacyproductcode           in product.legacyproductcode%type,
                              fpnfabric_id                   in product.fabric_id%type,
                              fpncolor_id                    in product.color_id%type,
                              fpnsupplier_id                 in product.supplier_id%type,
                              fpnsizetype_id                 in product.sizetype_id%type,
                              fpnwashingprocess_id           in product.washingprocess_id%type,
                              fpnproductgroup_id             in product.productgroup_id%type,
                              fpnweighingcategory_id         in product.weighingcategory_id%type,
                              fpnparentproduct_id            in out product.parentproduct_id%type,
                              fpnregistrationunit_id         in product.registrationunit_id%type,
                              fpssoilcountmethod             in product.soilcountmethod%type,
                              fpsrecordpassivestock          in product.recordpassivestock%type,
                              fpspermitinvoiceadjust         in varchar2, --NOT USED ANYMORE!!
                              fpntypeofmerchandise           in product.typeofmerchandise%type,
                              fpnminimumturnaround           in product.minimumturnaround%type,
                              fpnautoreplacement             in product.autoreplacement%type,
                              fpsshortdescription            in product.shortdescription%type,
                              fpninvoicecolumn               in product.invoicecolumn%type,
                              fpnrentturnovergroup_id        in product.rentturnovergroup_id%type,
                              fpnwashturnovergroup_id        in product.washturnovergroup_id%type,
                              fpnreplacementturnovergroup_id in product.replacementturnovergroup_id%type,
                              fpnsalesturnovergroup_id       in product.salesturnovergroup_id%type,
                              fpnimage_id                    in product.image_id%type,
                              fpnmaxwashes                   in product.maxwashes%type,
                              fpsuniquepoolitem              in product.uniquepoolitem%type,
                              fpnputuptype                   in product.putuptype%type,
                              fpnexchangemethod              in product.exchangemethod%type,
                              fpneannumber                   in product.eannumber%type,
                              fpnfinishingcode_id            in product.finishingcode_id%type,
                              fpnfulfillmentgroup            in product.fulfillmentgroup%type,
                              fpsstoreactivestocklocation    in product.storeactivestocklocation%type,
                              fpsdefaultprovisiongroupid     in provisiongroup.provisiongroup_id%type,
                              fpsusegradecategorydefect      in product.usegradecategorydefect%type,
                              fpndefaultreturngrade_id       in product.defaultreturngrade_id%type,
                              fpsmountingproduct             in product.mountingproduct%type,
                              fpsshowonmountingorder         in product.showonmountingorder%type,
                              fpsshowondismountingorder      in product.showondismountingorder%type,
                              fpsshowonpicklistrsc           in product.showonpicklistrsc%type,
                              fpndefaultsalesgrade           in product.defaultsalesgrade_id%type,
                              fpndefaultmountinggradeid      in product.defaultmountinggrade_id%type,
                              fpspercentagefirstdelivery     in product.percentagefirstdelivery%type,
                              fpnlostturnovergroup           in product.lossturnovergroup_id%type,
                              fpnadvanceturnovergroup_id     in product.advanceturnovergroup_id%type,
                              fpncorrectionsturnovergroup_id in product.correctionsturnovergroup_id%type,
                              fpnwashcogturnovergroup_id     in product.washcogturnovergroup_id%type,
                              fpnpacktype                    in product.packtype%type,
                              fpntreatmentcheckscheme_id     in product.treatmentcheckscheme_id%type,
                              fpslotnumberrequired           in product.lotnumberrequired%type,
                              fpnorpackcontentsallowed       in product.orpackcontentsallowed%type,
                              fpndefaultstockroomid          in product.defaultstockroom_id%type default null,
                              fpsfixedstockroom              in product.fixedstockroom%type default 'N',
                              fpnproductrankingid            in product.productranking_id%type default null,
                              fpnloanturnovergroup_id        in product.loanturnovergroup_id%type default null,
                              fpsizebreakdown                in product.sizebreakdown%type default 'N',
                              fpdefaultresidualvalueschemeid in product.defaultresidualvaluescheme_id%type default null,
                              fpmisproductid                 in product.misproduct_id%type default null,
                              fpconfirmproductonpda          in product.confirmproductonpda%type default 1,
                              fptotalpackweight              in product.totalpackweight%type default null,
                              fppackvolumeunits              in product.packvolumeunits%type default null,
                              fpproductsortgroupid           in product.productsortgroup_id%type default null,
                              fprentnotretturnovergroupid    in product.rentnotretturnovergroup_id%type default null,
                              fpcustomgarmentcharge          in product.customgarmentcharge%type default 'N',
                              fpmmprotection                 in product.materialmaintenanceprotection%type default 0,
                              fpdeliverytobillrelationship   in product.deliverytobillrelationship%type default 'N',
                              fpremark                       in product.remark%type default null,
                              fpsalesonly                    in product.salesonly%type default 'N',
                              fpmrpcodeid                    in product.mrpcode_id%type default null,
                              fpmmpdefaultpercentage         in product.mmpdefaultpercentage%type default null,
                              fpallowoneofforderingonra      in product.allowoneofforderingonra%type default 'N');
  procedure cfbcreate_productwashingproc(fp_productid        in productwashingprocess.product_id%type,
                                         fp_washingprocessid productwashingprocess.washingprocess_id%type);
  procedure cfbcreate_prodfinishingmethod(fpnproductid         product.product_id%type,
                                          fpnfinishingmethodid finishingmethod.finishingmethod_id%type);
  procedure cfbcreate_productlistpercust(fpnproductlistpercustomer_id   in out productlistpercustomer.productlistpercustomer_id%type,
                                         fpnproduct_id                  in productlistpercustomer.product_id%type,
                                         fpdtdateactive                 in productlistpercustomer.dateactive%type,
                                         fpdtdateinactive               in productlistpercustomer.dateinactive%type,
                                         fpnfinishingmethod_id          in productlistpercustomer.finishingmethod_id%type,
                                         fpscodeuniquely                in productlistpercustomer.codeuniquely%type,
                                         fpnsoilweight                  in productlistpercustomer.soilweight%type,
                                         fpncustomer_id                 in productlistpercustomer.customer_id%type,
                                         fpsonsiteinventorycount        in productlistpercustomer.onsiteinventorycount%type,
                                         fpnsizedefinition_id           in productlistpercustomer.sizedefinition_id%type,
                                         fpnrentpricefrequency          in productlistpercustomer.rentpriceperfrequency%type,
                                         fpnchangesperweek              in productlistpercustomer.changesperweek%type,
                                         fpnpercentageafterdepreciation in productlistpercustomer.percentageafterdepreciation%type,
                                         fpnbillingmethod               in productlistpercustomer.billingmethod%type,
                                         fpnsoilcountmethod             in productlistpercustomer.soilcountmethod%type,
                                         fpnsrcmethod                   in productlistpercustomer.srcmethod%type,
                                         fpscleancount                  in productlistpercustomer.cleancount%type,
                                         fpnsrcpercentagesoilcount      in productlistpercustomer.srcpercentagesoilcount%type,
                                         fpnsrcpercentageinventory      in productlistpercustomer.srcpercentageinventory%type,
                                         fpnsrcquantity                 in productlistpercustomer.srcquantity%type,
                                         fpnsrcfrequency                in productlistpercustomer.srcfrequency%type,
                                         fpnchargeoveruse               in productlistpercustomer.chargeoveruse%type,
                                         fpschargestockroominventory    in productlistpercustomer.chargestockroominventory%type,
                                         fpnminimumturnaround           in productlistpercustomer.minimumturnaround%type,
                                         fpnminimumquantity             in productlistpercustomer.minimumquantity%type,
                                         fpnqtyfreeofcharge             in productlistpercustomer.qtyfreeofcharge%type,
                                         fpscustomcode                  in productlistpercustomer.customcode%type,
                                         fpscustomdescription           in productlistpercustomer.customdescription%type,
                                         fpncustombundlesize            in productlistpercustomer.custombundlesize%type,
                                         fpngaincompetitor_id           in productlistpercustomer.gaincompetitor_id%type,
                                         fpngainreason_id               in productlistpercustomer.gainreason_id%type,
                                         fpnlostreason_id               in productlistpercustomer.lostreason_id%type,
                                         fpnlostcompetitor_id           in productlistpercustomer.lostcompetitor_id%type,
                                         fpnresidualvaluescheme_id      in productlistpercustomer.residualvaluescheme_id%type,
                                         fpndelayedevenexchange         in productlistpercustomer.delayedevenexchange%type,
                                         fpninventorybillingtype        in productlistpercustomer.inventorybillingtype%type,
                                         fpnminimumfrequency            in productlistpercustomer.minimumfrequency%type,
                                         fpsdeliverreplacementqty       in productlistpercustomer.deliverreplacementqty%type,
                                         fpnemblemtemplate              in productlistpercustomer.emblemtemplate_id%type,
                                         fpnwashprocess                 in productlistpercustomer.washingprocess_id%type,
                                         fpsautomaticsales              in productlistpercustomer.automaticsales%type,
                                         fpscustomerrelated             in productlistpercustomer.customerrelated%type,
                                         fpsautoreplafterlifetime       in productlistpercustomer.autoreplafterlifetime%type,
                                         fpnchargerentinactiveseason    in productlistpercustomer.chargerentinactiveseason%type,
                                         fpnseasontypeid                in productlistpercustomer.seasontype_id%type,
                                         fpnchargewashespack            in productlistpercustomer.chargewashespack%type,
                                         fpsspecificputuptype           in productlistpercustomer.specificputuptype%type,
                                         fpnquantityreturned            in productlistpercustomer.quantityreturned%type,
                                         fpsstraightevenexchange        in productlistpercustomer.straightevenexchange%type,
                                         fpneannumber                   in productlistpercustomer.eannumber%type,
                                         fpnfinishingcode_id            in productlistpercustomer.finishingcode_id%type,
                                         fpnfreeqtyfrequency            in productlistpercustomer.freeqtyfrequency%type,
                                         fpnsalesemployee_id            in productlistpercustomer.salesemployee_id%type,
                                         fpsreturnstockallowed          in productlistpercustomer.returnstockallowed%type,
                                         fpsdeedeliveryscheme_id        in productlistpercustomer.deedeliveryscheme_id%type,
                                         fpsremark                      in productlistpercustomer.remark%type,
                                         fpslocation                    in productlistpercustomer.location%type,
                                         fpschargewashesonlyforcog      in productlistpercustomer.chargewashesonlyforcog%type,
                                         fpnpriceusage                  in productlistpercustomer.priceusage%type,
                                         fpnsrcchargerent               in productlistpercustomer.srcchargerent%type default 0,
                                         fpntreatmentcheckscheme_id     in productlistpercustomer.treatmentcheckscheme_id%type default null,
                                         fpndeliverylabellayout_id      in productlistpercustomer.deliverylabellayout_id%type default null,
                                         fpnsalesemployee2              in productlistpercustomer.salesemployee2_id%type default null,
                                         fpndefaultstockroomid          in productlistpercustomer.defaultstockroom_id%type default null,
                                         fpsfixedstockroom              in productlistpercustomer.fixedstockroom%type default 'N',
                                         fpnorderviaweb                 in productlistpercustomer.orderviaweb%type default 0,
                                         fpninternalcalcpercentagelog   in productlistpercustomer.internalcalcpercentagelog%type default null,
                                         fpninternalcalcpercentagecog   in productlistpercustomer.internalcalcpercentagecog%type default null,
                                         fpnchargeexcess                in productlistpercustomer.chargeexcess%type default 0,
                                         fpnbudgetusage                 in productlistpercustomer.budgetusage%type default 0,
                                         fpncustomerbudgetdefinitionid  in productlistpercustomer.customerbudgetdefinition_id%type default null,
                                         fpbdepositstockallowed         in productlistpercustomer.depositstockallowed%type default 'N',
                                         fpndepositstockchargepercent   in productlistpercustomer.depositstockchargepercentage%type default 0,
                     fpnbm1fixedwearers             in productlistpercustomer.bm1fixedwearers%type default 'N',
                                         fpnsterilisationrequired       in productlistpercustomer.sterilisationrequired%type default 'N',
                                         fpimagecare                    in productlistpercustomer.imagecare%type default 0,
                                         fpallowreturntostock           in productlistpercustomer.allowreturntostock%type default 0,
                                         fpseasonalrent                 in productlistpercustomer.seasonalrent%type default 0,
                                         fpautosoilvalue                in productlistpercustomer.autosoil%type default 0,
                                         fpautosoilpercentage           in productlistpercustomer.autosoilpercentage%type default 0,
                                         fpdefaultsupplierid            in productlistpercustomer.defaultsupplier_id%type default null,
                                         fpcontractpurchaseorder_id     in productlistpercustomer.contractpurchaseorder_id%type default null,
                                         fpbm1rentcpwmax                in productlistpercustomer.bm1rentcpwmax%type default 0,
                     fpndepositstocklocation    in productlistpercustomer.depositstocklocation%type default null);
  procedure cfbcreate_productsize(fpnproduct_id        in productsize.product_id%type,
                                  fpnsizedefinition_id in productsize.sizedefinition_id%type,
                                  fpsspecialsize       in productsize.specialsize%type,
                                  fpnpackingamount     in productsize.packingamount%type,
                                  fpntheoreticalweight in productsize.theoreticalweight%type,
                                  fpnprovisiongroupid  in productsize.provisiongroup_id%type,
                                  fpnmaxcartqty        in productsize.maxcartqty%type default 0,
                                  fpnstandardlength    in productsize.standardlength%type default 'N',
                                  fpsizebillinggroupid in productsize.sizebillinggroup_id%type default null);
  function getqualitygradeid(qualitygradecode qualitygrade.code%type)
    return qualitygrade.qualitygrade_id%type;
  procedure cfbcreate_ragreason(fpnragreason_id        in out ragreason.ragreason_id%type,
                                fpscode                in ragreason.code%type,
                                fpsactive              in ragreason.active%type,
                                fpschargeresidualvalue in ragreason.chargeresidualvalue%type);
  procedure cfbcreate_ragreason_desc(fpnragreason_id in ragreason_desc.ragreason_id%type,
                                     fpsdescription  in ragreason_desc.description%type);
  procedure cfbcreate_reasoncode(fpnreasoncode_id         in out reasoncode.reasoncode_id%type,
                                 fpscode                  in reasoncode.code%type,
                                 fpsinternetselectable    in reasoncode.internetselectable%type default 'N',
                                 fpsallowprepcharges      in reasoncode.allowprepcharges%type default 'Y',
                                 fpsgarmentreason         in reasoncode.garmentreason%type default 'Y',
                                 fpslinenreason           in reasoncode.linenreason%type default 'Y',
                                 fpsexporttohandheld      in reasoncode.exporttohandheld%type default 'N',
                                 fpncancelinvoice         in reasoncode.cancelinvoice%type default 0,
                                 fpsaffectsnextinvoice    in reasoncode.affectsnextinvoice%type default 'N',
                                 fpsaffectscurrentinvoice in reasoncode.affectscurrentinvoice%type default 'N',
                                 fpninvoiceadjustment     in reasoncode.invoiceadjustment%type default 1,
                                 fpsfirstissue            in reasoncode.firstissue%type default 'N',
                                 fpninventorytrigger      in reasoncode.inventorytrigger%type default 0,
                                 fpschargeresidualvalue   in reasoncode.chargeresidualvalue%type default 'Y',
                                 fpschargerestockingfee   in reasoncode.chargerestockingfee%type default 'N');
  procedure cfbcreate_reasoncode_desc(fpnreasoncode_id in reasoncode_desc.reasoncode_id%type,
                                      fpsdescription   in reasoncode_desc.description%type);
  procedure cfbcreate_rentalqtyadjustment(fpnrentalqtyadjustment_id in out rentalqtyadjustment.rentalqtyadjustment_id%type,
                                          fpnproductlistperdip_id   in rentalqtyadjustment.productlistperdistribpoint_id%type,
                                          fpsremark                 in rentalqtyadjustment.remark%type,
                                          fpnquantity               in rentalqtyadjustment.quantity%type,
                                          fpdtadjustmentdate        in rentalqtyadjustment.adjustmentdate%type,
                                          fpnreasoncode_id          in rentalqtyadjustment.reasoncode_id%type,
                                          fpndeliveryvariation_id   in rentalqtyadjustment.deliveryvariations_id%type,
                                          fpnsalesemployee_id       in rentalqtyadjustment.salesemployee_id%type default null,
                                          fpnsalesemployee2_id      in rentalqtyadjustment.salesemployee2_id%type default null);
  procedure cfbcreate_season(fpnseason_id     in out season.season_id%type,
                             fpnseasontype_id in season.seasontype_id%type,
                             fpscode          in season.code%type);
  procedure cfbcreate_seasontype(fpnseasontype_id in out seasontype.seasontype_id%type,
                                 fpscode          in season.code%type);
  procedure cfbcreate_standarddelivery(fpnstandarddelivery_id       in out standarddelivery.standarddelivery_id%type,
                                       fpnsequencenumber            in standarddelivery.sequencenumber%type,
                                       fpsdeliversterile            in standarddelivery.deliversterile%type,
                                       fpnplantdepartment_id        in standarddelivery.plantdepartment_id%type,
                                       fpscleanreturn               in standarddelivery.cleanreturn%type,
                                       fpntransportarticle_id       in standarddelivery.transportarticle_id%type,
                                       fpsgeneratezerolines         in standarddelivery.generatezerolines%type,
                                       fpnnumberoftransportarticles in standarddelivery.numberoftransportarticles%type,
                                       fpndistributionpoint_id      in standarddelivery.distributionpoint_id%type,
                                       fpdtlastpackingdate          in standarddelivery.lastpackingdate%type,
                                       fpscorrectshortages          in standarddelivery.correctshortages%type,
                                       fpscorrectoverdeliveries     in standarddelivery.correctoverdeliveries%type,
                                       fpstruckloadposition         in standarddelivery.truckloadposition%type);
  procedure cfbstorecreate_stddelamount(fpnstandarddeliveryline_id in standarddeliveryamount.standarddeliveryline_id%type,
                                        fpnday_id                  in standarddeliveryamount.day_id%type,
                                        fpnamount                  in standarddeliveryamount.amount%type);
  procedure cfbstorecreate_normstockamount(fpnplpd_id in normstockamount.productlistperdistribpoint_id%type,
                                           fpnday_id  in normstockamount.day_id%type,
                                           fpnamount  in normstockamount.amount%type);
  procedure cfbcreate_sizedefinition(fpnsizedefinition_id in out sizedefinition.sizedefinition_id%type,
                                     fpscode              in sizedefinition.code%type,
                                     fpsunfinishedlength  in sizedefinition.unfinishedlength%type,
                                     fpslegacysizecode    in sizedefinition.legacysizecode%type,
                                     fpswidth             in sizedefinition.width%type,
                                     fpslength            in sizedefinition.length%type,
                                     fpsusedforemblem     in sizedefinition.usedforemblem%type,
                                     fpsizebillinggroupid in sizedefinition.sizebillinggroup_id%type default null,
                                     fpsizegroupingcodeid in sizedefinition.sizegroupingcode_id%type default null);
  procedure cfbcreate_sizedefinition_desc(fpnsizedefinition_id in sizedefinition_desc.sizedefinition_id%type,
                                          fpsdescription       in sizedefinition_desc.description%type);
  procedure cfbcreate_sizespersizetype(fpnsizedefinitionid in sizedefinition.sizedefinition_id%type,
                                       fpnsizetypeid       in sizetype.sizetype_id%type);
  procedure cfbcreate_specialcharge(fpnspecialcharge_id       in out specialcharge.specialcharge_id%type,
                                    fpnfrequency              in specialcharge.frequency%type,
                                    fpsincludininvoiceminimum in specialcharge.includininvoiceminimum%type,
                                    fpdtstartdate             in specialcharge.startdate%type,
                                    fpnnewpercentage          in specialcharge.newpercentage%type,
                                    fpnoldpercentage          in specialcharge.oldpercentage%type,
                                    fpnnewamount              in specialcharge.newamount%type,
                                    fpnoldamount              in specialcharge.oldamount%type,
                                    fpsfixedamount            in specialcharge.fixedamount%type,
                                    fpscode                   in specialcharge.code%type,
                                    fpnturnovergroup_id       in turnovergroup.turnovergroup_id%type,
                                    fpnminamount              in specialcharge.minimumamount%type default null,
                                    fpnmaxamount              in specialcharge.maximumamount%type default null);
  procedure cfbcreate_specialcharge_desc(fpnspecialcharge_id in specialcharge_desc.specialcharge_id%type,
                                         fpsdescription      in specialcharge_desc.description%type);
  procedure cfbcreate_standarddeliveryline(fpnstandarddeliveryline_id    in out standarddeliveryline.standarddeliveryline_id%type,
                                           fpnstandarddelivery_id        in standarddeliveryline.standarddelivery_id%type,
                                           fpnprodlistperdistribpoint_id in standarddeliveryline.productlistperdistribpoint_id%type,
                                           fpslocation                   in standarddeliveryline.location%type,
                                           fpsremarkforpackinstructions  in standarddeliveryline.remarkforpackinginstructions%type,
                                           fpnseason_id                  in standarddeliveryline.season_id%type,
                                           fpnfixedrentquantity          in standarddeliveryline.fixedrentquantity%type,
                                           fpdtdateactive                in standarddeliveryline.dateactive%type,
                                           fpdtdateinactive              in standarddeliveryline.dateinactive%type,
                                           fpndeliveryscheme_id          in standarddeliveryline.deliveryscheme_id%type,
                                           fpnproductlistpercustomer_id  in standarddeliveryline.productlistpercustomer_id%type,
                                           fpdtrenewalstartdate          in standarddeliveryline.renewalstartdate%type,
                                           fpdtrenewalenddate            in standarddeliveryline.renewalenddate%type,
                                           fpnqtyfreeofcharge            in standarddeliveryline.qtyfreeofcharge%type,
                                           fpnfreeqtyfrequency           in standarddeliveryline.freeqtyfrequency%type default 0);
  procedure cfbcreate_systemuser(fpnsystemuser_id            in out systemuser.systemuser_id%type,
                                 fpnusergroup_id             in systemuser.usergroup_id%type,
                                 fpsusername                 in systemuser.username%type,
                                 fpspassword                 in systemuser.password%type default null,
                                 fpsfullname                 in systemuser.fullname%type default null,
                                 fpsactive                   in systemuser.active%type default 'N',
                                 fpssysadmin                 in systemuser.sysadmin%type default 'N',
                                 fpsremark                   in systemuser.remark%type default null,
                                 fpscontactmanagerfullrights in systemuser.contactmgrfullrights%type default 'N');
  procedure cfbcreate_transportarticle(fpntransportarticle_id     in out transportarticle.transportarticle_id%type,
                                       fpscode                    in transportarticle.code%type,
                                       fpsdefaulttransportarticle in transportarticle.defaulttransportarticle%type,
                                       fpsdescription             in transportarticle_desc.description%type default '-');
  procedure cfbcreate_treatmenttype(fptreatmenttypeid   out treatmenttype.treatmenttype_id%type,
                                    fptreatmenttypecode in treatmenttype.code%type);
  procedure cfbcreate_workorderlinemod(fpnworkorderline_id in workorderlinemodification.workorderline_id%type,
                                       fpnmodification_id  in workorderlinemodification.modification_id%type,
                                       fpnsequencenumber   in workorderlinemodification.sequencenumber%type);
  function getcleanroomcustomertype_id(cleanroomcustomertypecode cleanroomcustomertype.code%type)
    return cleanroomcustomertype.cleanroomcustomertype_id%type;
  function get_sizebillinggroup(fp_sizebillinggroupcode in sizebillinggroup.code%type,
                                fp_standard             in sizebillinggroup.standard%type)
  return sizebillinggroup.sizebillinggroup_id%type;
  --  procedure open_log;
--  procedure close_log;
end pack_import;
/
create or replace package body pack_import is
  procedure write_log(fpserr_msg varchar2, fpnpriority number default 1) is
  begin
    /* writes conversion logs into database.
    priority
    1 = Message
    2 = Warning
    3 = Error
    4 = Stack trace
    5 = Debug info  */
    abslogwrite.abslog_write(6, 'Import Legacy Data', null, abs(fpnpriority), fpserr_msg,
                             lvnsystemuserid);
  end write_log;
  procedure get_language is
  begin
    lvnlanguageid   := null;
    lvnlanguagecode := null;
    --get language id
    select l.language_id, l.code
    into   lvnlanguageid, lvnlanguagecode
    from   languages l
    where  l.conversionlanguage_yn = 'Y';
  exception
    when others then
      begin
        select l.language_id, l.code
        into   lvnlanguageid, lvnlanguagecode
        from   languages l
        where  l.translatedescription = 'Y';
      exception
        when others then
          begin
            select l.language_id, l.code
            into   lvnlanguageid, lvnlanguagecode
            from   languages l
            where  l.language_id = (select min(xl.language_id) from languages xl);
          exception
            when others then
              begin
                lvnlanguageid   := null;
                lvnlanguagecode := null;
                write_log('Conversion error no language set! Please set 1 languages.conversionlanguage_yn=Y',
                          3);
                raise lvnuserexception;
              end;
          end;
      end;
  end get_language;
  procedure cfbimportplantfixedinfo is
    reasoncodeid reasoncode.reasoncode_id%type;
  begin
    get_language;
    -- reasoncode '-'
    begin
      select reasoncode_id into reasoncodeid from reasoncode where code = '-';
    exception
      when no_data_found then
        begin
          pack_import.cfbcreate_reasoncode(reasoncodeid,
                                           --fpnreasoncode_id,
                                           '-',
                                           --fpscode,
                                           'N',
                                           --fpsinternetselectable,
                                           'Y',
                                           --fpsallowprepcharges,
                                           'Y',
                                           --fpsgarmentreason,
                                           'Y',
                                           --fpslinenreason,
                                           'N',
                                           --fpsexporttohandheld,
                                           0,
                                           --fpncancelinvoice,
                                           'N',
                                           --fpsaffectsnextinvoice,
                                           'N',
                                           --fpsaffectscurrentinvoice,
                                           0,
                                           --fpninvoiceadjustment,
                                           'N',
                                           --fpsfirstissue,
                                           0,
                                           --fpninventorytrigger,
                                           'Y',
                                           --fpschargeresidualvalue
                                           'N'
                                           --fpschargerestockingfee
                                           );
          pack_import.cfbcreate_reasoncode_desc(reasoncodeid,
                                                --fpnreasoncode_id,
                                                '-');
          --fpsdescription,
          pack_import.write_log('cfbimportplantfixedinfo: created default reasoncode -');
        exception
          when dup_val_on_index then
            null;
          when others then
            pack_import.write_log('cfbimportplantfixedinfo: fail to create default reasoncode ' ||
                                  substr(sqlerrm, 1, 512), 3);
        end;
    end;
    -- salesgroupjournal '-'
    begin
      select salesjournalgroup_id
      into   lvnsalesjournalgroupminusid
      from   salesjournalgroup
      where  code = '-';
    exception
      when no_data_found then
        begin
          insert into salesjournalgroup
            (salesjournalgroup_id, code, active, systemuser_id, timestamp)
          values
            (seq_salesjournalgroup.nextval, '-', 'Y', lvnsystemuserid, sysdate)
          returning salesjournalgroup_id into lvnsalesjournalgroupminusid;
          insert into salesjournalgroup_desc
            (salesjournalgroup_id, language_id, description, systemuser_id, timestamp)
          values
            (seq_salesjournalgroup.currval, lvnlanguageid, '-', lvnsystemuserid, sysdate);
          pack_import.write_log('cfbimportplantfixedinfo: created default salesjournalgroup -');
        exception
          when dup_val_on_index then
            null;
          when others then
            pack_import.write_log('cfbimportplantfixedinfo: fail to create default salesjournalgroup ' ||
                                  substr(sqlerrm, 1, 512), 3);
        end;
    end;
    begin
      --insert employee function id = 1
      insert into employeefunction
        (employeefunction_id, code, description, active, systemuser_id, timestamp)
      values
        (1, '-', '-', 'Y', pack_import.lvnsystemuserid, sysdate);
      --insert employee function auth
      insert into employeefunctionauth
        (employeefunctionauth_id, employeefunction_id, ordertype, authorizationlevel, systemuser_id,
         timestamp)
        select seq_employeefunctionauth.nextval, e.employeefunction_id, ot.ordertype, 2,
               pack_import.lvnsystemuserid, sysdate
        from   employeefunction e,
               (select rownum ordertype from user_tables where rownum between 1 and 3) ot;
    exception
      when dup_val_on_index then
        null;
    end;
    begin
      --insert district id = 1
      insert into district
        (district_id, code, description, systemuser_id, timestamp)
      values
        (1, '-', '-', pack_import.lvnsystemuserid, sysdate);
    exception
      when dup_val_on_index then
        null;
    end;
    commit;
  end cfbimportplantfixedinfo;
  procedure disable_i_constraints is
    /*******************************************************************************\
    Disables i-table constrains for the user that calls this procedure.
    \*******************************************************************************/
    cursor c1 is
      select s.table_name, s.constraint_name
      from   user_constraints s
      where  s.status = 'ENABLED'
      and    s.constraint_type <> 'P'
      and    substr(s.table_name, 1, 2) = 'I_'
      order  by s.constraint_type;
    sqlstatement varchar2(500);
  begin
    --disable constraints, loop 3 times because of dependencies
    for i in 1 .. 3 loop
      for x in c1 loop
        begin
          sqlstatement := 'ALTER TABLE ' || x.table_name || ' DISABLE CONSTRAINT ' ||
                          x.constraint_name;
          execute immediate sqlstatement;
        exception
          when others then
            if i >= 3 then
              pack_import.write_log('Error to disable: ' || x.constraint_name, 3);
            end if;
        end;
      end loop;
    end loop;
    pack_import.write_log('disable_i_constraints for ran succesfull.');
  exception
    when others then
      begin
        pack_import.write_log('disable_i_constraints error; ' || sqlstatement || '
      ' || substr(sqlerrm, 1, 200), 3);
        raise;
      end;
  end disable_i_constraints;
  procedure enable_i_constraints is
    /*******************************************************************************\
    Enables i-table constrains for the user that calls this procedure.
    \*******************************************************************************/
    cursor c1 is
      select s.table_name, s.constraint_name
      from   user_constraints s
      where  s.status = 'DISABLED'
      and    substr(s.table_name, 1, 2) = 'I_';
    sqlstatement varchar2(500);
  begin
    --enable constraints, loop 3 times because of dependencies
    for i in 1 .. 3 loop
      for x in c1 loop
        begin
          sqlstatement := 'ALTER TABLE ' || x.table_name || ' ENABLE CONSTRAINT ' ||
                          x.constraint_name;
          execute immediate sqlstatement;
        exception
          when others then
            if i < 3 then
              null;
            end if;
        end;
      end loop;
    end loop;
    pack_import.write_log('Enable_i_constraints ran succesfull.');
  exception
    when others then
      begin
        pack_import.write_log('ERROR during Enable_i_constraints error; ' || sqlstatement || '
      ' || substr(sqlerrm, 1, 200), 3);
        raise;
      end;
  end enable_i_constraints;
  procedure check_underuse is
    lv_underuse_count number;
  begin
    --check_underuse
    select count(1)
    into   lv_underuse_count
    from   systemsetting st
    where  st.name = 'UNDERUSEMETHOD'
    and    st.value = '4';
    if lv_underuse_count > 0 then
      begin
        execute immediate 'alter table I_PRODUCTLISTPERCUSTOMER disable constraint CHK_PLPC_BILLMETHOD2';
      end;
    end if;
  end check_underuse;
  procedure cfbdelete_itables is
    sqlstatement varchar2(500);
    cursor c1 is
      select s.table_name from user_tables s where substr(s.table_name, 1, 2) = 'I_';
  begin
    --open_log;
    disable_i_constraints;
    pack_import.write_log('Start delete i_tables....');
    for x in c1 loop
      begin
        sqlstatement := 'delete from ' || x.table_name;
        execute immediate sqlstatement;
        commit;
      end;
    end loop;
    commit;
    enable_i_constraints;
    pack_import.write_log('Delete i_tables ran succesfully.');
    --close_log;
  exception
    when others then
      begin
        pack_import.write_log('Error during delete_i_tables: ' || substr(sqlerrm, 1, 200), 3);
        --close_log;
      end;
  end cfbdelete_itables;
  procedure cfbcreate_activity(fpnactivityid   in out activity.activity_id%type,
                               fpsactivitycode in activity.code%type) is
  begin
    select a.activity_id into fpnactivityid from activity a where a.code = fpsactivitycode;
  exception
    when no_data_found then
      begin
        insert into activity
          (activity_id, code, active, legacyactivitycode, systemuser_id, timestamp)
        values
          (seq_activity.nextval, fpsactivitycode, 'Y', null, pack_import.lvnsystemuserid, sysdate)
        returning activity_id into fpnactivityid;
        insert into activity_desc
          (activity_id, language_id, description, systemuser_id, timestamp)
        values
          (fpnactivityid, pack_import.lvnlanguageid, fpsactivitycode, pack_import.lvnsystemuserid,
           sysdate);
      end;
  end cfbcreate_activity;
  procedure cfbget_create_budgetunit(fp_budgetunitid   in out budgetunit.budgetunit_id%type,
                                     fp_budgetunitcode in budgetunit.code%type,
                                     fp_budgetunitdesc in budgetunit_desc.description%type default null) is
  begin
    if fp_budgetunitcode is null then
      fp_budgetunitid := null;
    else
      select bu.budgetunit_id
      into   fp_budgetunitid
      from   budgetunit bu
      where  bu.code = fp_budgetunitcode;
    end if;
  exception
    when no_data_found then
      begin
        insert into budgetunit
          (budgetunit_id, code, systemuser_id, timestamp)
        values
          (seq_budgetunit.nextval, fp_budgetunitcode, lvnsystemuserid, sysdate)
        returning budgetunit_id into fp_budgetunitid;
        insert into budgetunit_desc
          (budgetunit_id, language_id, description, systemuser_id, timestamp)
        values
          (fp_budgetunitid, lvnlanguageid, coalesce(fp_budgetunitdesc, fp_budgetunitcode, '-'),
           lvnsystemuserid, sysdate);
      end;
  end cfbget_create_budgetunit;
  procedure cfbcreate_color(fpncolor_id      in out color.color_id%type,
                            fpscode          in color.code%type,
                            fpsralcode       in color.ralcode%type,
                            fpsusedforemblem in color.usedforemblem%type) is
  begin
    insert into color
      (color_id, code, ralcode, systemuser_id, timestamp, usedforemblem)
    values
      (seq_color.nextval, fpscode, fpsralcode, lvnsystemuserid, sysdate, fpsusedforemblem);
    select seq_color.currval into fpncolor_id from dual;
  end cfbcreate_color;
  procedure cfbcreate_color_desc(fpncolor_id    in color_desc.color_id%type,
                                 fpsdescription in color_desc.description%type) is
  begin
    insert into color_desc
      (color_id, language_id, description, systemuser_id, timestamp)
    values
      (fpncolor_id, lvnlanguageid, nvl(fpsdescription, '-'), lvnsystemuserid, sysdate);
  end cfbcreate_color_desc;
  procedure cfbcreate_contact(fpncontact_id         in out contact.contact_id%type,
                              fpncustomer_link_id   in contact.customer_link_id%type,
                              fpndepartment_link_id in contact.department_link_id%type,
                              fpnbusinessunit_id    in contact.businessunit_id%type,
                              fpncontactcategory_id in contact.contactcategory_id%type,
                              fpncreatedbyuser_id   in contact.createdbyuser_id%type,
                              fpnfollowupbyuser_id  in contact.followupbyuser_id%type,
                              fpdtnewdate           in contact.newdate%type,
                              fpncallnumber         in contact.callnumber%type,
                              fpdtfollowupdate      in contact.followupdate%type,
                              fpdtinprogressdate    in contact.inprogressdate%type,
                              fpdtclosedate         in contact.closedate%type,
                              fpnstatus             in contact.status%type,
                              fpscontactpersonname  in contact.contactpersonname%type,
                              fpncontactperson_id   in contact.contactperson_id%type,
                              fpsfollowupbyusername in contact.followupbyusername%type,
                              fpscreatedbyusername  in contact.createdbyusername%type,
                              fpscontactnotes       in contact.contactnotes%type,
                              fpsfollowupnotes      in contact.followupnotes%type,
                              fpsattachment         in contact.attachment%type,
                              fpsshowonroutelist    in contact.showonroutelist%type,
                              fp_inprogressbyuserid in contact.inprogressbyuser_id%type,
                              fp_inprogressbyusernm in varchar2,
                              fp_closedbyuserid     in contact.closedbyuser_id%type,
                              fp_closedbyusername   in varchar2,
                              fp_priority           in contact.priority%type,
                              fp_contactcause_code  in varchar2,
                              fp_completeddate      in contact.completeddate%type,
                              fp_completedbyuserid  in contact.completedbyuser_id%type,
                              fp_completedbyuserame in varchar2,
                              fp_reviewdate         in contact.reviewdate%type,
                              fp_reviewedbyuserid   in contact.reviewedbyuser_id%type,
                              fp_reviewedbyusername in varchar2,
                              fp_blockdepartonstop  in contact.blockdepartureonstop%type,
                              fp_followupbyroute    in contact.followupbyroute%type,
                              fp_originalcallnumber in number,
                              fp_checkbefroutestart in contact.checkbeforeroutestart%type) is
    lv_contactcauseid contactcause.contactcause_id%type;
    lv_originalcallid contact.originalcontact_id%type;
    lv_stopid         contact.stop_id%type;
    procedure get_contactcause is
    begin
      if fp_contactcause_code is null then
        begin
          lv_contactcauseid := null;
        end;
      else
        begin
          select cc.contactcause_id
          into   lv_contactcauseid
          from   contactcause cc
          where  cc.code = fp_contactcause_code;
        exception
          when no_data_found then
            begin
              insert into contactcause
                (contactcause_id, code, defaultcause, systemuser_id, timestamp)
              values
                (seq_contactcause.nextval, fp_contactcause_code, 'N', lvnsystemuserid, sysdate)
              returning contactcause_id into lv_contactcauseid;
              insert into contactcause_desc
                (contactcause_id, language_id, description, systemuser_id, timestamp)
              values
                (lv_contactcauseid, lvnlanguageid, fp_contactcause_code, lvnsystemuserid, sysdate);
            end;
        end;
      end if;
    end get_contactcause;
  begin
    --get_contactcause
    get_contactcause;
    --get originalcontact_id
    if fp_originalcallnumber is null then
      begin
        lv_originalcallid := null;
      end;
    else
      begin
        select max(ct.contact_id)
        into   lv_originalcallid
        from   contact ct
        where  ct.callnumber = fp_originalcallnumber;
      end;
    end if;
    if fp_followupbyroute = 'Y' then
      begin
        select min(st.stop_id)
        into   lv_stopid
        from   stop st
        where  st.customer_link_id = fpncustomer_link_id;
      end;
    else
      begin
        lv_stopid := null;
      end;
    end if;
    --insert into contact
    insert into contact
      (contact_id, customer_link_id, department_link_id, businessunit_id, contactcategory_id,
       createdbyuser_id, followupbyuser_id, newdate, callnumber, followupdate, inprogressdate,
       closedate, status, contactpersonname, contactperson_id, followupbyusername, createdbyusername,
       contactnotes, followupnotes, attachment, systemuser_id, timestamp, showonroutelist,
       inprogressbyuser_id, inprogressbyusername, closedbyuser_id, closedbyusername, priority,
       contactcause_id, completeddate, completedbyusername, completedbyuser_id, reviewdate,
       reviewedbyusername, reviewedbyuser_id, blockdepartureonstop, followupbyroute,
       originalcontact_id, checkbeforeroutestart, stop_id)
    values
      (seq_contact.nextval, fpncustomer_link_id, fpndepartment_link_id, fpnbusinessunit_id,
       fpncontactcategory_id, fpncreatedbyuser_id, fpnfollowupbyuser_id, fpdtnewdate, fpncallnumber,
       fpdtfollowupdate, fpdtinprogressdate, fpdtclosedate, fpnstatus, fpscontactpersonname,
       fpncontactperson_id, fpsfollowupbyusername, fpscreatedbyusername, fpscontactnotes,
       fpsfollowupnotes, fpsattachment, lvnsystemuserid, sysdate, fpsshowonroutelist,
       fp_inprogressbyuserid, fp_inprogressbyusernm, fp_closedbyuserid, fp_closedbyusername,
       nvl(fp_priority, 1), lv_contactcauseid,
       nvl(fp_completeddate, to_date('31-12-2099', 'DD-MM-YYYY')), fp_completedbyuserame,
       fp_completedbyuserid, nvl(fp_reviewdate, to_date('31-12-2099', 'DD-MM-YYYY')),
       fp_reviewedbyusername, fp_reviewedbyuserid, nvl(fp_blockdepartonstop, 0),
       nvl(fp_followupbyroute, 'N'), lv_originalcallid, nvl(fp_checkbefroutestart, 0), lv_stopid)
    returning contact_id into fpncontact_id;
  end cfbcreate_contact;
  procedure cfbcreate_contactcategory(fpncontactcategory_id     in out contactcategory.contactcategory_id%type,
                                      fpscode                   in contactcategory.code%type,
                                      fpsdefaultcontactcategory in contactcategory.defaultcontactcategory%type) is
  begin
    insert into contactcategory
      (contactcategory_id, code, defaultcontactcategory, systemuser_id, timestamp)
    values
      (seq_contactcategory.nextval, fpscode, fpsdefaultcontactcategory, lvnsystemuserid, sysdate);
    select seq_contactcategory.currval into fpncontactcategory_id from dual;
  end cfbcreate_contactcategory;
  procedure cfbcreate_contactcategory_desc(fpncontactcategory_id in contactcategory_desc.contactcategory_id%type,
                                           fpsdescription        in contactcategory_desc.description%type) is
  begin
    insert into contactcategory_desc
      (contactcategory_id, language_id, description, systemuser_id, timestamp)
    values
      (fpncontactcategory_id, lvnlanguageid, nvl(fpsdescription, '-'), lvnsystemuserid, sysdate);
  end cfbcreate_contactcategory_desc;
  procedure cfbcreate_costcenter(fpncostcenter_id     in out costcenter.costcenter_id%type,
                                 fpscode              in costcenter.code%type,
                                 fpsdescription       in costcenter.description%type,
                                 fpncustomer_id       in costcenter.customer_id%type,
                                 fpninvoiceaddress_id in costcenter.invoiceaddress_id%type,
                                 fpncontactperson_id  in costcenter.contactperson_id%type,
                                 fp_ponumber          in costcenter.ponumber%type default null,
                                 fp_requisitionnumber in costcenter.requisitionnumber%type default null,
                                 fp_accountingstring  in costcenter.accountingstring%type default null,
                                 fp_eannumber         in costcenter.eannumber%type default null,
                                 fp_exportedi         in costcenter.exportedi%type default null,
                                 fp_costcentergroupid in costcenter.costcentergroup_id%type default null) is
  begin
    select cc.costcenter_id
    into   fpncostcenter_id
    from   costcenter cc
    where  cc.code = fpscode
    and    cc.customer_id = fpncustomer_id;
    update costcenter cc
    set    cc.description = fpsdescription, cc.invoiceaddress_id = fpninvoiceaddress_id,
           cc.contactperson_id = fpncontactperson_id, cc.ponumber = fp_ponumber,
           cc.requisitionnumber = fp_requisitionnumber, cc.accountingstring = fp_accountingstring,
           cc.eannumber = fp_eannumber, cc.exportedi = nvl(fp_exportedi, cc.exportedi),
           cc.costcentergroup_id = nvl(fp_costcentergroupid, cc.costcentergroup_id)
    where  cc.costcenter_id = fpncostcenter_id;
    update costcenter_link cl
    set    cl.description = fpsdescription
    where  cl.costcenter_link_id = fpncostcenter_id;
  exception
    when no_data_found then
      begin
        insert into costcenter
          (costcenter_id, code, description, customer_id, systemuser_id, timestamp,
           invoiceaddress_id, contactperson_id, ponumber, requisitionnumber, accountingstring,
           eannumber, exportedi, costcentergroup_id)
        values
          (seq_costcenter.nextval, fpscode, fpsdescription, fpncustomer_id, lvnsystemuserid,
           sysdate, fpninvoiceaddress_id, fpncontactperson_id, fp_ponumber, fp_requisitionnumber,
           fp_accountingstring, fp_eannumber, nvl(fp_exportedi, 0), fp_costcentergroupid)
        returning costcenter_id into fpncostcenter_id;
        insert into costcenter_link
          (costcenter_link_id, costcenter_id, code, description, customer_link_id, systemuser_id,
           timestamp)
        values
          (fpncostcenter_id, fpncostcenter_id, fpscode, fpsdescription, fpncustomer_id,
           lvnsystemuserid, sysdate);
      end;
  end cfbcreate_costcenter;
  procedure cfbcreate_customer(fpncustomer_id                in out customer.customer_id%type,
                               fpncustomernumber             in customer.customernumber%type,
                               fpsname                       in customer.name%type,
                               fpsphoneno                    in customer.phoneno%type,
                               fpslegalname                  in customer.legalname%type,
                               fpsfaxno                      in customer.faxno%type,
                               fpsemail                      in customer.email%type,
                               fpdtdateactive                in customer.dateactive%type,
                               fpdtdateinactive              in customer.dateinactive%type,
                               fpsactive                     in customer.active%type,
                               fpsremark                     in customer.remark%type,
                               fpssiccode                    in customer.siccode%type,
                               fpssearchname                 in customer.searchname%type,
                               fpslegacycustomernumber       in customer.legacycustomernumber%type,
                               fpsoccupancyfromstockcount    in customer.occupancyfromstockcount%type,
                               fpndebtor_id                  in out customer.debtor_id%type,
                               fpndefaultbusinessunit_id     in customer.defaultbusinessunit_id%type,
                               fpnmasteraccount_id           in out customer.masteraccount_id%type,
                               fpnmasteraccount              in customer.masteraccount%type,
                               fpnmarketsegment_id           in customer.marketsegment_id%type,
                               fpnsalesarea_id               in customer.salesarea_id%type,
                               fpncurrency_id                in customer.currency_id%type,
                               fpncountry_id                 in customer.country_id%type,
                               fpnvisitaddress_id            in customer.visitaddress_id%type,
                               fpnmailaddress_id             in customer.mailaddress_id%type,
                               fpncommunicationmethod_id     in customer.communicationmethod_id%type,
                               fpssoilcount                  in customer.soilcount%type,
                               fpndeliverynotelayout_id      in customer.deliverynotelayout_id%type,
                               fpnconsignmentnotelayout_id   in customer.consignmentnotelayout_id%type,
                               fpsinternetordering           in customer.internetordering%type,
                               fpsimportoccupancyhht         in customer.importoccupancyhht%type,
                               fpnreturnlinen                in customer.returnlinen%type,
                               fpnreturngarments             in customer.returngarments%type,
                               fpscodegarmentsuniquely       in customer.codegarmentsuniquely%type,
                               fpndaysnoprepcharge           in customer.daysnoprepcharge%type,
                               fpschargerepairs              in customer.chargerepairs%type,
                               fpngarmentrentspecification   in customer.garmentrentspecification%type,
                               fpsswingsuitdelivery          in customer.swingsuitdelivery%type,
                               fpsusesgarmentdispenser       in customer.usesgarmentdispenser%type,
                               fpslockermanagement           in customer.lockermanagement%type,
                               fpnfirstdaysgrade_id          in customer.firstdaysgrade_id%type,
                               fpndaysspecialgrade           in customer.daysspecialgrade%type,
                               fpnfirstissuegrade_id         in customer.firstissuegrade_id%type,
                               fpnqualitygrade_id            in customer.qualitygrade_id%type,
                               fpnserviceteam_id             in customer.serviceteam_id%type,
                               fpnstandardqtydefinition      in customer.standardqtydefinition%type,
                               fpscorrectshortages           in customer.correctshortages%type,
                               fpscorrectoverdeliveries      in customer.correctoverdeliveries%type,
                               fpninvoicelayout_id           in customer.invoicelayout_id%type,
                               fpninvoicecopies              in customer.invoicecopies%type,
                               fpnminimuminvoiceamount       in customer.minimuminvoiceamount%type,
                               fpstaxable                    in customer.taxable%type,
                               fpnpaymentmethod              in customer.paymentmethod%type,
                               fpnpaymenttype                in customer.paymenttype%type,
                               fpnstates_id                  in customer.states_id%type,
                               fpncountytaxauthority_id      in customer.countytaxauthority_id%type,
                               fpncitytaxauthority_id        in customer.citytaxauthority_id%type,
                               fpbisownmasteraccount         in varchar2,
                               fpbisowndebtor                in varchar2,
                               fpsmarkinggarment             in customer.customermarkinggarment%type,
                               fpninvoicefrequency_id        in customer.invoicefrequency_id%type,
                               fpncodelabellayout_id         in customer.codelabellayout_id%type,
                               fpnnamelabellayout_id         in customer.namelabellayout_id%type,
                               fpsallowprepchargepertemplate in customer.allowprepchargepertemplate%type,
                               fpnemblemspecification        in customer.emblemspecification%type,
                               fpnallownegativestockcount    in customer.allownegativestockcount%type,
                               fpnoutscansort                in customer.outscansort%type,
                               fpschargewashfirstissue       in customer.chargewashfirstissue%type,
                               fpsallowautomaticsales        in customer.allowautomaticsales%type,
                               fpncustomerrelated            in customer.customerrelated%type,
                               fpschargeresidualvalue        in customer.chargeresidualvalue%type,
                               fpnrentperiod                 in customer.rentperiod%type,
                               fpnsplitinvoices              in customer.splitinvoices%type,
                               fpsvatnumber                  in customer.vatnumber%type,
                               fpnchain_id                   in customer.chain_id%type,
                               fpngarmentinsurance           in customer.garmentinsurance%type,
                               fpninvoiceaddress_id          in customer.invoiceaddress_id%type,
                               fpnilnnumber                  in customer.ilnnumber%type,
                               fpsusesbundles                in customer.usesbundles%type,
                               fpsextraname1                 in customer.extraname1%type,
                               fpsextraname2                 in customer.extraname2%type,
                               fpnscansondeliverynote        in customer.scansondeliverynote%type,
                               fpnassociationtype            in customer.associationtype%type default 0,
                               fpsdirectinvdeliveries        in customer.directinvdeliveries%type,
                               fpsdirectinvcleanweights      in customer.directinvcleanweights%type,
                               fpsdirectinvsoilweights       in customer.directinvsoilweights%type,
                               fpndirectinvminimumamount     in customer.directinvminimumamount%type,
                               fpsusecoverpage               in customer.usecoverpage%type,
                               fpnsignaturerequired          in customer.signaturerequired%type,
                               fpnnationalaccount_id         in customer.nationalaccount_id%type,
                               fpncocnumber                  in customer.cocnumber%type,
                               fnpnnumber                    in customer.pnnumber%type,
                               fpnserviceemployee_id         in customer.serviceemployee_id%type,
                               fpncommoncustomer_id          in customer.commoncustomer_id%type,
                               fpbbonusagreement             in customer.bonusagreement%type,
                               fpnacquisioncode_id           in customer.acquisioncode_id%type,
                               fpncustomerranking_id         in customer.customerranking_id%type,
                               fpntdccode                    in customer.tdccode%type,
                               fpschargelosscharge           in customer.chargelosscharge%type,
                               fpsedimethod                  in customer.edimethod%type,
                               fpstaxexemptcode              in customer.taxexemptcode%type,
                               fpsinheritmapricelist         in customer.inheritmapricelist%type,
                               fpsrestrictonmaproducts       in customer.restrictonmaproducts%type,
                               fpnsalesemployee1             in customer.salesemployee1_id%type default null,
                               fpnsalesemployee2             in customer.salesemployee2_id%type default null,
                               fpssplitinvoicesperactivity   in customer.splitinvoicesperactivity%type default 'N',
                               fpnchargerepaircog            in customer.chargerepaircog%type default 0,
                               fpninternalbu                 in customer.internalbusinessunit_id%type default null,
                               fpndefaultinvbu               in customer.defaultinvoicebusinessunit_id%type default null,
                               fpbinformpriceupdate          in customer.informpriceupdate %type default 'N',
                               fpbdirectinvallservices       in customer.directinvallservices%type default 'N',
                               fpbdirectinvsalesnotes        in customer.directinvsalesnotes%type default 'N',
                               fpbdepositstockallowed        in customer.depositstockallowed%type default 'N',
                               fpnalternatesorting           in customer.alternatesorting%type default 'N',
                               fpninternalcalcpercentagelog  in customer.internalcalcpercentagelog%type default null,
                               fpninternalcalcpercentagecog  in customer.internalcalcpercentagecog%type default null,
                               fpnmaincustomertype           in customer.maincustomertype%type default 1,
                               fpnlanguageid                 in customer.language_id%type default null,
                               fpnlinenreducefactor          in customer.linenreducefactor%type default 0,
                               fpnusecontractcoefficient     in customer.usecontractcoefficient%type default 'N',
                               fpncontractcoefficient        in customer.contractcoefficient%type default 0,
                               fpnreturnsamecontainer        in customer.returnsamecontainer%type default 'N',
                               fpnownbatch                   in customer.ownbatch%type default 'N',
                               fpninvoicecurrencyid          in customer.invoicecurrency_id%type default null,
                               fpcustomgarmentcharge         in customer.customgarmentcharge%type default 'N',
                               fp_useprodsizesurchargpricing in customer.useprodsizesurchargepricing%type default 'N',
                               fpautosoilpercentage          in customer.autosoilpercentage%type default 0,
                               fptaxexemptcertificatedoc     in customer.taxexemptcertificatedocument%type default null,
                               fpchargerestockingfee         in customer.chargerestockingfee%type default 'N',
                               fpmasteraccountrelation       in customer.masteraccountrelation%type default 0,
                               fpseasonautoflagallowed       in customer.seasonautoflagallowed%type default 'N',
                               fppasserbycustomer            in customer.passerbycustomer%type default 'N',
                               fpfirstservicedate            in customer.firstservicedate%type default null) is
    lv_suppressprintdelnotebatch customer.suppressprintdelnotebatch%type;
    lv_suppressprintdelnote      customer.suppressprintdelnote%type;
    lv_associationtype           customer.associationtype%type;
    lv_masteraccountrelation     customer.masteraccountrelation%type;
  begin
    select seq_customer.nextval into fpncustomer_id from dual;
    if fpbisownmasteraccount = 'Y' then
      fpnmasteraccount_id := fpncustomer_id;
    end if;
    if fpbisowndebtor = 'Y' then
      fpndebtor_id := fpncustomer_id;
    end if;
    --get value for suppressprintdelnotebatch from systemsetting
    select max(st.value)
    into   lv_suppressprintdelnotebatch
    from   systemsetting st
    join   businessunit bu
    on     bu.plant_id = st.plant_id
    where  st.name = 'SUPPRESSPRINTDELNOTEBATCH'
    and    bu.businessunit_id = fpndefaultbusinessunit_id;
    --get value for suppressprintdelnote from systemsetting
    select max(st.value)
    into   lv_suppressprintdelnote
    from   systemsetting st
    join   businessunit bu
    on     bu.plant_id = st.plant_id
    where  st.name = 'SUPPRESSPRINTDELNOTE'
    and    bu.businessunit_id = fpndefaultbusinessunit_id;
    if nvl(fpnmasteraccount, 0) <> 2 then
      lv_associationtype := 0;
    else
      lv_associationtype := fpnassociationtype;
    end if;
    if nvl(fpnmasteraccount, 0) <> 3 then
      lv_masteraccountrelation := 0;
    else
      lv_masteraccountrelation := fpmasteraccountrelation;
    end if;
    --insert new customer
    insert into customer
      (customer_id, customernumber, name, phoneno, legalname, faxno, email, dateactive,
       dateinactive, active, remark, siccode, searchname, legacycustomernumber,
       occupancyfromstockcount, debtor_id, defaultbusinessunit_id, masteraccount_id,
       marketsegment_id, salesarea_id, currency_id, country_id, language_id, visitaddress_id,
       mailaddress_id, systemuser_id, communicationmethod_id, timestamp, masteraccount, soilcount,
       deliverynotelayout_id, consignmentnotelayout_id, internetordering, importoccupancyhht,
       returnlinen, returngarments, codegarmentsuniquely, daysnoprepcharge, chargerepairs,
       garmentrentspecification, swingsuitdelivery, usesgarmentdispenser, lockermanagement,
       firstdaysgrade_id, daysspecialgrade, firstissuegrade_id, qualitygrade_id, serviceteam_id,
       standardqtydefinition, correctshortages, correctoverdeliveries, invoicelayout_id,
       invoicecopies, minimuminvoiceamount, taxable, paymentmethod, paymenttype, states_id,
       countytaxauthority_id, citytaxauthority_id, customermarkinggarment, invoicefrequency_id,
       codelabellayout_id, namelabellayout_id, allowprepchargepertemplate, emblemspecification,
       allownegativestockcount, outscansort, chargewashfirstissue, allowautomaticsales,
       customerrelated, chargeresidualvalue, rentperiod, splitinvoices, vatnumber, chain_id,
       garmentinsurance, invoiceaddress_id, ilnnumber, usesbundles, extraname1, extraname2,
       scansondeliverynote, associationtype, directinvdeliveries, directinvcleanweights,
       directinvsoilweights, directinvminimumamount, usecoverpage, bulkpacking, ownedcontainer,
       edimethod, insurancepricetype, delnoteforbulkputupitems, passerbycustomer, signaturerequired,
       nationalaccount_id, cocnumber, pnnumber, serviceemployee_id, commoncustomer_id,
       bonusagreement, acquisioncode_id, customerranking_id, tdccode, chargelosscharge,
       sendinvoiceto, taxexemptcode, inheritmapricelist, restrictonmaproducts, salesemployee1_id,
       salesemployee2_id, splitinvoicesperactivity, chargerepaircog, defaultinvoicebusinessunit_id,
       internalbusinessunit_id, informpriceupdate, directinvallservices, directinvsalesnotes,
       depositstockallowed, alternatesorting, internalcalcpercentagelog, internalcalcpercentagecog,
       maincustomertype, linenreducefactor, usecontractcoefficient, contractcoefficient,
       returnsamecontainer, ownbatch, invoicecurrency_id, usespecificinvoicecurrency,
       customgarmentcharge, useprodsizesurchargepricing, autosoilpercentage,
       suppressprintdelnotebatch, suppressprintdelnote, taxexemptcertificatedocument,
       chargerestockingfee, createdbysystemuser_id, createdtimestamp, masteraccountrelation,seasonautoflagallowed,
       firstservicedate)
    values
      (fpncustomer_id, fpncustomernumber, fpsname, fpsphoneno, fpslegalname, fpsfaxno, fpsemail,
       fpdtdateactive, fpdtdateinactive, fpsactive, fpsremark, fpssiccode, fpssearchname,
       fpslegacycustomernumber, fpsoccupancyfromstockcount, fpndebtor_id, fpndefaultbusinessunit_id,
       fpnmasteraccount_id, fpnmarketsegment_id, fpnsalesarea_id, fpncurrency_id, fpncountry_id,
       nvl(fpnlanguageid, lvnlanguageid), fpnvisitaddress_id, fpnmailaddress_id, lvnsystemuserid,
       fpncommunicationmethod_id, sysdate, fpnmasteraccount, fpssoilcount, fpndeliverynotelayout_id,
       fpnconsignmentnotelayout_id, fpsinternetordering, fpsimportoccupancyhht, fpnreturnlinen,
       fpnreturngarments, fpscodegarmentsuniquely, fpndaysnoprepcharge, fpschargerepairs,
       fpngarmentrentspecification, fpsswingsuitdelivery, fpsusesgarmentdispenser,
       fpslockermanagement, fpnfirstdaysgrade_id, fpndaysspecialgrade, fpnfirstissuegrade_id,
       fpnqualitygrade_id, fpnserviceteam_id, fpnstandardqtydefinition, fpscorrectshortages,
       fpscorrectoverdeliveries, fpninvoicelayout_id, fpninvoicecopies, fpnminimuminvoiceamount,
       fpstaxable, fpnpaymentmethod, fpnpaymenttype, fpnstates_id, fpncountytaxauthority_id,
       fpncitytaxauthority_id, fpsmarkinggarment, fpninvoicefrequency_id, fpncodelabellayout_id,
       fpnnamelabellayout_id, fpsallowprepchargepertemplate, fpnemblemspecification,
       fpnallownegativestockcount, fpnoutscansort, fpschargewashfirstissue, fpsallowautomaticsales,
       fpncustomerrelated, nvl(fpschargeresidualvalue, 'N'), fpnrentperiod, fpnsplitinvoices,
       fpsvatnumber, fpnchain_id, fpngarmentinsurance, fpninvoiceaddress_id, fpnilnnumber,
       fpsusesbundles, fpsextraname1, fpsextraname2, fpnscansondeliverynote,
       nvl(lv_associationtype, 0), fpsdirectinvdeliveries, fpsdirectinvcleanweights,
       fpsdirectinvsoilweights, fpndirectinvminimumamount, fpsusecoverpage, 'N', 0, fpsedimethod, 1,
       0, fppasserbycustomer, nvl(fpnsignaturerequired, 'Y'), fpnnationalaccount_id, nvl(fpncocnumber, 0),
       nvl(fnpnnumber, 0), fpnserviceemployee_id, fpncommoncustomer_id, nvl(fpbbonusagreement, 'N'),
       fpnacquisioncode_id, fpncustomerranking_id, fpntdccode, nvl(fpschargelosscharge, 'N'), 1,
       fpstaxexemptcode, nvl(fpsinheritmapricelist, 'N'), nvl(fpsrestrictonmaproducts, 'N'),
       fpnsalesemployee1, fpnsalesemployee2, nvl(fpssplitinvoicesperactivity, 'N'),
       nvl(fpnchargerepaircog, 0), coalesce(fpndefaultinvbu, fpndefaultbusinessunit_id),
       coalesce(fpninternalbu, fpndefaultbusinessunit_id), nvl(fpbinformpriceupdate, 'N'),
       nvl(fpbdirectinvallservices, 'N'), nvl(fpbdirectinvsalesnotes, 'N'),
       nvl(fpbdepositstockallowed, 'N'), nvl(fpnalternatesorting, 'N'), fpninternalcalcpercentagelog,
       fpninternalcalcpercentagecog, nvl(fpnmaincustomertype, 1), nvl(fpnlinenreducefactor, 0),
       nvl(fpnusecontractcoefficient, 'N'), nvl(fpncontractcoefficient, 0),
       nvl(fpnreturnsamecontainer, 'N'), nvl(fpnownbatch, 'N'),
       case when fpncurrency_id = nvl(fpninvoicecurrencyid, fpncurrency_id) then null else
        fpninvoicecurrencyid end,
       case when fpncurrency_id = nvl(fpninvoicecurrencyid, fpncurrency_id) then 0 else 1 end,
       nvl(fpcustomgarmentcharge, 'N'), nvl(fp_useprodsizesurchargpricing, 'N'),
       nvl(fpautosoilpercentage, 0), nvl(lv_suppressprintdelnotebatch, 'N'),
       nvl(lv_suppressprintdelnote, 'N'), fptaxexemptcertificatedoc, nvl(fpchargerestockingfee, 'N'),
       lvnsystemuserid, sysdate, nvl(lv_masteraccountrelation, 0),fpseasonautoflagallowed,fpfirstservicedate);
    insert into customer_link
      (customer_link_id, customer_id, customernumber, name, legacycustomernumber, languagecode,
       systemuser_id, timestamp)
    values
      (fpncustomer_id, fpncustomer_id, fpncustomernumber, fpsname, fpslegacycustomernumber,
       (select l.code from languages l where l.language_id = nvl(fpnlanguageid, lvnlanguageid)),
       lvnsystemuserid, sysdate);
  end cfbcreate_customer;
  procedure cfbcreate_customeractivities(fpncustomer_id            in customeractivities.customer_id%type,
                                         fpnactivity_id            in customeractivities.activity_id%type,
                                         fpninvoicebusinessunit_id in customeractivities.invoicebusinessunit_id%type,
                                         fpnprocessbusinessunit_id in customeractivities.processbusinessunit_id%type,
                                         fpdtcutoffdate            in customeractivities.cutoffdate%type,
                                         fpsfinalinvoicecreated    in customeractivities.finalinvoicecreated%type,
                                         fpninvoicefrequency       in customeractivities.invoicefrequency_id%type,
                                         fpnsalesemployee1         in customeractivities.salesemployee1_id%type default null,
                                         fpnsalesemployee2         in customeractivities.salesemployee2_id%type default null,
                                         fpninternalbusinessunitid in customeractivities.internalprocessingbu_id%type default null) is
  begin
    insert into customeractivities
      (customer_id, activity_id, invoicebusinessunit_id, processbusinessunit_id, systemuser_id,
       timestamp, cutoffdate, finalinvoicecreated, invoicefrequency_id, salesemployee1_id,
       salesemployee2_id, internalprocessingbu_id)
    values
      (fpncustomer_id, fpnactivity_id, fpninvoicebusinessunit_id, fpnprocessbusinessunit_id,
       lvnsystemuserid, sysdate, fpdtcutoffdate, fpsfinalinvoicecreated, fpninvoicefrequency,
       fpnsalesemployee1, fpnsalesemployee2, fpninternalbusinessunitid);
  exception
    when dup_val_on_index then
      null; --does not matter if it was already there!
  end cfbcreate_customeractivities;
  procedure cfbcreate_customerbillinginfo(fpncustomer_id               in out customerbillinginfo.customer_id%type,
                                          fpndelinquentmarkafter       in customerbillinginfo.delinquentmarkafter%type,
                                          fpncreditlimit               in customerbillinginfo.creditlimit%type,
                                          fpnfinancechargeputon        in customerbillinginfo.financechargeputon%type,
                                          fpnfinancechargedays         in customerbillinginfo.financechargedays%type,
                                          fpnstatementcopies           in customerbillinginfo.statementcopies%type,
                                          fpsstatementpercustomer      in customerbillinginfo.statementpercustomer%type,
                                          fpsattachinvoicecopies       in customerbillinginfo.attachinvoicecopies%type,
                                          fpnstatementfrequency_id     in customerbillinginfo.statementfrequency_id%type,
                                          fpnsendstatement             in customerbillinginfo.sendstatement%type,
                                          fpssendstatementbyemail      in customerbillinginfo.sendstatementbyemail%type,
                                          fpncollectionresponsible_id  in customerbillinginfo.collectionresponsible_id%type,
                                          fpnpaymentterms_id           in customerbillinginfo.paymentterms_id%type,
                                          fpnstatementlayout_id        in customerbillinginfo.statementlayout_id%type,
                                          fpnhighestbalance            in customerbillinginfo.highestbalance%type,
                                          fpdthighestbalancedate       in customerbillinginfo.highestbalancedate%type,
                                          fpsconsolidatedinvoice       in customerbillinginfo.consolidatedinvoice%type,
                                          fpsbankaccount               in customerbillinginfo.bankaccount%type,
                                          fpncreditsqueezeperc         in customerbillinginfo.creditsqueezeperc%type,
                                          fpnbankinstitution_id        in customerbillinginfo.bankinstitution_id%type,
                                          fpnconsolidatedreportinv     in customerbillinginfo.consolidatedreportinv%type,
                                          fpnlaundrybankinstitution_id in customerbillinginfo.laundrybankinstitution_id%type,
                                          fpsibanno                    in customerbillinginfo.ibanno%type,
                                          fpnpaybycustomer             in customerbillinginfo.paybycustomer%type,
                                          fpnpaybycustomer_link_id     in customerbillinginfo.paybycustomer_link_id%type,
                                          fpnprintinvoice              in customerbillinginfo.printinvoice%type,
                                          fpnsendinvoiceby             in customerbillinginfo.sendinvoiceby%type,
                                          fpconsolidatedinvlayout_id   in customerbillinginfo.consolidatedinvoicelayout_id%type,
                                          fpgeneratepayment            in customerbillinginfo.generatepayment%type default 0,
										  fpsenddirectinvoicebyemail   in customerbillinginfo.senddirectinvoicebyemail%type) is
    lv_sendinvoicebyemail   customerbillinginfo.sendinvoicebyemail%type;
    lv_statementfrequencyid customerbillinginfo.statementfrequency_id%type;
    lv_sendstatementbyemail customerbillinginfo.sendstatementbyemail%type;
  begin
    if fpnsendinvoiceby = 2 then
      lv_sendinvoicebyemail := 'Y';
    else
      lv_sendinvoicebyemail := 'N';
    end if;
    /*
    --sendstatement
    1=Always
    2=Only if pas due
    3=Never
    */
    if fpnsendstatement = 3 then
      begin
        lv_statementfrequencyid := null;
        lv_sendstatementbyemail := 'N';
      end;
    else
      begin
        lv_statementfrequencyid := fpnstatementfrequency_id;
        lv_sendstatementbyemail := fpssendstatementbyemail;
      end;
    end if;
    insert into customerbillinginfo
      (delinquentmarkafter, customer_id, creditlimit, financechargeputon, financechargedays,
       statementcopies, statementpercustomer, attachinvoicecopies, statementfrequency_id,
       sendstatement, sendstatementbyemail, collectionresponsible_id, paymentterms_id,
       statementlayout_id, highestbalance, highestbalancedate, consolidatedinvoice, bankaccount,
       systemuser_id, timestamp, creditsqueezeperc, bankinstitution_id, consolidatedreportinv,
       laundrybankinstitution_id, ibanno, paybycustomer, paybycustomer_link_id, printinvoice,
       sendinvoiceby, sendinvoicebyemail, consolidatedinvoicelayout_id, generatepayment,senddirectinvoicebyemail)
    values
      (fpndelinquentmarkafter, fpncustomer_id, fpncreditlimit, fpnfinancechargeputon,
       fpnfinancechargedays, fpnstatementcopies, fpsstatementpercustomer, fpsattachinvoicecopies,
       lv_statementfrequencyid, fpnsendstatement, lv_sendstatementbyemail,
       fpncollectionresponsible_id, fpnpaymentterms_id, fpnstatementlayout_id, fpnhighestbalance,
       fpdthighestbalancedate, fpsconsolidatedinvoice, fpsbankaccount, lvnsystemuserid, sysdate,
       fpncreditsqueezeperc, fpnbankinstitution_id, fpnconsolidatedreportinv,
       fpnlaundrybankinstitution_id, fpsibanno, nvl(fpnpaybycustomer, 0), fpnpaybycustomer_link_id,
       nvl(fpnprintinvoice, 1), fpnsendinvoiceby, lv_sendinvoicebyemail, fpconsolidatedinvlayout_id,
       nvl(fpgeneratepayment, 0),nvl(fpsenddirectinvoicebyemail,'N'));
  end cfbcreate_customerbillinginfo;
  procedure cfbcreate_customerdelscheme(fpncustomer_id       in number,
                                        fpndeliveryscheme_id in number,
                                        fpnday_id            in number) is
  begin
    insert into customerdeliveryscheme
      (customer_id, deliveryscheme_id, day_id, systemuser_id, timestamp)
    values
      (fpncustomer_id, fpndeliveryscheme_id, fpnday_id, lvnsystemuserid, sysdate);
  end cfbcreate_customerdelscheme;
  procedure cfbcreate_custspecialcharge(fpncustomer_id      in customerspecialcharge.customer_id%type,
                                        fpnspecialcharge_id in customerspecialcharge.specialcharge_id%type) is
  begin
    insert into customerspecialcharge
      (customer_id, specialcharge_id, systemuser_id, timestamp)
    values
      (fpncustomer_id, fpnspecialcharge_id, lvnsystemuserid, sysdate);
  exception
    when dup_val_on_index then
      null;
  end cfbcreate_custspecialcharge;
  procedure cfbcreate_customerrentprice(fpncustomerrentprice_id      in out customerrentprice.customerrentprice_id%type,
                                        fpnproductlistpercustomer_id in customerrentprice.productlistpercustomer_id%type,
                                        fpnprice                     in customerrentprice.price%type,
                                        fpdtstartdate                in customerrentprice.startdate%type,
                                        fpnchangesperweek            in customerrentprice.changesperweek%type,
                                        fpntypeofrent                in customerrentprice.typeofrent%type,
                                        fpncontractcoefficient       in customerrentprice.contractcoefficient%type default null,
                                        fpnmaxinventory              in customerrentprice.maxinventory%type default 0,
                                        fpnsizebillingroup_id        in customerrentprice.sizebillinggroup_id%type default null) is
  begin
    insert into customerrentprice
      (customerrentprice_id, productlistpercustomer_id, price, startdate, changesperweek,
       typeofrent, systemuser_id, timestamp, contractcoefficient,maxinventory,sizebillinggroup_id)
    values
      (seq_customerrentprice.nextval, fpnproductlistpercustomer_id, fpnprice, fpdtstartdate,
       fpnchangesperweek, fpntypeofrent, lvnsystemuserid, sysdate, fpncontractcoefficient,nvl(fpnmaxinventory,0),fpnsizebillingroup_id)
    returning customerrentprice_id into fpncustomerrentprice_id;
  end cfbcreate_customerrentprice;
  procedure cfbcreate_deliveryscheme(fpndeliveryscheme_id     in out deliveryscheme.deliveryscheme_id%type,
                                     fpscode                  in deliveryscheme.code%type,
                                     fpsdefaultdeliveryscheme in deliveryscheme.defaultdeliveryscheme%type default 'N',
                                     fpnfrequency             in deliveryscheme.frequency%type default 1,
                                     fpnoffsetweek            in deliveryscheme.offsetweek%type default 0) is
    dfrequency deliveryscheme.frequency%type;
    doffset    deliveryscheme.offsetweek%type;
  begin
    begin
      select ds.deliveryscheme_id
      into   fpndeliveryscheme_id
      from   deliveryscheme ds
      where  ds.code = fpscode;
    exception
      when no_data_found then
        begin
          dfrequency := fpnfrequency;
          doffset    := fpnoffsetweek;
          if dfrequency is null or doffset is null then
            begin
              -- weeknumber  determination.
              if length(fpscode) = 3 then
                begin
                  dfrequency := to_number(substr(fpscode, 0, 1), '99');
                  doffset    := to_number(substr(fpscode, 3, 1), '99') - 1;
                end;
              else
                begin
                  dfrequency := to_number(substr(fpscode, 0, 2), '99');
                  doffset    := to_number(substr(fpscode, 4, 2), '99') - 1;
                end;
              end if;
            exception
              when others then
                null;
            end;
          end if;
          if doffset > dfrequency then
            doffset := nvl(doffset, 1) - dfrequency;
          end if;
          if doffset > dfrequency then
            doffset := nvl(dfrequency, 1) - 1;
          end if;
          if doffset < 1 then
            doffset := 0;
          end if;
          if doffset > 52 then
            doffset := 52;
          end if;
          if dfrequency < 1 then
            dfrequency := 1;
          end if;
          if dfrequency > 53 then
            dfrequency := 53;
          end if;
          insert into deliveryscheme
            (deliveryscheme_id, code, defaultdeliveryscheme, systemuser_id, timestamp, frequency,
             offsetweek)
          values
            (seq_deliveryscheme.nextval, fpscode, nvl(fpsdefaultdeliveryscheme, 'N'),
             lvnsystemuserid, sysdate, nvl(dfrequency, 1), nvl(doffset, 0))
          returning deliveryscheme_id into fpndeliveryscheme_id;
        end;
    end;
  end cfbcreate_deliveryscheme;
  procedure cfbcreate_deliverypoint(fpndeliverypoint_id  in out deliverypoint.deliverypoint_id%type,
                                    fpncustomer_id       in deliverypoint.customer_id%type,
                                    fpscode              in deliverypoint.code%type,
                                    fpsdescription       in deliverypoint.description%type,
                                    fpndeliveryaddressid in deliverypoint.deliveryaddress_id%type,
                                    fpssortaddress       in deliverypoint.sortaddress%type) is
  begin
    select p.deliverypoint_id
    into   fpndeliverypoint_id
    from   deliverypoint p
    where  p.code = fpscode
    and    p.customer_id = fpncustomer_id;
  exception
    when others then
      begin
        insert into deliverypoint
          (deliverypoint_id, customer_id, code, description, systemuser_id, timestamp,
           deliveryaddress_id, sortaddress)
        values
          (seq_deliverypoint.nextval, fpncustomer_id, fpscode, fpsdescription, lvnsystemuserid,
           sysdate, fpndeliveryaddressid, fpssortaddress);
        select seq_deliverypoint.currval into fpndeliverypoint_id from dual;
        insert into deliverypoint_link
          (deliverypoint_link_id, deliverypoint_id, customer_link_id, code, description,
           systemuser_id, timestamp)
        values
          (fpndeliverypoint_id, fpndeliverypoint_id, fpncustomer_id, fpscode, fpsdescription,
           lvnsystemuserid, sysdate);
      end;
  end cfbcreate_deliverypoint;
  procedure cfbcreate_deliveryvariations(fpndeliveryvariations_id in out deliveryvariations.deliveryvariations_id%type,
                                         fpnproduct_id            in deliveryvariations.product_id%type,
                                         fpdtdeliverydate         in deliveryvariations.deliverydate%type,
                                         fpnorigin                in deliveryvariations.origin%type,
                                         fpnamount                in deliveryvariations.amount%type,
                                         fpnfinishingmethod_id    in deliveryvariations.finishingmethod_id%type,
                                         fpsfixedamount           in deliveryvariations.fixedamount%type,
                                         fpndistributionpoint_id  in deliveryvariations.distributionpoint_id%type,
                                         fpnpackingnote_id        in deliveryvariations.packingnote_id%type,
                                         fpnsizedefinition_id     in deliveryvariations.sizedefinition_id%type,
                                         fpsreference             in deliveryvariations.reference%type,
                                         fpsprocessed             in deliveryvariations.processed%type,
                                         fpncausenote_id          in deliveryvariations.causenote_id%type,
                                         fpsupdaterentqty         in deliveryvariations.updaterentqty%type,
                                         fpnadjustmentreason_id    in deliveryvariations.adjustmentreason_id%type,
                                         fpnprocessbusinessunitid  in deliveryvariations.processbusinessunit_id%type,
                                         fpninternalprocessingbuid in deliveryvariations.internalprocessingbu_id%type) is
    lv_origin           deliveryvariations.origin%type;
    lv_soilcountsubtype deliveryvariations.soilcountsubtype%type;
  begin
    case fpnorigin
      when 1 then
        lv_origin           := 1;
        lv_soilcountsubtype := 1;
      when 2 then
        lv_origin           := 2;
        lv_soilcountsubtype := 0;
      when 3 then
        lv_origin           := 3;
        lv_soilcountsubtype := 0;
      when 4 then
        lv_origin           := 4;
        lv_soilcountsubtype := 0;
      when 5 then
        lv_origin           := 5;
        lv_soilcountsubtype := 0;
      when 6 then
        lv_origin           := 6;
        lv_soilcountsubtype := 0;
      when 7 then
        lv_origin           := 7;
        lv_soilcountsubtype := 0;
      when 8 then
        lv_origin           := 8;
        lv_soilcountsubtype := 0;
      when 9 then
        lv_origin           := 1;
        lv_soilcountsubtype := 2;
      when 10 then
        lv_origin           := 1;
        lv_soilcountsubtype := 3;
      when 11 then
        lv_origin           := 1;
        lv_soilcountsubtype := 4;
      when 12 then
        lv_origin           := 1;
        lv_soilcountsubtype := 5;
      when 13 then
        lv_origin           := 7;
        lv_soilcountsubtype := 6;
      when 14 then
        lv_origin           := 1;
        lv_soilcountsubtype := 7;
      else
        lv_origin           := 1;
        lv_soilcountsubtype := 0; --wrong entry actually
    end case;
    insert into deliveryvariations
      (deliveryvariations_id, product_id, deliverydate, origin, amount, finishingmethod_id,
       fixedamount, distributionpoint_id, packingnote_id, sizedefinition_id, reference, processed,
       causenote_id, updaterentqty, adjustmentreason_id, systemuser_id, timestamp, soilcountsubtype,
       processbusinessunit_id, internalprocessingbu_id)
    values
      (seq_deliveryvariations.nextval, fpnproduct_id, fpdtdeliverydate, lv_origin, fpnamount,
       fpnfinishingmethod_id, fpsfixedamount, fpndistributionpoint_id, fpnpackingnote_id,
       fpnsizedefinition_id, fpsreference, fpsprocessed, fpncausenote_id, fpsupdaterentqty,
       fpnadjustmentreason_id, lvnsystemuserid, sysdate, lv_soilcountsubtype,
       fpnprocessbusinessunitid, nvl(fpninternalprocessingbuid, fpnprocessbusinessunitid));
    select seq_deliveryvariations.currval into fpndeliveryvariations_id from dual;
  end cfbcreate_deliveryvariations;
  procedure cfbcreate_department(fpndepartment_id        in out department.department_id%type,
                                 fpsnumber               in department.departmentnumber%type,
                                 fpsdescription          in department.description%type,
                                 fpncostcenter_id        in department.costcenter_id%type,
                                 fpnoccupancy            in department.occupancy%type,
                                 fpsstandardpackamount   in department.standardpackamount%type,
                                 fpsactive               in department.active%type,
                                 fpncustomer_id          in department.customer_id%type,
                                 fpslegacydepartmentcode in department.legacydepartmentcode%type,
                                 fpncontactperson_id     in department.contactperson_id%type,
                                 fpsdelnotetoemail       in department.delnotetoemail%type) is
  begin
    insert into department
      (department_id, departmentnumber, description, costcenter_id, occupancy, standardpackamount,
       active, customer_id, systemuser_id, legacydepartmentcode, timestamp, contactperson_id,
       delnotetoemail, bulkdeliveriesdept)
    values
      (seq_department.nextval, fpsnumber, fpsdescription, fpncostcenter_id, nvl(fpnoccupancy, 100),
       nvl(fpsstandardpackamount, 'N'), nvl(fpsactive, 'Y'), fpncustomer_id, lvnsystemuserid,
       fpslegacydepartmentcode, sysdate, fpncontactperson_id, fpsdelnotetoemail, 'N')
    returning department_id into fpndepartment_id;
    -- insert into DEPARTMENT_LINK
    insert into department_link
      (department_link_id, department_id, customer_link_id, departmentnumber, description,
       legacydepartmentcode, systemuser_id, timestamp)
    values
      (fpndepartment_id, fpndepartment_id, fpncustomer_id, fpsnumber, fpsdescription,
       fpslegacydepartmentcode, lvnsystemuserid, sysdate);
  end cfbcreate_department;
  procedure cfbcreate_distributionpoint(fpndistributionpoint_id      in out distributionpoint.distributionpoint_id%type,
                                        fpndistributionpointnumber   in distributionpoint.distributionpointnumber%type,
                                        fpsdescription               in distributionpoint.description%type,
                                        fpsremarkonpackingnote       in distributionpoint.remarkonpackingnote%type,
                                        fpsremarkondeliverynote      in distributionpoint.remarkondeliverynote%type,
                                        fpdtpackremarkenddate        in distributionpoint.packremarkenddate%type,
                                        fpdtdeliverremarkenddate     in distributionpoint.deliverremarkenddate%type,
                                        fpsactive                    in distributionpoint.active%type,
                                        fpndepartment_id             in distributionpoint.department_id%type,
                                        fpndeliverypoint_id          in distributionpoint.deliverypoint_id%type,
                                        fpncostcenter_id             in distributionpoint.costcenter_id%type,
                                        fpslegacydistributionpnumber in distributionpoint.legacydistributionpointnumber%type,
                                        fpsproofofvisitbarcode       in distributionpoint.proofofvisitbarcode%type,
                                        fpsdriverinstruction         in distributionpoint.driverinstruction%type,
                                        fp_materialmaintenance       in distribpointbgprotection.materialmaintenance%type default 'N',
                                        fp_garmentsetup              in distribpointbgprotection.garmentsetup%type default 'N',
                                        fp_garmentmaintenance        in distribpointbgprotection.garmentmaintenance%type default 'N',
                                        fp_garmentloss               in distribpointbgprotection.garmentloss %type default 'N',
                                        fp_garmentrepair             in distribpointbgprotection.garmentrepair%type default 'N',
                                        fp_mbyoprotection            in distribpointbgprotection.mbyoprotection%type default 'N',
                                        fp_garmentemblem             in distribpointbgprotection.garmentemblem%type default 'N') is
  begin
    select p.distributionpoint_id
    into   fpndistributionpoint_id
    from   distributionpoint p
    where  p.department_id = fpndepartment_id
    and    p.distributionpointnumber = fpndistributionpointnumber;
  exception
    when others then
      begin
        insert into distributionpoint
          (distributionpoint_id, distributionpointnumber, description, remarkonpackingnote,
           remarkondeliverynote, packremarkenddate, deliverremarkenddate, active, department_id,
           deliverypoint_id, costcenter_id, legacydistributionpointnumber, systemuser_id, timestamp,
           proofofvisitbarcode, driverinstruction)
        values
          (seq_distributionpoint.nextval, fpndistributionpointnumber, fpsdescription,
           fpsremarkonpackingnote, fpsremarkondeliverynote, fpdtpackremarkenddate,
           fpdtdeliverremarkenddate, fpsactive, fpndepartment_id, fpndeliverypoint_id,
           fpncostcenter_id, fpslegacydistributionpnumber, lvnsystemuserid, sysdate,
           fpsproofofvisitbarcode, fpsdriverinstruction)
        returning distributionpoint_id into fpndistributionpoint_id;
        insert into distributionpoint_link
          (distributionpoint_link_id, distributionpoint_id, department_link_id,
           distributionpointnumber, description, legacydistributionpointnumber, systemuser_id,
           timestamp)
        values
          (fpndistributionpoint_id, fpndistributionpoint_id, fpndepartment_id,
           fpndistributionpointnumber, fpsdescription, fpslegacydistributionpnumber, lvnsystemuserid,
           sysdate);
        if (fp_materialmaintenance = 'Y' or fp_garmentsetup = 'Y' or fp_garmentmaintenance = 'Y' or
           fp_garmentloss = 'Y' or fp_garmentrepair = 'Y' or fp_mbyoprotection = 'Y' or
           fp_garmentemblem = 'Y') then
          begin
            --take as default Y if at least one had default Y
            insert into distribpointbgprotection
              (distributionpoint_id, materialmaintenance, garmentsetup, garmentmaintenance,
               garmentloss, garmentrepair, systemuser_id, timestamp, mbyoprotection, garmentemblem)
            values
              (fpndistributionpoint_id, nvl(fp_materialmaintenance, 'Y'), nvl(fp_garmentsetup, 'Y'),
               nvl(fp_garmentmaintenance, 'Y'), nvl(fp_garmentloss, 'Y'), nvl(fp_garmentrepair, 'Y'),
               pack_import.lvnsystemuserid, sysdate, nvl(fp_mbyoprotection, 'Y'),
               nvl(fp_garmentemblem, 'Y'));
          end;
        else
          begin
            --not used all defaults N
            insert into distribpointbgprotection
              (distributionpoint_id, materialmaintenance, garmentsetup, garmentmaintenance,
               garmentloss, garmentrepair, systemuser_id, timestamp, mbyoprotection, garmentemblem)
            values
              (fpndistributionpoint_id, nvl(fp_materialmaintenance, 'N'), nvl(fp_garmentsetup, 'N'),
               nvl(fp_garmentmaintenance, 'N'), nvl(fp_garmentloss, 'N'), nvl(fp_garmentrepair, 'N'),
               pack_import.lvnsystemuserid, sysdate, nvl(fp_mbyoprotection, 'N'),
               nvl(fp_garmentemblem, 'N'));
          end;
        end if;
      end;
  end cfbcreate_distributionpoint;
  procedure cfbcreate_emblemproduct(fpnproduct_id     in out emblemproduct.product_id%type,
                                    fpnemblemtype     in emblemproduct.emblemtype%type,
                                    fpntextcolor_id   in emblemproduct.textcolor_id%type,
                                    fpnbordercolor_id in emblemproduct.bordercolor_id%type,
                                    fpnemblemfont_id  in emblemproduct.emblemfont_id%type) is
  begin
    insert into emblemproduct
      (product_id, emblemtype, textcolor_id, bordercolor_id, systemuser_id, timestamp,
       emblemfont_id)
    values
      (fpnproduct_id, fpnemblemtype, fpntextcolor_id, fpnbordercolor_id, lvnsystemuserid, sysdate,
       fpnemblemfont_id);
  end cfbcreate_emblemproduct;
  procedure cfbcreate_emblemtemplate(fpnemblemtemplate_id in out emblemtemplate.emblemtemplate_id%type,
                                     fpncustomer_id       in emblemtemplate.customer_id%type,
                                     fpscode              in emblemtemplate.code%type,
                                     fpsdescription       in emblemtemplate.description%type,
                                     fpsprintnamelabel    in emblemtemplate.printnamelabel%type,
                                     fpsactive            in emblemtemplate.active%type,
                                     fpsrentemblem        in emblemtemplate.rentemblem%type) is
  begin
    insert into emblemtemplate
      (emblemtemplate_id, customer_id, code, description, printnamelabel, systemuser_id, timestamp,
       active, rentemblem)
    values
      (seq_emblemtemplate.nextval, fpncustomer_id, upper(trim(fpscode)),
       substr(trim(fpsdescription), 1, 30), fpsprintnamelabel, lvnsystemuserid, sysdate, fpsactive,
       fpsrentemblem)
    returning emblemtemplate_id into fpnemblemtemplate_id;
  end cfbcreate_emblemtemplate;
  procedure cfbcreate_emblemtemplateline(fpnemblemtemplateline_id in out emblemtemplateline.emblemtemplateline_id%type,
                                         fpnemblemtemplate_id     in emblemtemplateline.emblemtemplate_id%type,
                                         fpnproduct_id            in emblemtemplateline.product_id%type,
                                         fpnsizedefinition_id     in emblemtemplateline.sizedefinition_id%type,
                                         fpnfontsize              in emblemtemplateline.fontsize%type,
                                         fpsdescription           in emblemtemplateline.description%type,
                                         fpntextcolor_id          in emblemtemplateline.textcolor_id%type,
                                         fpnbordercolor_id        in emblemtemplateline.bordercolor_id%type,
                                         fpnbkgcolor_id           in emblemtemplateline.bkgcolor_id%type,
                                         fpnfabric_id             in emblemtemplateline.fabric_id%type,
                                         fpnplacement_id          in emblemtemplateline.placement_id%type,
                                         fpnemblemtype            in emblemtemplateline.emblemtype%type,
                                         fpnattachmentby          in emblemtemplateline.attachmentby%type,
                                         fpnqtypergarment         in emblemtemplateline.qtypergarment%type,
                                         fpnemblemimage_id        in emblemtemplateline.emblemimage_id%type,
                                         fpnplacementimage_id     in emblemtemplateline.placementimage_id%type,
                                         fpnemblemfont_id         in emblemtemplateline.emblemfont_id%type) is
  begin
    insert into emblemtemplateline
      (emblemtemplateline_id, emblemtemplate_id, product_id, sizedefinition_id, description,
       textcolor_id, bordercolor_id, bkgcolor_id, fabric_id, placement_id, emblemtype, attachmentby,
       qtypergarment, emblemimage_id, placementimage_id, fontsize, systemuser_id, timestamp,
       emblemfont_id)
    values
      (seq_emblemtemplateline.nextval, fpnemblemtemplate_id, fpnproduct_id, fpnsizedefinition_id,
       fpsdescription, fpntextcolor_id, fpnbordercolor_id, fpnbkgcolor_id, fpnfabric_id,
       fpnplacement_id, fpnemblemtype, fpnattachmentby, fpnqtypergarment, fpnemblemimage_id,
       fpnplacementimage_id, fpnfontsize, lvnsystemuserid, sysdate, fpnemblemfont_id)
    returning emblemtemplateline_id into fpnemblemtemplateline_id;
  end cfbcreate_emblemtemplateline;
  procedure cfbcreate_emblemtemplineprice(fpnemblemtemplatelineprice_id in out emblemtemplatelineprice.emblemtemplatelineprice_id%type,
                                          fpnemblemtemplateline_id      in emblemtemplatelineprice.emblemtemplateline_id%type,
                                          fpnprice                      in emblemtemplatelineprice.price%type,
                                          fpdtstartdate                 in emblemtemplatelineprice.startdate%type) is
  begin
    insert into emblemtemplatelineprice
      (emblemtemplatelineprice_id, emblemtemplateline_id, price, startdate, systemuser_id,
       timestamp)
    values
      (seq_emblemtemplatelineprice.nextval, fpnemblemtemplateline_id, fpnprice, fpdtstartdate,
       lvnsystemuserid, sysdate);
    select seq_emblemtemplatelineprice.currval into fpnemblemtemplatelineprice_id from dual;
  end cfbcreate_emblemtemplineprice;
  procedure cfbgetcreate_employee(lvnplant_id            in plant.plant_id%type,
                                  lvnemployee_id         in out employee.employee_id%type,
                                  lvnemployeenumber      in employee.employeenumber%type,
                                  lvsname                in employee.name%type,
                                  lvssearchname          in employee.searchname%type,
                                  lvdtdateactive         in employee.dateactive%type,
                                  lvdtdateinactive       in employee.dateinactive%type,
                                  lvnpdanumber           in employee.pdanumber%type,
                                  lvnmobiledevice_id     in employee.mobiledevice_id%type,
                                  lvnworkspot            in employee.workspot%type,
                                  lvnemployeefunction_id in employee.employeefunction_id%type) is
    lvndefemployeefunction_id employee.employeefunction_id%type;
    lv_overalluniqueemployee databasesettings.overalluniqueemployee%type;
      begin
            select nvl(d.overalluniqueemployee, 'A')  into   lv_overalluniqueemployee from   databasesettings d;
        if lvnemployeenumber is null then
            lvnemployee_id := null;
       else
            if lv_overalluniqueemployee = 'A' then
               begin
                  select e.employee_id
                  into   lvnemployee_id
                  from   employee e
                  where  e.plant_id = lvnplant_id
                  and    e.employeenumber = lvnemployeenumber;
                exception
                  when no_data_found then
                    begin
                      select min(e.employee_id)
                      into   lvnemployee_id
                      from   employee e
                      where  e.employeenumber = lvnemployeenumber;
                     end;
                 end;
             elsif lv_overalluniqueemployee = 'N' then
                   begin
                      select min(e.employee_id)
                      into   lvnemployee_id
                      from   employee e
                      where  e.plant_id = lvnplant_id
                      and    e.employeenumber = lvnemployeenumber;
                   end;
             else
                begin
                   select min(e.employee_id)
                   into   lvnemployee_id
                   from   employee e
                   where  e.employeenumber = lvnemployeenumber;
                end;
             end if;
             if lvnemployee_id is null then
                  begin
                    if lvnemployeefunction_id is null and lvndefemployeefunction_id is null then
                      begin
                        select min(empf.employeefunction_id)
                        into   lvndefemployeefunction_id
                        from   employeefunction empf;
                      end;
                    end if;
                      insert into employee
                        (plant_id, employee_id, employeenumber, name, searchname, dateactive,
                         dateinactive, systemuser_id, timestamp, pdanumber, mobiledevice_id, workspot,
                         employeefunction_id)
                      values
                        (lvnplant_id, seq_employee.nextval, lvnemployeenumber,
                         nvl(lvsname, substr(to_char(lvnemployeenumber), 1, 40)),
                         nvl(substr(lvssearchname, 1, 10), '-'), nvl(lvdtdateactive, trunc(sysdate) - 1),
                         nvl(lvdtdateinactive, to_date('31-12-2099', 'dd-mm-yyyy')), lvnsystemuserid,
                         sysdate, nvl(lvnpdanumber, 0), lvnmobiledevice_id, nvl(lvnworkspot, 1),
                         nvl(lvnemployeefunction_id, lvndefemployeefunction_id))
                      returning employee_id into lvnemployee_id;
                  end;
                end if;
    end if;
  end cfbgetcreate_employee;
  procedure cfbcreate_fabric(fpnfabric_id     in out fabric.fabric_id%type,
                             fpscode          in fabric.code%type,
                             fpsusedforemblem in fabric.usedforemblem%type) is
  begin
    insert into fabric
      (fabric_id, code, systemuser_id, timestamp, usedforemblem)
    values
      (seq_fabric.nextval, fpscode, lvnsystemuserid, sysdate, fpsusedforemblem);
    select seq_fabric.currval into fpnfabric_id from dual;
  end cfbcreate_fabric;
  procedure cfbcreate_fabric_desc(fpnfabric_id   in fabric_desc.fabric_id%type,
                                  fpsdescription in fabric_desc.description%type) is
  begin
    insert into fabric_desc
      (fabric_id, language_id, description, systemuser_id, timestamp)
    values
      (fpnfabric_id, lvnlanguageid, nvl(fpsdescription, '-'), lvnsystemuserid, sysdate);
  end cfbcreate_fabric_desc;
  procedure cfbcreate_flag(fpnflag_id                   in out flag.flag_id%type,
                           fpnflagtype                  in flag.flagtype%type,
                           fpscode                      in flag.code%type,
                           fpnpriority                  in flag.priority%type,
                           fpscolor                     in flag.color%type,
                           fpsincludeincompletnesscheck in flag.includeincompletnesscheck%type,
                           fpnsound_id                  in flag.sound_id%type,
                           fpsshowalways                in flag.showalways%type,
                           fpsexporttogarmentdispenser  in flag.exporttogarmentdispenser%type,
                           fpnexportgdcode              in flag.exportgdcode%type,
                           fpnuseinwebapplication       in flag.useinwebapplication%type) is
  begin
    insert into flag
      (flag_id, flagtype, code, priority, color, includeincompletnesscheck, systemuser_id,
       timestamp, sound_id, showalways, exporttogarmentdispenser, exportgdcode, useinwebapplication)
    values
      (seq_flag.nextval, fpnflagtype, fpscode, fpnpriority, fpscolor, fpsincludeincompletnesscheck,
       lvnsystemuserid, sysdate, fpnsound_id, fpsshowalways, fpsexporttogarmentdispenser,
       fpnexportgdcode, fpnuseinwebapplication);
    select seq_flag.currval into fpnflag_id from dual;
  end cfbcreate_flag;
  procedure cfbcreate_flag_desc(fpnflag_id     in flag_desc.flag_id%type,
                                fpsdescription in flag_desc.description%type) is
  begin
    insert into flag_desc
      (flag_id, language_id, description, systemuser_id, timestamp)
    values
      (fpnflag_id, lvnlanguageid, nvl(fpsdescription, '-'), lvnsystemuserid, sysdate);
  end cfbcreate_flag_desc;
  procedure add_check_customerdeliveryday(fpncustomerid        customerdeliveryday.customer_id%type,
                                          fpndayid             customerdeliveryday.day_id%type,
                                          fpsdeliverytype      customerdeliveryday.deliverytype%type,
                                          fpntypeofmerchandise customerdeliveryday.typeofmerchadise%type) is
    lvsdeliverytype   customerdeliveryday.deliverytype%type;
    lvncheck          number;
    lvncustomernumber customer.customernumber%type;
  begin
    lvsdeliverytype := nvl(fpsdeliverytype, 'B');
    select count(1)
    into   lvncheck
    from   customerdeliveryday cd
    where  cd.customer_id = fpncustomerid
    and    cd.day_id = fpndayid
    and    cd.typeofmerchadise = fpntypeofmerchandise;
    if lvncheck = 0 and fpntypeofmerchandise in (1, 2, 5) then
      begin
        insert into customerdeliveryday
          (customer_id, day_id, timestamp, systemuser_id, deliverytype, typeofmerchadise)
        values
          (fpncustomerid, fpndayid, sysdate, lvnsystemuserid, lvsdeliverytype, fpntypeofmerchandise);
      end;
    end if;
    select count(1)
    into   lvncheck
    from   customerdeliveryscheme ds
    where  ds.customer_id = fpncustomerid
    and    ds.day_id = fpndayid;
    if lvncheck = 0 then
      begin
        select c.customernumber
        into   lvncustomernumber
        from   customer c
        where  c.customer_id = fpncustomerid;
        pack_import.write_log('No customer deliveryscheme record for customer ' ||
                              lvncustomernumber || ' on day ' || fpndayid, 3);
      end;
    end if;
  end add_check_customerdeliveryday;
  procedure cbcreate_formlayout(fpnformlayout_id in out formlayout.formlayout_id%type,
                                fpsformtype      in formlayout.formtype%type,
                                fpscode          in formlayout.code%type,
                                fpsreportname    in formlayout.reportname%type,
                                fpndefaultlayout in formlayout.defaultlayout%type,
                                fpndescription   in formlayout_desc.description%type) is
  begin
    insert into formlayout
      (formlayout_id, formtype, code, systemuser_id, reportname, timestamp, defaultlayout)
    values
      (seq_formlayout.nextval, fpsformtype, fpscode, lvnsystemuserid, fpsreportname, sysdate,
       fpndefaultlayout)
    returning formlayout_id into fpnformlayout_id;
    insert into formlayout_desc
      (formlayout_id, language_id, description, systemuser_id, timestamp)
    values
      (fpnformlayout_id, lvnlanguageid, fpndescription, lvnsystemuserid, sysdate);
  end cbcreate_formlayout;
  procedure cfbcreate_generalemblemprice(fpngeneralemblemprice_id in out generalemblemprice.generalemblemprice_id%type,
                                         fpnproduct_id            in generalemblemprice.product_id%type,
                                         fpnsizedefinition_id     in generalemblemprice.sizedefinition_id%type,
                                         fpnprice                 in generalemblemprice.price%type,
                                         fpdtstartdate            in generalemblemprice.startdate%type,
                                         fpngeneralpricelist_id   in generalemblemprice.generalpricelist_id%type) is
  begin
    insert into generalemblemprice
      (generalemblemprice_id, product_id, sizedefinition_id, price, startdate, generalpricelist_id,
       systemuser_id, timestamp)
    values
      (seq_generalemblemprice.nextval, fpnproduct_id, fpnsizedefinition_id, fpnprice, fpdtstartdate,
       fpngeneralpricelist_id, lvnsystemuserid, sysdate);
    select seq_generalemblemprice.currval into fpngeneralemblemprice_id from dual;
  end cfbcreate_generalemblemprice;
  procedure cfbcreate_generalpricelist(fpngeneralpricelist_id in out generalpricelist.generalpricelist_id%type,
                                       fpnpricetype           in generalpricelist.pricetype%type,
                                       fpscode                in generalpricelist.code%type,
                                       fpsdescription         in generalpricelist.description%type,
                                       fpsactive              in generalpricelist.active%type,
                                       fpsautopriceupdate     in generalpricelist.autopriceupdate%type,
                                       fpspriceindexcode      in generalpricelist.priceindexcode%type,
                                       fpncurrency_id         in generalpricelist.currency_id%type,
                                       fpnusage               in generalpricelist.usage%type,
                                       fpchainid              in generalpricelist.chain_id%type default null,
                                       fppriceupdatelockdate  in generalpricelist.priceupdatelockdate%type default null,
                                       fp_salesvolumeprice    in generalpricelist.salesvolumeprice%type default 'N',
                                       fp_defaultpricelist    in generalpricelist.defaultpricelist%type default 'N') is
  begin
    insert into generalpricelist
      (priceindexcode, generalpricelist_id, autopriceupdate, active, description, code, pricetype,
       currency_id, systemuser_id, timestamp, usage, chain_id, defaultpricelist, salesvolumeprice,
       priceupdatelockdate)
    values
      (fpspriceindexcode, seq_generalpricelist.nextval, nvl(fpsautopriceupdate, 'N'),
       nvl(fpsactive, 'Y'), nvl(fpsdescription, fpscode), fpscode, fpnpricetype, fpncurrency_id,
       lvnsystemuserid, sysdate, nvl(fpnusage, 0), fpchainid, nvl(fp_defaultpricelist, 'N'),
       nvl(fp_salesvolumeprice, 'N'), fppriceupdatelockdate)
    returning generalpricelist_id into fpngeneralpricelist_id;
  end cfbcreate_generalpricelist;
  procedure cfbcreate_generalrentprice(fpngeneralrentprice_id in out generalrentprice.generalrentprice_id%type,
                                       fpngeneralpricelist_id in generalrentprice.generalpricelist_id%type,
                                       fpnproduct_id          in generalrentprice.product_id%type,
                                       fpnsizedefinition_id   in generalrentprice.sizedefinition_id%type,
                                       fpnfinishingmethod_id  in generalrentprice.finishingmethod_id%type,
                                       fpnprice               in generalrentprice.price%type,
                                       fpdtstartdate          in generalrentprice.startdate%type,
                                       fpnchangesperweek      in generalrentprice.changesperweek%type,
                                       fpntypeofrent          in generalrentprice.typeofrent%type,
                                       fpnsizebillinggroup_id in generalrentprice.sizebillinggroup_id%type,
                                       fpnmaxinventory        in generalrentprice.maxinventory%type default 0) is
  begin
    insert into generalrentprice
      (generalrentprice_id, generalpricelist_id, product_id, sizedefinition_id, finishingmethod_id,
       price, startdate, changesperweek, typeofrent, maxinventory,sizebillinggroup_id ,systemuser_id, timestamp)
    values
      (seq_generalrentprice.nextval, fpngeneralpricelist_id, fpnproduct_id, fpnsizedefinition_id,
       fpnfinishingmethod_id, fpnprice, fpdtstartdate, fpnchangesperweek, fpntypeofrent,nvl(fpnmaxinventory,0),
       fpnsizebillinggroup_id,lvnsystemuserid, sysdate);
    select seq_generalrentprice.currval into fpngeneralrentprice_id from dual;
  end cfbcreate_generalrentprice;
  procedure cfbcreate_generalrepairprice(fpngeneralrepairprice_id in out generalrepairprice.generalrepairprice_id%type,
                                         fpngeneralpricelist_id   in generalrepairprice.generalpricelist_id%type,
                                         fpnrepairtype_id         in generalrepairprice.repairtype_id%type,
                                         fpnprice                 in generalrepairprice.price%type,
                                         fpdtstartdate            in generalrepairprice.startdate%type,
                                         fpnpriceperminute        in generalrepairprice.priceperminute%type) is
  begin
    insert into generalrepairprice
      (generalrepairprice_id, generalpricelist_id, repairtype_id, price, startdate, priceperminute,
       systemuser_id, timestamp)
    values
      (seq_generalrepairprice.nextval, fpngeneralpricelist_id, fpnrepairtype_id, fpnprice,
       fpdtstartdate, fpnpriceperminute, lvnsystemuserid, sysdate)
    returning generalrepairprice_id into fpngeneralrepairprice_id;
  end cfbcreate_generalrepairprice;
  procedure cfbcreate_genreplacementprice(fpngeneralreplacementprice_id in out generalreplacementprice.generalreplacementprice_id%type,
                                          fpngeneralpricelist_id        in generalreplacementprice.generalpricelist_id%type,
                                          fpnproduct_id                 in generalreplacementprice.product_id%type,
                                          fpnsizedefinition_id          in generalreplacementprice.sizedefinition_id%type,
                                          fpnprice                      in generalreplacementprice.price%type,
                                          fpdtstartdate                 in generalreplacementprice.startdate%type,
                                          fpnsizebillinggroup_id        in generalreplacementprice.sizebillinggroup_id%type) is
  begin
    insert into generalreplacementprice
      (generalreplacementprice_id, generalpricelist_id, product_id, sizedefinition_id, price,
       startdate, sizebillinggroup_id, systemuser_id, timestamp)
    values
      (seq_generalreplacementprice.nextval, fpngeneralpricelist_id, fpnproduct_id,
       fpnsizedefinition_id, fpnprice, fpdtstartdate,fpnsizebillinggroup_id, lvnsystemuserid, sysdate);
    select seq_generalreplacementprice.currval into fpngeneralreplacementprice_id from dual;
  end cfbcreate_genreplacementprice;
  procedure cfbcreate_generalsalesprice(fpngeneralsalesprice_id in out generalsalesprice.generalsalesprice_id%type,
                                        fpngeneralpricelist_id  in generalsalesprice.generalpricelist_id%type,
                                        fpnproduct_id           in generalsalesprice.product_id%type,
                                        fpnsizedefinition_id    in generalsalesprice.sizedefinition_id%type,
                                        fpnprice                in generalsalesprice.price%type,
                                        fpdtstartdate           in generalsalesprice.startdate%type,
                                        fpnvolumeprice          in generalsalesprice.volumeprice%type default 1,
                                        fpnsizebillinggroup_id  in generalsalesprice.sizebillinggroup_id%type) is
  begin
    insert into generalsalesprice
      (generalsalesprice_id, generalpricelist_id, product_id, sizedefinition_id, price, startdate,
       systemuser_id, timestamp, volumeprice,sizebillinggroup_id)
    values
      (seq_generalsalesprice.nextval, fpngeneralpricelist_id, fpnproduct_id, fpnsizedefinition_id,
       fpnprice, fpdtstartdate, lvnsystemuserid, sysdate, nvl(fpnvolumeprice, 1),fpnsizebillinggroup_id)
    returning generalsalesprice_id into fpngeneralsalesprice_id;
  end cfbcreate_generalsalesprice;
  procedure cfbcreate_generalwashprice(fpngeneralwashprice_id in out generalwashprice.generalwashprice_id%type,
                                       fpngeneralpricelist_id in generalwashprice.generalpricelist_id%type,
                                       fpnproduct_id          in generalwashprice.product_id%type,
                                       fpnsizedefinition_id   in generalwashprice.sizedefinition_id%type,
                                       fpnfinishingmethod_id  in generalwashprice.finishingmethod_id%type,
                                       fpnprice               in generalwashprice.price%type,
                                       fpdtstartdate          in generalwashprice.startdate%type,
                                       fpnpricetype           in generalwashprice.pricetype%type) is
  begin
    insert into generalwashprice
      (generalwashprice_id, generalpricelist_id, product_id, sizedefinition_id, finishingmethod_id,
       price, startdate, systemuser_id, timestamp, pricetype)
    values
      (seq_generalwashprice.nextval, fpngeneralpricelist_id, fpnproduct_id, fpnsizedefinition_id,
       fpnfinishingmethod_id, fpnprice, fpdtstartdate, lvnsystemuserid, sysdate, fpnpricetype);
    select seq_generalwashprice.currval into fpngeneralwashprice_id from dual;
  end cfbcreate_generalwashprice;
  procedure cfbcreate_generalweightprice(fpngeneralweightprice_id in out generalweightprice.generalweightprice_id%type,
                                         fpngeneralpricelist_id   in generalweightprice.generalpricelist_id%type,
                                         fpnweighingcategory_id   in generalweightprice.weighingcategory_id%type,
                                         fpssoil                  in generalweightprice.soil%type,
                                         fpnprice                 in generalweightprice.price%type,
                                         fpdtstartdate            in generalweightprice.startdate%type) is
  begin
    insert into generalweightprice
      (generalweightprice_id, generalpricelist_id, price, startdate, soil, weighingcategory_id,
       systemuser_id, timestamp)
    values
      (seq_generalweightprice.nextval, fpngeneralpricelist_id, fpnprice, fpdtstartdate, fpssoil,
       fpnweighingcategory_id, lvnsystemuserid, sysdate);
    select seq_generalweightprice.currval into fpngeneralweightprice_id from dual;
  end cfbcreate_generalweightprice;
  procedure cfbcreate_invoiceheader(fpninvoiceheader_id       in out invoiceheader.invoiceheader_id%type,
                                    fpdtinvoicedate           in invoiceheader.invoicedate%type,
                                    fpninvoicenumber          in invoiceheader.invoicenumber%type,
                                    fpndocumenttype           in invoiceheader.documenttype%type,
                                    fpninvoicebusinessunit_id in invoiceheader.invoicebusinessunit_id%type,
                                    fpnbilltocustomer_link_id in invoiceheader.billtocustomer_link_id%type,
                                    fpndeltocustomer_link_id  in invoiceheader.deltocustomer_link_id%type,
                                    fpnendweek                in invoiceheader.endweek%type,
                                    fpnstartweek              in invoiceheader.startweek%type,
                                    fpnendmonth               in invoiceheader.endmonth%type,
                                    fpnstartmonth             in invoiceheader.startmonth%type,
                                    fpscounty                 in invoiceheader.county%type,
                                    fpsstate                  in invoiceheader.state%type,
                                    fpscity                   in invoiceheader.city%type,
                                    fpszipcode                in invoiceheader.zipcode%type,
                                    fpsstreet2                in invoiceheader.street2%type,
                                    fpsstreet                 in invoiceheader.street%type,
                                    fpsdeltocustomername      in invoiceheader.deltocustomername%type,
                                    fpndeltocustomernumber    in invoiceheader.deltocustomernumber%type,
                                    fpsbilltocustomername     in invoiceheader.billtocustomername%type,
                                    fpnbilltocustomernumber   in invoiceheader.billtocustomernumber%type,
                                    fpnroutecontrol_id        in invoiceheader.routecontrol_id%type,
                                    fpnroute_id               in invoiceheader.route_id%type,
                                    fpscontactpersonphone     in invoiceheader.contactpersonphone%type,
                                    fpsemailstatus            in invoiceheader.emailstatus%type,
                                    fpsemailaddress           in invoiceheader.emailaddress%type,
                                    fpscontactpersonname      in invoiceheader.contactpersonname%type,
                                    fpnstopnumber             in invoiceheader.stopnumber%type,
                                    fpnstatus_id              in invoiceheader.status_id%type,
                                    fpnrealcollectiontype     in invoiceheader.realcollectiontype%type,
                                    fpnoriginalcollectiontype in invoiceheader.originalcollectiontype%type,
                                    fpninvoicetype            in invoiceheader.invoicetype%type,
                                    fpnadjustmentreason_id    in invoiceheader.adjustmentreason_id%type,
                                    fpsexported               in invoiceheader.exported%type,
                                    fpspurchaseorder          in invoiceheader.purchaseorder%type,
                                    fpsdeliverinstructions    in invoiceheader.deliverinstructions%type,
                                    fpsinvoicecomments        in invoiceheader.invoicecomments%type,
                                    fpntotalminusadjustment   in invoiceheader.totalminusadjustment%type,
                                    fpntotalplusadjustment    in invoiceheader.totalplusadjustment%type,
                                    fpncashcollected          in invoiceheader.cashcollected%type,
                                    fpnpaythisamount          in invoiceheader.paythisamount%type,
                                    fpnprebillamount          in invoiceheader.prebillamount%type,
                                    fpninvoicefrequency_id    in invoiceheader.invoicefrequency_id%type,
                                    fpncurrency_id            in invoiceheader.currency_id%type,
                                    fpnroutenumber            in invoiceheader.routenumber%type,
                                    fpnstartyear              in invoiceheader.startyear%type,
                                    fpnendyear                in invoiceheader.endyear%type,
                                    fpscontractcode           in invoiceheader.contractcode%type,
                                    fpsdepotcode              in invoiceheader.depotcode%type,
                                    fpdtstartdate             in invoiceheader.startdate%type,
                                    fpdtenddate               in invoiceheader.enddate%type,
                                    fpncreditsqueezeperc      in invoiceheader.creditsqueezeperc%type,
                                    fpsconvertedfromlegacy    in invoiceheader.convertedfromlegacy%type,
                                    fpntotalamontexclvat      in invoiceheader.totalamountexclvat%type,
                                    fpnclusterid              in invoiceheader.cluster_id%type,
                                    fpncreditsqueezeamount    in invoiceheader.creditsqueezeamount%type,
                                    fpnsplitupcode            in invoiceheader.splitupcode%type,
                                    fpnsplitupdesc            in invoiceheader.splitupdescription%type,
                                    fpnstop_id                in invoiceheader.stop_id%type,
                                    fpninvoiceyear            in invoiceheader.invoiceyear%type,
                                    fpninvoiceweek            in invoiceheader.invoiceweek%type,
                                    fpninvoicedaynumber       in invoiceheader.invoicedaynumber%type,
                                    fpsextraname1             in invoiceheader.extraname1%type,
                                    fpsextraname2             in invoiceheader.extraname2%type,
                                    fpnparentinvoiceheaderid  in invoiceheader.parentinvoiceheader_id%type,
                                    fpdtcontractstartdate     in invoiceheader.contractstartdate%type,
                                    fpdtcontractenddate       in invoiceheader.contractenddate%type,
                                    fpnpaymentdiscountdays    in invoiceheader.paymentdiscountdays%type,
                                    fpnnetpaymentdays         in invoiceheader.netpaymentdays%type,
                                    fpsdeltostreet            in invoiceheader.deltostreet%type,
                                    fpsdeltostreet2           in invoiceheader.deltostreet2%type,
                                    fpsdeltocounty            in invoiceheader.deltocounty%type,
                                    fpsdeltostate             in invoiceheader.deltostate%type,
                                    fpsdeltocity              in invoiceheader.deltocity%type,
                                    fpsdeltozipcode           in invoiceheader.deltozipcode%type,
                                    fpsstreet3                in invoiceheader.street3%type) is
  begin
    insert into invoiceheader
      (invoiceheader_id, invoicedate, invoicenumber, documenttype, invoicebusinessunit_id,
       billtocustomer_link_id, deltocustomer_link_id, endweek, startweek, endmonth, startmonth,
       county, state, city, zipcode, street2, street, deltocustomername, deltocustomernumber,
       billtocustomername, billtocustomernumber, routecontrol_id, route_id, contactpersonphone,
       emailstatus, emailaddress, contactpersonname, stopnumber, status_id, realcollectiontype,
       originalcollectiontype, invoicetype, adjustmentreason_id, exported, purchaseorder,
       deliverinstructions, invoicecomments, totalminusadjustment, totalplusadjustment,
       cashcollected, paythisamount, prebillamount, invoicefrequency_id, systemuser_id, timestamp,
       currency_id, routenumber, startyear, endyear, contractcode, depotcode, startdate, enddate,
       creditsqueezeperc, convertedfromlegacy, totalamountexclvat, cluster_id, creditsqueezeamount,
       splitupcode, splitupdescription, stop_id, invoiceyear, invoiceweek, invoicedaynumber,
       extraname1, extraname2, parentinvoiceheader_id, contractstartdate, contractenddate,
       paymentdiscountdays, netpaymentdays, deltostreet, deltostreet2, deltocounty, deltostate,
       deltocity, deltozipcode, roundingamount, nextperiodnoweeks, credited, street3)
    values
      (seq_invoiceheader.nextval, fpdtinvoicedate, fpninvoicenumber, fpndocumenttype,
       fpninvoicebusinessunit_id, fpnbilltocustomer_link_id, fpndeltocustomer_link_id, fpnendweek,
       fpnstartweek, fpnendmonth, fpnstartmonth, fpscounty, fpsstate, fpscity, fpszipcode,
       fpsstreet2, fpsstreet, fpsdeltocustomername, fpndeltocustomernumber, fpsbilltocustomername,
       fpnbilltocustomernumber, fpnroutecontrol_id, fpnroute_id, fpscontactpersonphone,
       fpsemailstatus, fpsemailaddress, fpscontactpersonname, fpnstopnumber, fpnstatus_id,
       fpnrealcollectiontype, fpnoriginalcollectiontype, fpninvoicetype, fpnadjustmentreason_id,
       fpsexported, fpspurchaseorder, fpsdeliverinstructions, fpsinvoicecomments,
       fpntotalminusadjustment, fpntotalplusadjustment, fpncashcollected, fpnpaythisamount,
       fpnprebillamount, fpninvoicefrequency_id, lvnsystemuserid, sysdate, fpncurrency_id,
       fpnroutenumber, fpnstartyear, fpnendyear, fpscontractcode, fpsdepotcode, fpdtstartdate,
       fpdtenddate, fpncreditsqueezeperc, fpsconvertedfromlegacy, fpntotalamontexclvat, fpnclusterid,
       fpncreditsqueezeamount, fpnsplitupcode, fpnsplitupdesc, fpnstop_id, fpninvoiceyear,
       fpninvoiceweek, fpninvoicedaynumber, fpsextraname1, fpsextraname2, fpnparentinvoiceheaderid,
       fpdtcontractstartdate, fpdtcontractenddate, fpnpaymentdiscountdays, fpnnetpaymentdays,
       fpsdeltostreet, fpsdeltostreet2, fpsdeltocounty, fpsdeltostate, fpsdeltocity, fpsdeltozipcode,
       0, 0, 0, fpsstreet3)
    returning invoiceheader_id into fpninvoiceheader_id;
  end cfbcreate_invoiceheader;
  procedure cfbcreate_invoiceheaderus(fpninvoiceheader_id in out invoiceheaderus.invoiceheader_id%type,
                                      fpntaxstates_id     in invoiceheaderus.taxstates_id%type,
                                      fpnstatestaxrate    in invoiceheaderus.statestaxrate%type,
                                      fpntaxcity_id       in invoiceheaderus.taxcity_id%type,
                                      fpncitytaxrate      in invoiceheaderus.citytaxrate%type,
                                      fpntaxcounty_id     in invoiceheaderus.taxcounty_id%type,
                                      fpncountytaxrate    in invoiceheaderus.countytaxrate%type) is
  begin
    insert into invoiceheaderus
      (invoiceheader_id, taxstates_id, statestaxrate, taxcity_id, citytaxrate, taxcounty_id,
       countytaxrate, systemuser_id, timestamp)
    values
      (fpninvoiceheader_id, fpntaxstates_id, fpnstatestaxrate, fpntaxcity_id, fpncitytaxrate,
       fpntaxcounty_id, fpncountytaxrate, lvnsystemuserid, sysdate);
  exception
    when dup_val_on_index then
      update invoiceheaderus
      set    invoiceheader_id = fpninvoiceheader_id, taxstates_id = fpntaxstates_id,
             statestaxrate = fpnstatestaxrate, taxcity_id = fpntaxcity_id,
             citytaxrate = fpncitytaxrate, taxcounty_id = fpntaxcounty_id,
             countytaxrate = fpncountytaxrate, systemuser_id = lvnsystemuserid, timestamp = sysdate
      where  invoiceheader_id = fpninvoiceheader_id;
      if sql%rowcount < 1 then
        raise no_data_found;
      end if;
  end cfbcreate_invoiceheaderus;
  procedure cfbcreate_miscellaneouscharge(fpnmiscellaneouscharge_id in out miscellaneouscharge.miscellaneouscharge_id%type,
                                          fpninvoicebusinessunit_id in miscellaneouscharge.invoicebusinessunit_id%type,
                                          fpncustomer_link_id       in miscellaneouscharge.customer_link_id%type,
                                          fpdtcreationdate          in miscellaneouscharge.creationdate%type,
                                          fpsdescription            in miscellaneouscharge.description%type,
                                          fpnturnovergroup_id       in miscellaneouscharge.turnovergroup_id%type,
                                          fpninvoiceheader_id       in miscellaneouscharge.invoiceheader_id%type,
                                          fpnquantity               in miscellaneouscharge.quantity%type,
                                          fpnprice                  in miscellaneouscharge.price%type,
                                          fpndiscountpercentage     in miscellaneouscharge.discountpercentage%type,
                                          fpnamount                 in miscellaneouscharge.amount%type,
                                          fpnchargestatus           in miscellaneouscharge.chargestatus%type,
                                          fpntaxgroup_id            in miscellaneouscharge.taxgroup_id%type,
                                          fpncostcenterid           in miscellaneouscharge.costcenter_link_id%type) is
  begin
    insert into miscellaneouscharge
      (miscellaneouscharge_id, invoicebusinessunit_id, customer_link_id, creationdate, description,
       turnovergroup_id, invoiceheader_id, quantity, price, discountpercentage, amount, chargestatus,
       taxgroup_id, systemuser_id, timestamp, costcenter_link_id, creationuser_id, creationtimestamp)
    values
      (seq_miscellaneouscharge.nextval, fpninvoicebusinessunit_id, fpncustomer_link_id,
       fpdtcreationdate, fpsdescription, fpnturnovergroup_id, fpninvoiceheader_id, fpnquantity,
       fpnprice, fpndiscountpercentage, fpnamount, fpnchargestatus, fpntaxgroup_id, lvnsystemuserid,
       sysdate, fpncostcenterid, lvnsystemuserid, fpdtcreationdate)
    returning miscellaneouscharge_id into fpnmiscellaneouscharge_id;
  end cfbcreate_miscellaneouscharge;
  procedure cfbcreate_modification(fpnmodification_id        in out modification.modification_id%type,
                                   fpscode                   in modification.code%type,
                                   fpsstockwithstandardsize  in modification.stockwithstandardsize%type,
                                   fpslegacymodificationcode in modification.legacymodificationcode%type,
                                   fpsuseinwebapplication    in modification.useinwebapplication%type) is
  begin
    insert into modification
      (modification_id, code, stockwithstandardsize, legacymodificationcode, systemuser_id,
       timestamp, useinwebapplication)
    values
      (seq_modification.nextval, fpscode, fpsstockwithstandardsize, fpslegacymodificationcode,
       lvnsystemuserid, sysdate, fpsuseinwebapplication);
    select seq_modification.currval into fpnmodification_id from dual;
  end cfbcreate_modification;
  procedure cfbcreate_modification_desc(fpnmodification_id in modification_desc.modification_id%type,
                                        fpsdescription     in modification_desc.description%type) is
  begin
    insert into modification_desc
      (modification_id, language_id, description, systemuser_id, timestamp)
    values
      (fpnmodification_id, lvnlanguageid, nvl(fpsdescription, '-'), lvnsystemuserid, sysdate);
  end cfbcreate_modification_desc;
  procedure cfbcreate_placement(fpnplacement_id in out placement.placement_id%type,
                                fpscode         in placement.code%type) is
  begin
    insert into placement
      (placement_id, code, systemuser_id, timestamp)
    values
      (seq_placement.nextval, fpscode, lvnsystemuserid, sysdate);
    select seq_placement.currval into fpnplacement_id from dual;
  end cfbcreate_placement;
  procedure cfbcreate_placement_desc(fpnplacement_id in placement_desc.placement_id%type,
                                     fpsdescription  in placement_desc.description%type) is
  begin
    insert into placement_desc
      (placement_id, language_id, description, systemuser_id, timestamp)
    values
      (fpnplacement_id, lvnlanguageid, nvl(fpsdescription, '-'), lvnsystemuserid, sysdate);
  end cfbcreate_placement_desc;
  procedure cfbcreate_plpdistribpoint(fpnprodlistperdistribpoint_id in out productlistperdistribpoint.productlistperdistribpoint_id%type,
                                      fpndistributionpoint_id       in productlistperdistribpoint.distributionpoint_id%type,
                                      fpnproduct_id                 in productlistperdistribpoint.product_id%type,
                                      fpnsizedefinition_id          in productlistperdistribpoint.sizedefinition_id%type,
                                      fpnfinishingmethod_id         in productlistperdistribpoint.finishingmethod_id%type,
                                      fpncountsequence              in productlistperdistribpoint.countsequence%type,
                                      fpnorderingmethod             in productlistperdistribpoint.orderingmethod%type,
                                      fpnholidayusagefactor         in productlistperdistribpoint.holidayusagefactor%type,
                                      fpncontractperiod             in productlistperdistribpoint.contractperiod%type default 0,
                                      fpnprolongationperiod         in productlistperdistribpoint.prolongationperiod%type default 0,
                                      fpncanceladvanceperiod        in productlistperdistribpoint.canceladvanceperiod%type default 0,
                                      fpdeliverypercentage          in productlistperdistribpoint.deliverypercentage%type default null,
                                      fpbillingpercentage           in productlistperdistribpoint.billingpercentage%type default null) is
    lv_countsequence productlistperdistribpoint.countsequence%type;
  begin
    insert into productlistperdistribpoint
      (productlistperdistribpoint_id, distributionpoint_id, product_id, sizedefinition_id,
       finishingmethod_id, countsequence, orderingmethod, holidayusagefactor, systemuser_id,
       timestamp, contractperiod, prolongationperiod, canceladvanceperiod, deliverypercentage,
       billingpercentage)
    values
      (seq_productlistperdistribpoint.nextval, fpndistributionpoint_id, fpnproduct_id,
       fpnsizedefinition_id, fpnfinishingmethod_id, fpncountsequence, fpnorderingmethod,
       fpnholidayusagefactor, lvnsystemuserid, sysdate, nvl(fpncontractperiod, 0),
       nvl(fpnprolongationperiod, 0), nvl(fpncanceladvanceperiod, 0), fpdeliverypercentage,
       fpbillingpercentage)
    returning productlistperdistribpoint_id into fpnprodlistperdistribpoint_id;
  exception
    when dup_val_on_index then
      begin
        --guess index error XAK1PRODUCTLISTPERDISTRIBPOINT, get free next countsequence
        select nvl(max(countsequence), 0) + 1
        into   lv_countsequence
        from   productlistperdistribpoint
        where  distributionpoint_id = fpndistributionpoint_id;
        --try again insert
        insert into productlistperdistribpoint
          (productlistperdistribpoint_id, distributionpoint_id, product_id, sizedefinition_id,
           finishingmethod_id, countsequence, orderingmethod, holidayusagefactor, systemuser_id,
           timestamp, contractperiod, prolongationperiod, canceladvanceperiod)
        values
          (seq_productlistperdistribpoint.nextval, fpndistributionpoint_id, fpnproduct_id,
           fpnsizedefinition_id, fpnfinishingmethod_id, lv_countsequence, fpnorderingmethod,
           fpnholidayusagefactor, lvnsystemuserid, sysdate, nvl(fpncontractperiod, 0),
           nvl(fpnprolongationperiod, 0), nvl(fpncanceladvanceperiod, 0))
        returning productlistperdistribpoint_id into fpnprodlistperdistribpoint_id;
      end;
  end cfbcreate_plpdistribpoint;
  procedure cfbcreate_pricelistpercustomer(fpnpricelistpercustomer_id in out pricelistpercustomer.pricelistpercustomer_id%type,
                                           fpncustomer_id             in pricelistpercustomer.customer_id%type,
                                           fpnpricetype               in pricelistpercustomer.pricetype%type,
                                           fpngeneralpricelist_id     in pricelistpercustomer.generalpricelist_id%type,
                                           fpnpriority                in pricelistpercustomer.priority%type default null,
                                           fpdtdateactive             in pricelistpercustomer.dateactive%type,
                                           fpdtdateinactive           in pricelistpercustomer.dateinactive%type,
                                           fpspriceindexcode          in pricelistpercustomer.priceindexcode%type,
                                           fpdpriceupdatelockdate     in pricelistpercustomer.priceupdatelockdate%type,
                                           fpnotfound_prioritydefault in pricelistpercustomer.priority%type default null) is
    lv_priority pricelistpercustomer.priority%type;
    procedure get_cust_pricelistprio is
    begin
      select i.priority
      into   lv_priority
      from   i_pricelistpercustomer i
      join   customer c
      on     c.customernumber = i.customernumber
      where  c.customer_id = fpncustomer_id
      and    i.pricelisttype = fpnpricetype
      and    i.pricelistcode is null;
    exception
      when no_data_found then
        lv_priority := fpnotfound_prioritydefault;
    end get_cust_pricelistprio;
  begin
    --get pricelistper customer bassed on the main key which is:
    -- 1. customer
    -- 2. price type
    -- 3. general price list
    if fpngeneralpricelist_id is null then
      select l.pricelistpercustomer_id
      into   fpnpricelistpercustomer_id
      from   pricelistpercustomer l
      where  l.customer_id = fpncustomer_id
      and    l.pricetype = fpnpricetype
      and    l.generalpricelist_id is null;
    else
      select l.pricelistpercustomer_id
      into   fpnpricelistpercustomer_id
      from   pricelistpercustomer l
      where  l.customer_id = fpncustomer_id
      and    l.pricetype = fpnpricetype
      and    l.generalpricelist_id = fpngeneralpricelist_id;
    end if;
  exception
    when no_data_found then
      begin
        --get id
        select seq_pricelistpercustomer.nextval into fpnpricelistpercustomer_id from dual;
        get_cust_pricelistprio;
        --insert record
        insert into pricelistpercustomer
          (pricelistpercustomer_id, customer_id, pricetype, generalpricelist_id, priority,
           dateactive, dateinactive, systemuser_id, timestamp, priceindexcode, priceupdatelockdate)
        values
          (fpnpricelistpercustomer_id, fpncustomer_id, fpnpricetype, fpngeneralpricelist_id,
           coalesce(fpnpriority, lv_priority, fpnotfound_prioritydefault, 1), fpdtdateactive,
           nvl(fpdtdateinactive, to_date('31-12-2099', 'dd-mm-yyyy')), lvnsystemuserid, sysdate,
           fpspriceindexcode, fpdpriceupdatelockdate);
      end;
  end cfbcreate_pricelistpercustomer;
  procedure cfbcreate_product(fpnproduct_id                  in out product.product_id%type,
                              fpscode                        in product.code%type,
                              fpnpackingsequence             in product.packingsequence%type,
                              fpnpackingamount               in product.packingamount%type,
                              fpsactive                      in product.active%type,
                              fpsgarmentset                  in product.garmentset%type,
                              fpspack                        in product.pack%type,
                              fpsmodel                       in product.model%type,
                              fpsoccupancyrelated            in product.occupancyrelated%type,
                              fpsspecialsize                 in product.specialsize%type,
                              fpnvolumeunits                 in product.volumeunits%type,
                              fpntheoreticalweight           in product.theoreticalweight%type,
                              fpslegacyproductcode           in product.legacyproductcode%type,
                              fpnfabric_id                   in product.fabric_id%type,
                              fpncolor_id                    in product.color_id%type,
                              fpnsupplier_id                 in product.supplier_id%type,
                              fpnsizetype_id                 in product.sizetype_id%type,
                              fpnwashingprocess_id           in product.washingprocess_id%type,
                              fpnproductgroup_id             in product.productgroup_id%type,
                              fpnweighingcategory_id         in product.weighingcategory_id%type,
                              fpnparentproduct_id            in out product.parentproduct_id%type,
                              fpnregistrationunit_id         in product.registrationunit_id%type,
                              fpssoilcountmethod             in product.soilcountmethod%type,
                              fpsrecordpassivestock          in product.recordpassivestock%type,
                              fpspermitinvoiceadjust         in varchar2, --NOT USED ANYMORE!!
                              fpntypeofmerchandise           in product.typeofmerchandise%type,
                              fpnminimumturnaround           in product.minimumturnaround%type,
                              fpnautoreplacement             in product.autoreplacement%type,
                              fpsshortdescription            in product.shortdescription%type,
                              fpninvoicecolumn               in product.invoicecolumn%type,
                              fpnrentturnovergroup_id        in product.rentturnovergroup_id%type,
                              fpnwashturnovergroup_id        in product.washturnovergroup_id%type,
                              fpnreplacementturnovergroup_id in product.replacementturnovergroup_id%type,
                              fpnsalesturnovergroup_id       in product.salesturnovergroup_id%type,
                              fpnimage_id                    in product.image_id%type,
                              fpnmaxwashes                   in product.maxwashes%type,
                              fpsuniquepoolitem              in product.uniquepoolitem%type,
                              fpnputuptype                   in product.putuptype%type,
                              fpnexchangemethod              in product.exchangemethod%type,
                              fpneannumber                   in product.eannumber%type,
                              fpnfinishingcode_id            in product.finishingcode_id%type,
                              fpnfulfillmentgroup            in product.fulfillmentgroup%type,
                              fpsstoreactivestocklocation    in product.storeactivestocklocation%type,
                              fpsdefaultprovisiongroupid     in provisiongroup.provisiongroup_id%type,
                              fpsusegradecategorydefect      in product.usegradecategorydefect%type,
                              fpndefaultreturngrade_id       in product.defaultreturngrade_id%type,
                              fpsmountingproduct             in product.mountingproduct%type,
                              fpsshowonmountingorder         in product.showonmountingorder%type,
                              fpsshowondismountingorder      in product.showondismountingorder%type,
                              fpsshowonpicklistrsc           in product.showonpicklistrsc%type,
                              fpndefaultsalesgrade           in product.defaultsalesgrade_id%type,
                              fpndefaultmountinggradeid      in product.defaultmountinggrade_id%type,
                              fpspercentagefirstdelivery     in product.percentagefirstdelivery%type,
                              fpnlostturnovergroup           in product.lossturnovergroup_id%type,
                              fpnadvanceturnovergroup_id     in product.advanceturnovergroup_id%type,
                              fpncorrectionsturnovergroup_id in product.correctionsturnovergroup_id%type,
                              fpnwashcogturnovergroup_id     in product.washcogturnovergroup_id%type,
                              fpnpacktype                    in product.packtype%type,
                              fpntreatmentcheckscheme_id     in product.treatmentcheckscheme_id%type,
                              fpslotnumberrequired           in product.lotnumberrequired%type,
                              fpnorpackcontentsallowed       in product.orpackcontentsallowed%type,
                              fpndefaultstockroomid          in product.defaultstockroom_id%type default null,
                              fpsfixedstockroom              in product.fixedstockroom%type default 'N',
                              fpnproductrankingid            in product.productranking_id%type default null,
                              fpnloanturnovergroup_id        in product.loanturnovergroup_id%type default null,
                              fpsizebreakdown                in product.sizebreakdown%type default 'N',
                              fpdefaultresidualvalueschemeid in product.defaultresidualvaluescheme_id%type default null,
                              fpmisproductid                 in product.misproduct_id%type default null,
                              fpconfirmproductonpda          in product.confirmproductonpda%type default 1,
                              fptotalpackweight              in product.totalpackweight%type default null,
                              fppackvolumeunits              in product.packvolumeunits%type default null,
                              fpproductsortgroupid           in product.productsortgroup_id%type default null,
                              fprentnotretturnovergroupid    in product.rentnotretturnovergroup_id%type default null,
                              fpcustomgarmentcharge          in product.customgarmentcharge%type default 'N',
                              fpmmprotection                 in product.materialmaintenanceprotection%type default 0,
                              fpdeliverytobillrelationship   in product.deliverytobillrelationship%type default 'N',
                              fpremark                       in product.remark%type default null,
                              fpsalesonly                    in product.salesonly%type default 'N',
                              fpmrpcodeid                    in product.mrpcode_id%type default null,
                              fpmmpdefaultpercentage         in product.mmpdefaultpercentage%type default null,
                              fpallowoneofforderingonra      in product.allowoneofforderingonra%type default 'N') is
    sproductgroupcode             productgroup.code%type;
    lv_storeactivestocklocation   varchar2(1);
    lv_bulkpackingactivestocktype number(1);
  begin
    select seq_product.nextval into fpnproduct_id from dual;
    if fpsmodel = 'N' then
      fpnparentproduct_id := fpnproduct_id;
    end if;
    case fpsstoreactivestocklocation
      when 'N' then
        lv_storeactivestocklocation   := 'N';
        lv_bulkpackingactivestocktype := 0;
      when 'Y' then
        lv_storeactivestocklocation   := 'Y';
        lv_bulkpackingactivestocktype := 0;
      when '0' then
        lv_storeactivestocklocation   := 'N';
        lv_bulkpackingactivestocktype := 0;
      when '1' then
        lv_storeactivestocklocation   := 'Y';
        lv_bulkpackingactivestocktype := 1;
      when '2' then
        lv_storeactivestocklocation   := 'Y';
        lv_bulkpackingactivestocktype := 2;
      when '3' then
        lv_storeactivestocklocation   := 'Y';
        lv_bulkpackingactivestocktype := 3;
      else
        lv_storeactivestocklocation   := 'N';
        lv_bulkpackingactivestocktype := 0;
    end case;
    insert into product
      (product_id, packingsequence, code, packingamount, active, garmentset, pack, model,
       occupancyrelated, specialsize, volumeunits, productgroup_id, theoreticalweight,
       weighingcategory_id, sizetype_id, color_id, fabric_id, washingprocess_id, supplier_id,
       parentproduct_id, registrationunit_id, systemuser_id, legacyproductcode, timestamp,
       soilcountmethod, recordpassivestock, typeofmerchandise, minimumturnaround, autoreplacement,
       shortdescription, invoicecolumn, rentturnovergroup_id, washturnovergroup_id,
       replacementturnovergroup_id, salesturnovergroup_id, image_id, maxwashes, uniquepoolitem,
       putuptype, exchangemethod, eannumber, finishingcode_id, fulfillmentgroup,
       storeactivestocklocation, defaultprovisiongroup_id, usegradecategorydefect,
       defaultreturngrade_id, mountingproduct, showonmountingorder, showondismountingorder,
       showonpicklistrsc, defaultsalesgrade_id, defaultmountinggrade_id, percentagefirstdelivery,
       lossturnovergroup_id, advanceturnovergroup_id, correctionsturnovergroup_id,
       washcogturnovergroup_id, packtype, treatmentcheckscheme_id, lotnumberrequired,
       orpackcontentsallowed, defaultstockroom_id, fixedstockroom, productranking_id,
       loanturnovergroup_id, sizebreakdown, defaultresidualvaluescheme_id, misproduct_id,
       confirmproductonpda, totalpackweight, packvolumeunits, productsortgroup_id,
       rentnotretturnovergroup_id, customgarmentcharge, materialmaintenanceprotection,
       deliverytobillrelationship, remark, salesonly, mrpcode_id, bulkpackingactivestocktype,
       mmpdefaultpercentage, allowoneofforderingonra)
    values
      (fpnproduct_id, fpnpackingsequence, fpscode, fpnpackingamount, fpsactive, fpsgarmentset,
       fpspack, fpsmodel, fpsoccupancyrelated, fpsspecialsize, fpnvolumeunits, fpnproductgroup_id,
       fpntheoreticalweight, fpnweighingcategory_id, fpnsizetype_id, fpncolor_id, fpnfabric_id,
       fpnwashingprocess_id, fpnsupplier_id, fpnparentproduct_id, fpnregistrationunit_id,
       lvnsystemuserid, fpslegacyproductcode, sysdate, fpssoilcountmethod, fpsrecordpassivestock,
       fpntypeofmerchandise, fpnminimumturnaround, fpnautoreplacement, fpsshortdescription,
       fpninvoicecolumn, fpnrentturnovergroup_id, fpnwashturnovergroup_id,
       fpnreplacementturnovergroup_id, fpnsalesturnovergroup_id, fpnimage_id, fpnmaxwashes,
       fpsuniquepoolitem, fpnputuptype, fpnexchangemethod, fpneannumber, fpnfinishingcode_id,
       fpnfulfillmentgroup, lv_storeactivestocklocation, fpsdefaultprovisiongroupid,
       fpsusegradecategorydefect, fpndefaultreturngrade_id, fpsmountingproduct,
       fpsshowonmountingorder, fpsshowondismountingorder, fpsshowonpicklistrsc, fpndefaultsalesgrade,
       fpndefaultmountinggradeid, fpspercentagefirstdelivery, fpnlostturnovergroup,
       fpnadvanceturnovergroup_id, fpncorrectionsturnovergroup_id, fpnwashcogturnovergroup_id,
       fpnpacktype, fpntreatmentcheckscheme_id, fpslotnumberrequired, fpnorpackcontentsallowed,
       fpndefaultstockroomid, nvl(fpsfixedstockroom, 'N'), fpnproductrankingid,
       fpnloanturnovergroup_id,
       case when fpntypeofmerchandise <> 1 then 'N' else nvl(fpsizebreakdown, 'N') end,
       fpdefaultresidualvalueschemeid, fpmisproductid, nvl(fpconfirmproductonpda, 1),
       fptotalpackweight, fppackvolumeunits, fpproductsortgroupid, fprentnotretturnovergroupid,
       nvl(fpcustomgarmentcharge, 'N'), nvl(fpmmprotection, 0),
       nvl(fpdeliverytobillrelationship, 'N'), fpremark, nvl(fpsalesonly, 'N'), fpmrpcodeid,
       nvl(lv_bulkpackingactivestocktype, 0),
       case when fpmmprotection = 1 then nvl(fpmmpdefaultpercentage, 0.1) else
        nvl(fpmmpdefaultpercentage, 0) end, nvl(fpallowoneofforderingonra, 'N'));
    select code
    into   sproductgroupcode
    from   productgroup
    where  productgroup_id = fpnproductgroup_id;
    insert into product_link
      (product_link_id, product_id, code, productgroupcode, legacyproductcode, systemuser_id,
       timestamp)
    values
      (fpnproduct_id, fpnproduct_id, fpscode, sproductgroupcode, fpslegacyproductcode,
       lvnsystemuserid, sysdate);
    if fpntypeofmerchandise = 5 then
      begin
        --cfbcreate_productwashingprocess
        cfbcreate_productwashingproc(fpnproduct_id, fpnwashingprocess_id);
      end;
    end if;
  end cfbcreate_product;
  procedure cfbcreate_productwashingproc(fp_productid        in productwashingprocess.product_id%type,
                                         fp_washingprocessid productwashingprocess.washingprocess_id%type) is
  begin
    --cfbcreate_productwashingprocess, only for TOM=5 needed!
    insert into productwashingprocess
      (productwashingprocess_id, product_id, washingprocess_id, systemuser_id, timestamp)
      select seq_productwashingprocess.nextval, fp_productid, fp_washingprocessid, lvnsystemuserid,
             sysdate
      from   product p
      where  p.product_id = fp_productid
      and    p.typeofmerchandise = 5;
  exception
    when no_data_found then
      null; --no problem not TOM=5
    when dup_val_on_index then
      null; --no problem when it already exists
  end cfbcreate_productwashingproc;
  procedure cfbcreate_prodfinishingmethod(fpnproductid         product.product_id%type,
                                          fpnfinishingmethodid finishingmethod.finishingmethod_id%type) is
    id number;
  begin
    select pf.product_id
    into   id
    from   productfinishingmethod pf
    where  pf.product_id = fpnproductid
    and    pf.finishingmethod_id = fpnfinishingmethodid;
  exception
    when no_data_found then
      begin
        insert into productfinishingmethod
          (product_id, finishingmethod_id, systemuser_id, timestamp)
        values
          (fpnproductid, fpnfinishingmethodid, lvnsystemuserid, sysdate);
      end;
  end cfbcreate_prodfinishingmethod;
  procedure cfbcreate_productlistpercust(fpnproductlistpercustomer_id   in out productlistpercustomer.productlistpercustomer_id%type,
                                         fpnproduct_id                  in productlistpercustomer.product_id%type,
                                         fpdtdateactive                 in productlistpercustomer.dateactive%type,
                                         fpdtdateinactive               in productlistpercustomer.dateinactive%type,
                                         fpnfinishingmethod_id          in productlistpercustomer.finishingmethod_id%type,
                                         fpscodeuniquely                in productlistpercustomer.codeuniquely%type,
                                         fpnsoilweight                  in productlistpercustomer.soilweight%type,
                                         fpncustomer_id                 in productlistpercustomer.customer_id%type,
                                         fpsonsiteinventorycount        in productlistpercustomer.onsiteinventorycount%type,
                                         fpnsizedefinition_id           in productlistpercustomer.sizedefinition_id%type,
                                         fpnrentpricefrequency          in productlistpercustomer.rentpriceperfrequency%type,
                                         fpnchangesperweek              in productlistpercustomer.changesperweek%type,
                                         fpnpercentageafterdepreciation in productlistpercustomer.percentageafterdepreciation%type,
                                         fpnbillingmethod               in productlistpercustomer.billingmethod%type,
                                         fpnsoilcountmethod             in productlistpercustomer.soilcountmethod%type,
                                         fpnsrcmethod                   in productlistpercustomer.srcmethod%type,
                                         fpscleancount                  in productlistpercustomer.cleancount%type,
                                         fpnsrcpercentagesoilcount      in productlistpercustomer.srcpercentagesoilcount%type,
                                         fpnsrcpercentageinventory      in productlistpercustomer.srcpercentageinventory%type,
                                         fpnsrcquantity                 in productlistpercustomer.srcquantity%type,
                                         fpnsrcfrequency                in productlistpercustomer.srcfrequency%type,
                                         fpnchargeoveruse               in productlistpercustomer.chargeoveruse%type,
                                         fpschargestockroominventory    in productlistpercustomer.chargestockroominventory%type,
                                         fpnminimumturnaround           in productlistpercustomer.minimumturnaround%type,
                                         fpnminimumquantity             in productlistpercustomer.minimumquantity%type,
                                         fpnqtyfreeofcharge             in productlistpercustomer.qtyfreeofcharge%type,
                                         fpscustomcode                  in productlistpercustomer.customcode%type,
                                         fpscustomdescription           in productlistpercustomer.customdescription%type,
                                         fpncustombundlesize            in productlistpercustomer.custombundlesize%type,
                                         fpngaincompetitor_id           in productlistpercustomer.gaincompetitor_id%type,
                                         fpngainreason_id               in productlistpercustomer.gainreason_id%type,
                                         fpnlostreason_id               in productlistpercustomer.lostreason_id%type,
                                         fpnlostcompetitor_id           in productlistpercustomer.lostcompetitor_id%type,
                                         fpnresidualvaluescheme_id      in productlistpercustomer.residualvaluescheme_id%type,
                                         fpndelayedevenexchange         in productlistpercustomer.delayedevenexchange%type,
                                         fpninventorybillingtype        in productlistpercustomer.inventorybillingtype%type,
                                         fpnminimumfrequency            in productlistpercustomer.minimumfrequency%type,
                                         fpsdeliverreplacementqty       in productlistpercustomer.deliverreplacementqty%type,
                                         fpnemblemtemplate              in productlistpercustomer.emblemtemplate_id%type,
                                         fpnwashprocess                 in productlistpercustomer.washingprocess_id%type,
                                         fpsautomaticsales              in productlistpercustomer.automaticsales%type,
                                         fpscustomerrelated             in productlistpercustomer.customerrelated%type,
                                         fpsautoreplafterlifetime       in productlistpercustomer.autoreplafterlifetime%type,
                                         fpnchargerentinactiveseason    in productlistpercustomer.chargerentinactiveseason%type,
                                         fpnseasontypeid                in productlistpercustomer.seasontype_id%type,
                                         fpnchargewashespack            in productlistpercustomer.chargewashespack%type,
                                         fpsspecificputuptype           in productlistpercustomer.specificputuptype%type,
                                         fpnquantityreturned            in productlistpercustomer.quantityreturned%type,
                                         fpsstraightevenexchange        in productlistpercustomer.straightevenexchange%type,
                                         fpneannumber                   in productlistpercustomer.eannumber%type,
                                         fpnfinishingcode_id            in productlistpercustomer.finishingcode_id%type,
                                         fpnfreeqtyfrequency            in productlistpercustomer.freeqtyfrequency%type,
                                         fpnsalesemployee_id            in productlistpercustomer.salesemployee_id%type,
                                         fpsreturnstockallowed          in productlistpercustomer.returnstockallowed%type,
                                         fpsdeedeliveryscheme_id        in productlistpercustomer.deedeliveryscheme_id%type,
                                         fpsremark                      in productlistpercustomer.remark%type,
                                         fpslocation                    in productlistpercustomer.location%type,
                                         fpschargewashesonlyforcog      in productlistpercustomer.chargewashesonlyforcog%type,
                                         fpnpriceusage                  in productlistpercustomer.priceusage%type,
                                         fpnsrcchargerent               in productlistpercustomer.srcchargerent%type default 0,
                                         fpntreatmentcheckscheme_id     in productlistpercustomer.treatmentcheckscheme_id%type default null,
                                         fpndeliverylabellayout_id      in productlistpercustomer.deliverylabellayout_id%type default null,
                                         fpnsalesemployee2              in productlistpercustomer.salesemployee2_id%type default null,
                                         fpndefaultstockroomid          in productlistpercustomer.defaultstockroom_id%type default null,
                                         fpsfixedstockroom              in productlistpercustomer.fixedstockroom%type default 'N',
                                         fpnorderviaweb                 in productlistpercustomer.orderviaweb%type default 0,
                                         fpninternalcalcpercentagelog   in productlistpercustomer.internalcalcpercentagelog%type default null,
                                         fpninternalcalcpercentagecog   in productlistpercustomer.internalcalcpercentagecog%type default null,
                                         fpnchargeexcess                in productlistpercustomer.chargeexcess%type default 0,
                                         fpnbudgetusage                 in productlistpercustomer.budgetusage%type default 0,
                                         fpncustomerbudgetdefinitionid  in productlistpercustomer.customerbudgetdefinition_id%type default null,
                                         fpbdepositstockallowed         in productlistpercustomer.depositstockallowed%type default 'N',
                                         fpndepositstockchargepercent   in productlistpercustomer.depositstockchargepercentage%type default 0,
                     fpnbm1fixedwearers             in productlistpercustomer.bm1fixedwearers%type default 'N',
                                         fpnsterilisationrequired       in productlistpercustomer.sterilisationrequired%type default 'N',
                                         fpimagecare                    in productlistpercustomer.imagecare%type default 0,
                                         fpallowreturntostock           in productlistpercustomer.allowreturntostock%type default 0,
                                         fpseasonalrent                 in productlistpercustomer.seasonalrent%type default 0,
                                         fpautosoilvalue                in productlistpercustomer.autosoil%type default 0,
                                         fpautosoilpercentage           in productlistpercustomer.autosoilpercentage%type default 0,
                                         fpdefaultsupplierid            in productlistpercustomer.defaultsupplier_id%type default null,
                                         fpcontractpurchaseorder_id     in productlistpercustomer.contractpurchaseorder_id%type default null,
                     fpbm1rentcpwmax                in productlistpercustomer.bm1rentcpwmax%type default 0,
                     fpndepositstocklocation    in productlistpercustomer.depositstocklocation%type default null) is
  begin
    --Remark chargewashinactiveseason is chargerentinactiveseason in productlistpercustomer
    insert into productlistpercustomer
      (productlistpercustomer_id, product_id, dateactive, dateinactive, finishingmethod_id,
       codeuniquely, soilweight, customer_id, onsiteinventorycount, sizedefinition_id, systemuser_id,
       rentpriceperfrequency, changesperweek, percentageafterdepreciation, timestamp, billingmethod,
       soilcountmethod, srcmethod, cleancount, srcpercentagesoilcount, srcpercentageinventory,
       srcquantity, srcfrequency, chargeoveruse, chargestockroominventory, minimumturnaround,
       minimumquantity, qtyfreeofcharge, customcode, customdescription, custombundlesize,
       gaincompetitor_id, gainreason_id, lostreason_id, lostcompetitor_id, residualvaluescheme_id,
       delayedevenexchange, inventorybillingtype, minimumfrequency, deliverreplacementqty,
       emblemtemplate_id, washingprocess_id, automaticsales, customerrelated, autoreplafterlifetime,
       chargerentinactiveseason, seasontype_id, chargewashespack, specificputuptype,
       quantityreturned, straightevenexchange, eannumber, finishingcode_id, freeqtyfrequency,
       chargewashesonlyforcog, salesemployee_id, returnstockallowed, maxwashes, deedeliveryscheme_id,
       remark, location, priceusage, srcchargerent, treatmentcheckscheme_id, deliverylabellayout_id,
       salesemployee2_id, defaultstockroom_id, fixedstockroom, orderviaweb,
       internalcalcpercentagelog, internalcalcpercentagecog, chargeexcess, budgetusage,
       customerbudgetdefinition_id, depositstockallowed, depositstockchargepercentage,
       bm1fixedwearers, sterilisationrequired, imagecare, allowreturntostock, seasonalrent, autosoil,
       autosoilpercentage, defaultsupplier_id, contractpurchaseorder_id,bm1rentcpwmax,depositstocklocation)
    values
      (seq_productlistpercustomer.nextval, fpnproduct_id, fpdtdateactive, fpdtdateinactive,
       fpnfinishingmethod_id, fpscodeuniquely, fpnsoilweight, fpncustomer_id,
       fpsonsiteinventorycount, fpnsizedefinition_id, lvnsystemuserid, fpnrentpricefrequency,
       fpnchangesperweek, fpnpercentageafterdepreciation, sysdate, fpnbillingmethod,
       fpnsoilcountmethod, fpnsrcmethod, fpscleancount, fpnsrcpercentagesoilcount,
       fpnsrcpercentageinventory, fpnsrcquantity, fpnsrcfrequency, fpnchargeoveruse,
       fpschargestockroominventory, fpnminimumturnaround, fpnminimumquantity, fpnqtyfreeofcharge,
       fpscustomcode, fpscustomdescription, fpncustombundlesize, fpngaincompetitor_id,
       fpngainreason_id, fpnlostreason_id, fpnlostcompetitor_id, fpnresidualvaluescheme_id,
       fpndelayedevenexchange, fpninventorybillingtype, fpnminimumfrequency,
       fpsdeliverreplacementqty, fpnemblemtemplate, fpnwashprocess, fpsautomaticsales,
       fpscustomerrelated, fpsautoreplafterlifetime, nvl(fpnchargerentinactiveseason, 'N'),
       fpnseasontypeid, fpnchargewashespack, fpsspecificputuptype, fpnquantityreturned,
       fpsstraightevenexchange, fpneannumber, fpnfinishingcode_id, fpnfreeqtyfrequency,
       fpschargewashesonlyforcog, fpnsalesemployee_id, fpsreturnstockallowed, 0,
       fpsdeedeliveryscheme_id, fpsremark, fpslocation, nvl(fpnpriceusage, 0),
       nvl(fpnsrcchargerent, 0), fpntreatmentcheckscheme_id, fpndeliverylabellayout_id,
       fpnsalesemployee2, fpndefaultstockroomid, nvl(fpsfixedstockroom, 'N'), nvl(fpnorderviaweb, 0),
       fpninternalcalcpercentagelog, fpninternalcalcpercentagecog, fpnchargeexcess,
       nvl(fpnbudgetusage, 0), fpncustomerbudgetdefinitionid, nvl(fpbdepositstockallowed, 'N'),
       nvl(fpndepositstockchargepercent, 0),nvl(fpnbm1fixedwearers, 'N'),
       nvl(fpnsterilisationrequired, 'N'), nvl(fpimagecare, 0), nvl(fpallowreturntostock, 0),
       nvl(fpseasonalrent, 0), nvl(fpautosoilvalue, 0), nvl(fpautosoilpercentage, 0),
       fpdefaultsupplierid, fpcontractpurchaseorder_id ,nvl(fpbm1rentcpwmax,0),fpndepositstocklocation)
    returning productlistpercustomer_id into fpnproductlistpercustomer_id;
  end cfbcreate_productlistpercust;
   procedure cfbcreate_productsize(fpnproduct_id        in productsize.product_id%type,
                                  fpnsizedefinition_id in productsize.sizedefinition_id%type,
                                  fpsspecialsize       in productsize.specialsize%type,
                                  fpnpackingamount     in productsize.packingamount%type,
                                  fpntheoreticalweight in productsize.theoreticalweight%type,
                                  fpnprovisiongroupid  in productsize.provisiongroup_id%type,
                                  fpnmaxcartqty        in productsize.maxcartqty%type default 0,
                                  fpnstandardlength    in productsize.standardlength%type default 'N',
                                  fpsizebillinggroupid in productsize.sizebillinggroup_id%type default null) is
    fpnsequencenumber productsize.sequencenumber%type;
    lv_productcode    product.code%type;
    lv_sizecode       sizedefinition.code%type;
  begin
    select ps.sequencenumber
    into   fpnsequencenumber
    from   productsize ps
    where  ps.product_id = fpnproduct_id
    and    ps.sizedefinition_id = fpnsizedefinition_id;
  exception
    when no_data_found then
      begin
        if lvdbcustomercode = 'SMG' then
          begin
            --get product code for error message
            select p.code into lv_productcode from product p where p.product_id = fpnproduct_id;
            --get size code for error message
            select s.code
            into   lv_sizecode
            from   sizedefinition s
            where  s.sizedefinition_id = fpnsizedefinition_id;
            --write SMG error message
            pack_import.write_log('Product ' || lv_productcode || ' size ' || lv_sizecode ||
                                  ' does not exist, and may not be added!', 3);
          end;
        else
          begin
            select nvl(max(sequencenumber), 0) + 1
            into   fpnsequencenumber
            from   productsize
            where  product_id = fpnproduct_id;
            insert into productsize
              (product_id, sizedefinition_id, sequencenumber, specialsize, packingamount,
               theoreticalweight, systemuser_id, timestamp, provisiongroup_id, maxcartqty,
               standardlength, sizebillinggroup_id)
            values
              (fpnproduct_id, fpnsizedefinition_id, fpnsequencenumber, fpsspecialsize,
               fpnpackingamount, fpntheoreticalweight, lvnsystemuserid, sysdate, fpnprovisiongroupid,
               nvl(fpnmaxcartqty, 0), nvl(fpnstandardlength, 'N'), fpsizebillinggroupid);
          end;
        end if;
      end;
  end cfbcreate_productsize;
  procedure cfbcreate_qualitygrade(fpnqualitygrade_id     in out qualitygrade.qualitygrade_id%type,
                                   fpscode                in qualitygrade.code%type,
                                   fpsinstruction         in qualitygrade.instruction%type,
                                   fpnpriority            in qualitygrade.priority%type,
                                   fpnmaxwashes           in qualitygrade.maxwashes%type,
                                   fpnminwashes           in qualitygrade.minwashes%type,
                                   fpnmaxweeksinuse       in qualitygrade.maxweeksinuse%type,
                                   fpnminweeksinuse       in qualitygrade.minweeksinuse%type,
                                   fpsdefaultqualitygrade in qualitygrade.defaultqualitygrade%type,
                                   fpsnewgarment          in qualitygrade.newgarment%type) is
  begin
    insert into qualitygrade
      (instruction, qualitygrade_id, priority, code, maxwashes, minwashes, maxweeksinuse,
       minweeksinuse, defaultqualitygrade, newgarment, systemuser_id, timestamp)
    values
      (fpsinstruction, seq_qualitygrade.nextval, fpnpriority, fpscode, fpnmaxwashes, fpnminwashes,
       fpnmaxweeksinuse, fpnminweeksinuse, fpsdefaultqualitygrade, fpsnewgarment, lvnsystemuserid,
       sysdate);
    select seq_qualitygrade.currval into fpnqualitygrade_id from dual;
  end cfbcreate_qualitygrade;
  procedure cfbcreate_qualitygrade_desc(fpnqualitygrade_id in qualitygrade_desc.qualitygrade_id%type,
                                        fpsdescription     in qualitygrade_desc.description%type) is
  begin
    insert into qualitygrade_desc
      (qualitygrade_id, language_id, description, systemuser_id, timestamp)
    values
      (fpnqualitygrade_id, lvnlanguageid, nvl(fpsdescription, '-'), lvnsystemuserid, sysdate);
  end cfbcreate_qualitygrade_desc;
  function getqualitygradeid(qualitygradecode qualitygrade.code%type)
    return qualitygrade.qualitygrade_id%type is
    qualitygradeid qualitygrade.qualitygrade_id%type;
    priority       qualitygrade.priority%type;
  begin
    if qualitygradecode is null then
      begin
        return null;
      end;
    else
      begin
        select q.qualitygrade_id
        into   qualitygradeid
        from   qualitygrade q
        where  q.code = upper(qualitygradecode);
        return qualitygradeid;
      exception
        when no_data_found then
          begin
            select max(q.priority) + 1 into priority from qualitygrade q;
            cfbcreate_qualitygrade(qualitygradeid, upper(qualitygradecode), null,
                                               priority, 999, 0, 99, 0, 'N', 'Y');
            cfbcreate_qualitygrade_desc(qualitygradeid, upper(qualitygradecode));
            return qualitygradeid;
          exception
            when others then
              return null;
          end;
      end;
    end if;
  end getqualitygradeid; -- Determine quality grade
  procedure getdefaultqualitygradeid is
  begin
    --getdefaultqualitygradeid with highest priority
    select q.qualitygrade_id
    into   lvndefaultqualitygradeid
    from   qualitygrade q
    where  rownum = 1
    order  by q.priority asc;
    if lvndefaultqualitygradeid is null then
      raise no_data_found;
    end if;
  exception
    when no_data_found then
      begin
        lvndefaultqualitygradeid := getqualitygradeid('N');
      end;
  end getdefaultqualitygradeid;
  procedure cfbcreate_ragreason(fpnragreason_id        in out ragreason.ragreason_id%type,
                                fpscode                in ragreason.code%type,
                                fpsactive              in ragreason.active%type,
                                fpschargeresidualvalue in ragreason.chargeresidualvalue%type) is
  begin
    insert into ragreason
      (ragreason_id, code, active, chargeresidualvalue, systemuser_id, timestamp)
    values
      (seq_ragreason.nextval, fpscode, fpsactive, fpschargeresidualvalue, lvnsystemuserid, sysdate);
    select seq_ragreason.currval into fpnragreason_id from dual;
  end cfbcreate_ragreason;
  procedure cfbcreate_ragreason_desc(fpnragreason_id in ragreason_desc.ragreason_id%type,
                                     fpsdescription  in ragreason_desc.description%type) is
  begin
    insert into ragreason_desc
      (ragreason_id, language_id, description, systemuser_id, timestamp)
    values
      (fpnragreason_id, lvnlanguageid, nvl(fpsdescription, '-'), lvnsystemuserid, sysdate);
  end cfbcreate_ragreason_desc;
  procedure cfbcreate_reasoncode(fpnreasoncode_id         in out reasoncode.reasoncode_id%type,
                                 fpscode                  in reasoncode.code%type,
                                 fpsinternetselectable    in reasoncode.internetselectable%type default 'N',
                                 fpsallowprepcharges      in reasoncode.allowprepcharges%type default 'Y',
                                 fpsgarmentreason         in reasoncode.garmentreason%type default 'Y',
                                 fpslinenreason           in reasoncode.linenreason%type default 'Y',
                                 fpsexporttohandheld      in reasoncode.exporttohandheld%type default 'N',
                                 fpncancelinvoice         in reasoncode.cancelinvoice%type default 0,
                                 fpsaffectsnextinvoice    in reasoncode.affectsnextinvoice%type default 'N',
                                 fpsaffectscurrentinvoice in reasoncode.affectscurrentinvoice%type default 'N',
                                 fpninvoiceadjustment     in reasoncode.invoiceadjustment%type default 1,
                                 fpsfirstissue            in reasoncode.firstissue%type default 'N',
                                 fpninventorytrigger      in reasoncode.inventorytrigger%type default 0,
                                 fpschargeresidualvalue   in reasoncode.chargeresidualvalue%type default 'Y',
                                 fpschargerestockingfee   in reasoncode.chargerestockingfee%type default 'N') is
  begin
    insert into reasoncode
      (reasoncode_id, code, internetselectable, allowprepcharges, garmentreason, linenreason,
       exporttohandheld, cancelinvoice, affectsnextinvoice, affectscurrentinvoice, invoiceadjustment,
       firstissue, inventorytrigger, systemuser_id, timestamp, chargeresidualvalue,
       chargerestockingfee)
    values
      (seq_reasoncode.nextval, fpscode, fpsinternetselectable, fpsallowprepcharges,
       fpsgarmentreason, fpslinenreason, fpsexporttohandheld, fpncancelinvoice,
       fpsaffectsnextinvoice, fpsaffectscurrentinvoice, fpninvoiceadjustment, fpsfirstissue,
       fpninventorytrigger, lvnsystemuserid, sysdate, fpschargeresidualvalue, fpschargerestockingfee);
    select seq_reasoncode.currval into fpnreasoncode_id from dual;
  end cfbcreate_reasoncode;
  procedure cfbcreate_reasoncode_desc(fpnreasoncode_id in reasoncode_desc.reasoncode_id%type,
                                      fpsdescription   in reasoncode_desc.description%type) is
  begin
    insert into reasoncode_desc
      (description, reasoncode_id, language_id, systemuser_id, timestamp)
    values
      (nvl(fpsdescription, '-'), fpnreasoncode_id, lvnlanguageid, lvnsystemuserid, sysdate);
  end cfbcreate_reasoncode_desc;
  procedure cfbcreate_rentalqtyadjustment(fpnrentalqtyadjustment_id in out rentalqtyadjustment.rentalqtyadjustment_id%type,
                                          fpnproductlistperdip_id   in rentalqtyadjustment.productlistperdistribpoint_id%type,
                                          fpsremark                 in rentalqtyadjustment.remark%type,
                                          fpnquantity               in rentalqtyadjustment.quantity%type,
                                          fpdtadjustmentdate        in rentalqtyadjustment.adjustmentdate%type,
                                          fpnreasoncode_id          in rentalqtyadjustment.reasoncode_id%type,
                                          fpndeliveryvariation_id   in rentalqtyadjustment.deliveryvariations_id%type,
                                          fpnsalesemployee_id       in rentalqtyadjustment.salesemployee_id%type default null,
                                          fpnsalesemployee2_id      in rentalqtyadjustment.salesemployee2_id%type default null) is
  begin
    insert into rentalqtyadjustment
      (rentalqtyadjustment_id, productlistperdistribpoint_id, remark, quantity, adjustmentdate,
       reasoncode_id, systemuser_id, timestamp, deliveryvariations_id, qualitygrade_id, origin,
       salesemployee_id, salesemployee2_id)
    values
      (seq_rentalqtyadjustment.nextval, fpnproductlistperdip_id, fpsremark, fpnquantity,
       fpdtadjustmentdate, fpnreasoncode_id, lvnsystemuserid, sysdate, fpndeliveryvariation_id,
       lvndefaultqualitygradeid, 1, fpnsalesemployee_id, fpnsalesemployee2_id);
    select seq_rentalqtyadjustment.currval into fpnrentalqtyadjustment_id from dual;
  end cfbcreate_rentalqtyadjustment;
  procedure cfbcreate_season(fpnseason_id     in out season.season_id%type,
                             fpnseasontype_id in season.seasontype_id%type,
                             fpscode          in season.code%type) is
  begin
    select s.season_id
    into   fpnseason_id
    from   season s
    where  s.code = fpscode
    and    s.seasontype_id = fpnseasontype_id;
  exception
    when no_data_found then
      begin
        insert into season
          (season_id, seasontype_id, code, systemuser_id, timestamp)
        values
          (seq_season.nextval, fpnseasontype_id, fpscode, lvnsystemuserid, sysdate)
        returning season_id into fpnseason_id;
      end;
  end cfbcreate_season;
  procedure cfbcreate_seasontype(fpnseasontype_id in out seasontype.seasontype_id%type,
                                 fpscode          in season.code%type) is
  begin
    select st.seasontype_id into fpnseasontype_id from seasontype st where st.code = fpscode;
  exception
    when no_data_found then
      begin
        insert into seasontype
          (seasontype_id, code, systemuser_id, timestamp, active)
        values
          (seq_seasontype.nextval, fpscode, lvnsystemuserid, sysdate, 'Y')
        returning seasontype_id into fpnseasontype_id;
      end;
  end cfbcreate_seasontype;
  procedure cfbcreate_standarddelivery(fpnstandarddelivery_id       in out standarddelivery.standarddelivery_id%type,
                                       fpnsequencenumber            in standarddelivery.sequencenumber%type,
                                       fpsdeliversterile            in standarddelivery.deliversterile%type,
                                       fpnplantdepartment_id        in standarddelivery.plantdepartment_id%type,
                                       fpscleanreturn               in standarddelivery.cleanreturn%type,
                                       fpntransportarticle_id       in standarddelivery.transportarticle_id%type,
                                       fpsgeneratezerolines         in standarddelivery.generatezerolines%type,
                                       fpnnumberoftransportarticles in standarddelivery.numberoftransportarticles%type,
                                       fpndistributionpoint_id      in standarddelivery.distributionpoint_id%type,
                                       fpdtlastpackingdate          in standarddelivery.lastpackingdate%type,
                                       fpscorrectshortages          in standarddelivery.correctshortages%type,
                                       fpscorrectoverdeliveries     in standarddelivery.correctoverdeliveries%type,
                                       fpstruckloadposition         in standarddelivery.truckloadposition%type) is
  begin
    insert into standarddelivery
      (standarddelivery_id, sequencenumber, deliversterile, plantdepartment_id, cleanreturn,
       transportarticle_id, generatezerolines, numberoftransportarticles, distributionpoint_id,
       lastpackingdate, correctshortages, correctoverdeliveries, truckloadposition, systemuser_id,
       timestamp)
    values
      (seq_standarddelivery.nextval, fpnsequencenumber, fpsdeliversterile, fpnplantdepartment_id,
       fpscleanreturn, fpntransportarticle_id, fpsgeneratezerolines, fpnnumberoftransportarticles,
       fpndistributionpoint_id, fpdtlastpackingdate, fpscorrectshortages, fpscorrectoverdeliveries,
       fpstruckloadposition, lvnsystemuserid, sysdate);
    select seq_standarddelivery.currval into fpnstandarddelivery_id from dual;
  end cfbcreate_standarddelivery;
  procedure cfbstorecreate_stddelamount(fpnstandarddeliveryline_id in standarddeliveryamount.standarddeliveryline_id%type,
                                        fpnday_id                  in standarddeliveryamount.day_id%type,
                                        fpnamount                  in standarddeliveryamount.amount%type) is
  begin
    insert into standarddeliveryamount
      (standarddeliveryline_id, day_id, amount, systemuser_id, timestamp)
    values
      (fpnstandarddeliveryline_id, fpnday_id, fpnamount, lvnsystemuserid, sysdate);
  exception
    when dup_val_on_index then
      update standarddeliveryamount
      set    amount = fpnamount, systemuser_id = lvnsystemuserid, timestamp = sysdate
      where  standarddeliveryline_id = fpnstandarddeliveryline_id
      and    day_id = fpnday_id;
  end cfbstorecreate_stddelamount;
  procedure cfbstorecreate_normstockamount(fpnplpd_id in normstockamount.productlistperdistribpoint_id%type,
                                           fpnday_id  in normstockamount.day_id%type,
                                           fpnamount  in normstockamount.amount%type) is
  begin
    insert into normstockamount
      (productlistperdistribpoint_id, day_id, amount, systemuser_id, timestamp)
    values
      (fpnplpd_id, fpnday_id, fpnamount, lvnsystemuserid, sysdate);
  exception
    when dup_val_on_index then
      update normstockamount
      set    amount = fpnamount, systemuser_id = lvnsystemuserid, timestamp = sysdate
      where  productlistperdistribpoint_id = fpnplpd_id
      and    day_id = fpnday_id;
  end cfbstorecreate_normstockamount;
  procedure cfbcreate_sizedefinition(fpnsizedefinition_id in out sizedefinition.sizedefinition_id%type,
                                     fpscode              in sizedefinition.code%type,
                                     fpsunfinishedlength  in sizedefinition.unfinishedlength%type,
                                     fpslegacysizecode    in sizedefinition.legacysizecode%type,
                                     fpswidth             in sizedefinition.width%type,
                                     fpslength            in sizedefinition.length%type,
                                     fpsusedforemblem     in sizedefinition.usedforemblem%type,
                                     fpsizebillinggroupid in sizedefinition.sizebillinggroup_id%type default null,
                                     fpsizegroupingcodeid in sizedefinition.sizegroupingcode_id%type default null) is
    lv_reservealternativesize sizedefinition.reservealternativesize%type;
  begin
    if fpsizegroupingcodeid is null then
      lv_reservealternativesize := 'N';
    else
      lv_reservealternativesize := 'Y';
    end if;
    insert into sizedefinition
      (sizedefinition_id, code, systemuser_id, unfinishedlength, legacysizecode, width, length,
       timestamp, usedforemblem, sizebillinggroup_id, reservealternativesize, sizegroupingcode_id)
    values
      (seq_sizedefinition.nextval, fpscode, lvnsystemuserid, nvl(fpsunfinishedlength, 'N'),
       fpslegacysizecode, fpswidth, fpslength, sysdate, nvl(fpsusedforemblem, 'N'),
       fpsizebillinggroupid, lv_reservealternativesize, fpsizegroupingcodeid)
    returning sizedefinition_id into fpnsizedefinition_id;
    insert into sizedefinition_link
      (sizedefinition_link_id, sizedefinition_id, code, legacysizecode, systemuser_id, timestamp)
    values
      (fpnsizedefinition_id, fpnsizedefinition_id, fpscode, fpslegacysizecode, lvnsystemuserid,
       sysdate);
  end cfbcreate_sizedefinition;
  procedure cfbcreate_sizedefinition_desc(fpnsizedefinition_id in sizedefinition_desc.sizedefinition_id%type,
                                          fpsdescription       in sizedefinition_desc.description%type) is
  begin
    insert into sizedefinition_desc
      (sizedefinition_id, language_id, systemuser_id, description, timestamp)
    values
      (fpnsizedefinition_id, lvnlanguageid, lvnsystemuserid, nvl(fpsdescription, '-'), sysdate);
    insert into sizedefinition_link_desc
      (sizedefinition_link_id, language_id, description, systemuser_id, timestamp)
    values
      (fpnsizedefinition_id, lvnlanguageid, nvl(fpsdescription, '-'), lvnsystemuserid, sysdate);
  end cfbcreate_sizedefinition_desc;
  procedure cfbcreate_sizespersizetype(fpnsizedefinitionid in sizedefinition.sizedefinition_id%type,
                                       fpnsizetypeid       in sizetype.sizetype_id%type) is
    lvnsequencenumber sizespersizetype.sequencenumber%type;
    lv_sizetype       sizetype.code%type;
    lv_sizecode       sizedefinition.code%type;
  begin
    select sequencenumber
    into   lvnsequencenumber
    from   sizespersizetype
    where  sizetype_id = fpnsizetypeid
    and    sizedefinition_id = fpnsizedefinitionid;
  exception
    when no_data_found then
      begin
        if lvdbcustomercode = 'SMG' then
          begin
            --get size type
            select st.code into lv_sizetype from sizetype st where st.sizetype_id = fpnsizetypeid;
            --get size code for error message
            select s.code
            into   lv_sizecode
            from   sizedefinition s
            where  s.sizedefinition_id = fpnsizedefinitionid;
            --write SMG error message
            pack_import.write_log('Sizetype ' || lv_sizetype || ' for size ' || lv_sizecode ||
                                  ' does not exist, and may not be added!', 3);
          end;
        else
          begin
            --add missing sizespersizetype
            select nvl(max(sequencenumber), 0) + 1
            into   lvnsequencenumber
            from   sizespersizetype
            where  sizetype_id = fpnsizetypeid;
            insert into sizespersizetype
              (sizetype_id, sizedefinition_id, sequencenumber, systemuser_id, timestamp)
            values
              (fpnsizetypeid, fpnsizedefinitionid, lvnsequencenumber, lvnsystemuserid, sysdate);
          end;
        end if;
      end;
  end cfbcreate_sizespersizetype;
  procedure cfbcreate_specialcharge(fpnspecialcharge_id       in out specialcharge.specialcharge_id%type,
                                    fpnfrequency              in specialcharge.frequency%type,
                                    fpsincludininvoiceminimum in specialcharge.includininvoiceminimum%type,
                                    fpdtstartdate             in specialcharge.startdate%type,
                                    fpnnewpercentage          in specialcharge.newpercentage%type,
                                    fpnoldpercentage          in specialcharge.oldpercentage%type,
                                    fpnnewamount              in specialcharge.newamount%type,
                                    fpnoldamount              in specialcharge.oldamount%type,
                                    fpsfixedamount            in specialcharge.fixedamount%type,
                                    fpscode                   in specialcharge.code%type,
                                    fpnturnovergroup_id       in turnovergroup.turnovergroup_id%type,
                                    fpnminamount              in specialcharge.minimumamount%type default null,
                                    fpnmaxamount              in specialcharge.maximumamount%type default null) is
  begin
    insert into specialcharge
      (specialcharge_id, frequency, includininvoiceminimum, startdate, newpercentage, oldpercentage,
       newamount, oldamount, fixedamount, code, turnovergroup_id, systemuser_id, timestamp,
       minimumamount, maximumamount)
    values
      (seq_specialcharge.nextval, fpnfrequency, fpsincludininvoiceminimum, fpdtstartdate,
       fpnnewpercentage, fpnoldpercentage, fpnnewamount, fpnoldamount, fpsfixedamount, fpscode,
       fpnturnovergroup_id, lvnsystemuserid, sysdate, fpnminamount, fpnmaxamount);
    select seq_specialcharge.currval into fpnspecialcharge_id from dual;
  end cfbcreate_specialcharge;
  procedure cfbcreate_specialcharge_desc(fpnspecialcharge_id in specialcharge_desc.specialcharge_id%type,
                                         fpsdescription      in specialcharge_desc.description%type) is
  begin
    insert into specialcharge_desc
      (specialcharge_id, language_id, description, systemuser_id, timestamp)
    values
      (fpnspecialcharge_id, lvnlanguageid, nvl(fpsdescription, '-'), lvnsystemuserid, sysdate);
  end cfbcreate_specialcharge_desc;
  procedure cfbcreate_standarddeliveryline(fpnstandarddeliveryline_id    in out standarddeliveryline.standarddeliveryline_id%type,
                                           fpnstandarddelivery_id        in standarddeliveryline.standarddelivery_id%type,
                                           fpnprodlistperdistribpoint_id in standarddeliveryline.productlistperdistribpoint_id%type,
                                           fpslocation                   in standarddeliveryline.location%type,
                                           fpsremarkforpackinstructions  in standarddeliveryline.remarkforpackinginstructions%type,
                                           fpnseason_id                  in standarddeliveryline.season_id%type,
                                           fpnfixedrentquantity          in standarddeliveryline.fixedrentquantity%type,
                                           fpdtdateactive                in standarddeliveryline.dateactive%type,
                                           fpdtdateinactive              in standarddeliveryline.dateinactive%type,
                                           fpndeliveryscheme_id          in standarddeliveryline.deliveryscheme_id%type,
                                           fpnproductlistpercustomer_id  in standarddeliveryline.productlistpercustomer_id%type,
                                           fpdtrenewalstartdate          in standarddeliveryline.renewalstartdate%type,
                                           fpdtrenewalenddate            in standarddeliveryline.renewalenddate%type,
                                           fpnqtyfreeofcharge            in standarddeliveryline.qtyfreeofcharge%type,
                                           fpnfreeqtyfrequency           in standarddeliveryline.freeqtyfrequency%type default 0) is
    lvnrenewalyn standarddeliveryline.renewal%type;
  begin
    if fpdtrenewalstartdate is null or fpdtrenewalenddate is null then
      lvnrenewalyn := 'N';
    else
      lvnrenewalyn := 'Y';
    end if;
    insert into standarddeliveryline
      (standarddeliveryline_id, standarddelivery_id, productlistperdistribpoint_id, location,
       remarkforpackinginstructions, season_id, fixedrentquantity, dateactive, dateinactive,
       deliveryscheme_id, productlistpercustomer_id, systemuser_id, timestamp, renewal,
       renewalstartdate, renewalenddate, qtyfreeofcharge, freeqtyfrequency)
    values
      (seq_standarddeliveryline.nextval, fpnstandarddelivery_id, fpnprodlistperdistribpoint_id,
       fpslocation, fpsremarkforpackinstructions, fpnseason_id, fpnfixedrentquantity, fpdtdateactive,
       fpdtdateinactive, fpndeliveryscheme_id, fpnproductlistpercustomer_id, lvnsystemuserid,
       sysdate, lvnrenewalyn, fpdtrenewalstartdate, fpdtrenewalenddate, nvl(fpnqtyfreeofcharge, 0),
       nvl(fpnfreeqtyfrequency, 0))
    returning standarddeliveryline_id into fpnstandarddeliveryline_id;
  end cfbcreate_standarddeliveryline;
  procedure cfbcreate_systemuser(fpnsystemuser_id            in out systemuser.systemuser_id%type,
                                 fpnusergroup_id             in systemuser.usergroup_id%type,
                                 fpsusername                 in systemuser.username%type,
                                 fpspassword                 in systemuser.password%type default null,
                                 fpsfullname                 in systemuser.fullname%type default null,
                                 fpsactive                   in systemuser.active%type default 'N',
                                 fpssysadmin                 in systemuser.sysadmin%type default 'N',
                                 fpsremark                   in systemuser.remark%type default null,
                                 fpscontactmanagerfullrights in systemuser.contactmgrfullrights%type default 'N') is
  begin
    insert into systemuser
      (systemuser_id, usergroup_id, language_id, username, password, fullname, active, sysadmin,
       remark, contactmgrfullrights, creditcardauthorised)
    values
      (seq_systemuser.nextval, fpnusergroup_id, lvnlanguageid, fpsusername,
       nvl(fpspassword, 'PFpP3zMAjbw='), nvl(fpsfullname, fpsusername), nvl(fpsactive, 'Y'),
       nvl(fpssysadmin, 'N'), fpsremark, nvl(fpscontactmanagerfullrights, 'N'), 'N')
    returning systemuser_id into fpnsystemuser_id;
  end cfbcreate_systemuser;
  procedure cfbcreate_transportarticle(fpntransportarticle_id     in out transportarticle.transportarticle_id%type,
                                       fpscode                    in transportarticle.code%type,
                                       fpsdefaulttransportarticle in transportarticle.defaulttransportarticle%type,
                                       fpsdescription             in transportarticle_desc.description%type default '-') is
  begin
    insert into transportarticle
      (transportarticle_id, code, defaulttransportarticle, systemuser_id, timestamp)
    values
      (seq_transportarticle.nextval, fpscode, fpsdefaulttransportarticle, lvnsystemuserid, sysdate)
    returning transportarticle_id into fpntransportarticle_id;
    insert into transportarticle_desc
      (transportarticle_id, language_id, systemuser_id, description, timestamp)
    values
      (fpntransportarticle_id, lvnlanguageid, lvnsystemuserid, nvl(fpsdescription, '-'), sysdate);
  end cfbcreate_transportarticle;
  procedure cfbcreate_treatmenttype(fptreatmenttypeid   out treatmenttype.treatmenttype_id%type,
                                    fptreatmenttypecode in treatmenttype.code%type) is
  begin
    select t.treatmenttype_id
    into   fptreatmenttypeid
    from   treatmenttype t
    where  t.code = fptreatmenttypecode;
  exception
    when no_data_found then
      begin
        insert into treatmenttype
          (treatmenttype_id, code, systemuser_id, timestamp)
        values
          (seq_treatmenttype.nextval, fptreatmenttypecode, lvnsystemuserid, sysdate)
        returning treatmenttype_id into fptreatmenttypeid;
      end;
  end cfbcreate_treatmenttype;
  procedure cfbcreate_workorderlinemod(fpnworkorderline_id in workorderlinemodification.workorderline_id%type,
                                       fpnmodification_id  in workorderlinemodification.modification_id%type,
                                       fpnsequencenumber   in workorderlinemodification.sequencenumber%type) is
  begin
    insert into workorderlinemodification
      (workorderline_id, modification_id, sequencenumber, systemuser_id, timestamp)
    values
      (fpnworkorderline_id, fpnmodification_id, fpnsequencenumber, lvnsystemuserid, sysdate);
  end cfbcreate_workorderlinemod;
  --CleanRoomCustomerType
  procedure cfbcreate_cleanroomcustomertype(fpncleanroomcustomertype_id in out cleanroomcustomertype.cleanroomcustomertype_id%type,
                                            fpscode                     in cleanroomcustomertype.code%type,
                                            fpsdescription              in cleanroomcustomertype.description%type,
                                            fpsactive                   in cleanroomcustomertype.active%type default 'Y',
                                            fpssterile                  in cleanroomcustomertype.sterile%type default 'Y') is
  begin
    insert into cleanroomcustomertype
      (cleanroomcustomertype_id,code,description,active,sterile,systemuser_id,timestamp)
    values
      (seq_cleanroomcustomertype.nextval,fpscode,fpsdescription,fpsactive,fpssterile,lvnsystemuserid,sysdate);
    select seq_cleanroomcustomertype.currval
      into fpncleanroomcustomertype_id
      from dual;
  end cfbcreate_cleanroomcustomertype;
  function getcleanroomcustomertype_id(cleanroomcustomertypecode cleanroomcustomertype.code%type)
      return cleanroomcustomertype.cleanroomcustomertype_id%type is
      cleanroomcustomertype_id cleanroomcustomertype.cleanroomcustomertype_id%type;
    begin
      if cleanroomcustomertypecode is null then
        begin
          return null;
        end;
      else
        begin
          select c.cleanroomcustomertype_id
            into cleanroomcustomertype_id
            from cleanroomcustomertype c
           where c.code = cleanroomcustomertypecode;
          return cleanroomcustomertype_id;
        exception
          when no_data_found then
            begin
              pack_import.cfbcreate_cleanroomcustomertype(cleanroomcustomertype_id, cleanroomcustomertypecode,cleanroomcustomertypecode,'Y','Y');
              return cleanroomcustomertype_id;
            exception
              when others then
                return null;
            end;
        end;
      end if;
    end getcleanroomcustomertype_id;
function get_sizebillinggroup(fp_sizebillinggroupcode in sizebillinggroup.code%type,
                                fp_standard             in sizebillinggroup.standard%type)
    return sizebillinggroup.sizebillinggroup_id%type is
    lv_sizebillinggroupid sizebillinggroup.sizebillinggroup_id%type;
    lv_standard           sizebillinggroup.standard%type;
  begin
    --get_sizebillinggroup
    if fp_sizebillinggroupcode is null then
      begin
        lv_sizebillinggroupid := null;
      end;
    else
      begin
        select sbg.sizebillinggroup_id, sbg.standard
        into   lv_sizebillinggroupid, lv_standard
        from   sizebillinggroup sbg
        where  sbg.code = fp_sizebillinggroupcode;
        if nvl(fp_standard, 'N') = 'Y' and lv_standard <> fp_standard then
          begin
            pack_import.write_log('Error sizebillinggroup ' || fp_sizebillinggroupcode ||
                                  ' is not standard! Please check', 3);
          end;
        end if;
      end;
    end if;
    return lv_sizebillinggroupid;
  end get_sizebillinggroup;
begin
  -- Initialization
  select t.code into lvdbcustomercode from databasesettings t;
  get_language;
  if lvnsystemuserid is null then
    begin
      --get usergroup
      select min(usergroup_id) into lvnusergroupid from usergroup;
      begin
        --Select CONVERSION systemuser
        select st.systemuser_id
        into   lvnsystemuserid
        from   systemuser st
        where  st.username = 'CONVERSION';
      exception
        when no_data_found then
          begin
            cfbcreate_systemuser(lvnsystemuserid, lvnusergroupid, 'CONVERSION');
          end;
      end;
      select min(currency_id)
      into   lvncurrencydefaultid
      from   currency c, i_customer i
      where  i.currency = c.code;
      if lvncurrencydefaultid is null then
        select min(currency_id) into lvncurrencydefaultid from currency;
      end if;
      select min(c.country_id)
      into   lvncountrydefaultid
      from   country c, i_customer i
      where  c.code = i.country
      and    c.definetax = 'Y';
      if lvncountrydefaultid is null then
        select min(country_id) into lvncountrydefaultid from country where definetax = 'Y';
      end if;
      if lvncountrydefaultid is null then
        select min(country_id) into lvncountrydefaultid from country;
      end if;
      select min(region_id) into lvnregionid from region;
      select min(division_id) into lvndivisionid from division;
      --create/get the default 'New' quality grade
      getdefaultqualitygradeid;
    end;
  end if;
  --set sorting to faster sorting mechanism
  execute immediate 'alter session set nls_sort=binary';
exception
  when lvnuserexception then
    begin
      raise lvnuserexception;
    end;
  when others then
    begin
      --close_log;
      write_log('Pack_import Error: ' || substr(sqlerrm, 1, 200), 3);
    end;
end pack_import;
/
create or replace package pack_import_artransaction is
  -- Author  : CRISTINA
  -- Created : 18/06/2002 2:44:07 PM
  -- Version : 1.0
  -- Changes : TNE order 500468: add field ExportStatus on Insert in ARTransaction table
  --         : PVD/HVH 03/02/2012 with cashapplication
  procedure cfbimportartransaction;
  procedure cfbimportcashapplication;
end pack_import_artransaction;
/
create or replace package body pack_import_artransaction is
  errormsg varchar2(256);
  ---------------------------------------------------------------------------------
  procedure cfbimportartransaction is
    nartransactionid  artransaction.artransaction_id%type;
    nrouteid          route.route_id%type;
    ninvoicenumber    artransaction.invoicenumber%type;
    nstatusid         status.status_id%type;
    countinsertedrows integer := 0;
    c                 integer;
    errorplace        varchar2(100);
    lv_remitbatchid   remitbatch.remitbatch_id%type;
    function cfbinsertupdateremitbatch(fpbusinessunitid remitbatch.businessunit_id%type,
                                       fpbatchnumber    remitbatch.batchnumber%type,
                                       fpbatchdate      remitbatch.batchdate%type,
                                       fpamount         remitbatch.totalamount%type,
                                       fpstatusid       remitbatch.status_id%type) return number is
      lv_remitbatchid remitbatch.remitbatch_id%type;
    begin
      update remitbatch
      set    totalamount = totalamount + fpamount, systemuser_id = pack_import.lvnsystemuserid,
             timestamp = sysdate
      where  businessunit_id = fpbusinessunitid
      and    batchnumber = fpbatchnumber
      and    batchdate = fpbatchdate
      returning remitbatch_id into lv_remitbatchid;
      if sql%rowcount = 0 then
        insert into remitbatch
          (remitbatch_id, businessunit_id, status_id, batchnumber, batchdate, totalamount,
           systemuser_id, timestamp)
        values
          (seq_remitbatch.nextval, fpbusinessunitid, fpstatusid, fpbatchnumber, fpbatchdate,
           fpamount, pack_import.lvnsystemuserid, sysdate)
        returning remitbatch_id into lv_remitbatchid;
      end if;
      return lv_remitbatchid;
    end cfbinsertupdateremitbatch;
  begin
    --get status
    errorplace := 'init';
    select status_id
    into   nstatusid
    from   status
    where  statustype = 'RB'
    and    code = 1;
    --update wrong artransactions
    errorplace := 'update i_artransaction';
    update i_artransaction set amount = 0 where amount is null;
    update i_artransaction set totalappliedamount = 0 where totalappliedamount is null;
    update i_artransaction set remitidentification = '-' where remitidentification is null;
    update i_artransaction set artransaction_id = null where artransaction_id is not null;
    --update i_artransaction set invoicenumber = null where invoicenumber = 0;
    -- missing AR transaction types
    errorplace := 'missing AR transaction types';
    for vcursor in (select distinct artransactiontype, debitcredit
                    from   i_artransaction a
                    where  not exists (select x.artransactiontype_id
                            from   artransactiontype x
                            where  x.typenumber = a.artransactiontype
                            and    x.debitcredit = a.debitcredit)) loop
      begin
        --insert into artransactiontype
        insert into artransactiontype
          (artransactiontype_id, typenumber, debitcredit, code, predefined, factorydescription,
           systemuser_id, timestamp)
        values
          (seq_artransactiontype.nextval, vcursor.artransactiontype, vcursor.debitcredit,
           seq_artransactiontype.currval, 'N', 'Type ' || vcursor.artransactiontype,
           pack_import.lvnsystemuserid, sysdate);
        --insert into artransactiontype_desc
        insert into artransactiontype_desc
          (artransactiontype_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_artransactiontype.currval, pack_import.lvnlanguageid,
           'Type ' || vcursor.artransactiontype, pack_import.lvnsystemuserid, sysdate);
      end;
    end loop;
    errorplace        := 'insert AR transaction start loop';
    countinsertedrows := 0;
    for vcursor in (select b.customer_id  billto,c.customer_link_id  delto,d.businessunit_id,f.invoiceheader_id,
		    g.artransactiontype_id,a.artransactionno, a.rowid, a.artransactiondate,a.debitcredit,a.remark,
		    a.invoicenumber,a.remitbatchno,a.totalappliedamount,a.routenumber,a.remitidentification,a.amount,
		    a.billtocustomernumber,a.paymenttype,a.artransactiontype,b.currency_id
			from  i_artransaction a
			join customer b
			    on a.billtocustomernumber = b.customernumber
			left join
			    customer_link c
			    ON a.deltocustomernumber = c.customernumber
			join businessunit d
			    on TO_CHAR(a.businessunit) = d.code
			join
			    invoiceheader f
			    on a.invoicenumber = f.invoicenumber
			    and f.invoicebusinessunit_id = d.businessunit_id
			    and f.billtocustomer_link_id = b.customer_id
			join
			    artransactiontype g
			    on a.artransactiontype = g.typenumber
			    and a.debitcredit = g.debitcredit
			where
			    a.artransaction_id is null
			union all
			select
			    b.customer_id  billto,  c.customer_link_id  delto,d.businessunit_id, NULL AS invoiceheader_id,
			    g.artransactiontype_id, a.artransactionno, a.rowid, a.artransactiondate,a.debitcredit, a.remark,
			    a.invoicenumber,  a.remitbatchno,a.totalappliedamount, a.routenumber,a.remitidentification, a.amount,
			    a.billtocustomernumber, a.paymenttype, a.artransactiontype, b.currency_id
			from i_artransaction a
			join customer b
			    ON a.billtocustomernumber = b.customernumber
			left join customer_link c
			    ON a.deltocustomernumber = c.customernumber
			join businessunit d
			    ON TO_CHAR(a.businessunit) = d.code
			join  artransactiontype g
			    ON a.artransactiontype = g.typenumber
			    AND a.debitcredit = g.debitcredit
			where
			    a.artransaction_id is null
			    AND (a.invoicenumber is null
			         or not exists (
			             select 1
			             from invoiceheader h
			             where h.invoicenumber = a.invoicenumber
			               and h.invoicebusinessunit_id = d.businessunit_id
			               and h.billtocustomer_link_id = b.customer_id
			         ))
			) loop
      begin
        nrouteid := null;
        if vcursor.routenumber is not null then
          begin
            errorplace := 'insert AR transaction/route';
            select r.route_id
            into   nrouteid
            from   route r, businessunit u
            where  r.routenumber = vcursor.routenumber
            and    u.businessunit_id = vcursor.businessunit_id
            and    r.plant_id = u.plant_id
            and    getabsdaynumber(vcursor.artransactiondate) = r.drivingday_id;
          exception
            when others then
              begin
                errormsg := 'Warning route ' || to_char(vcursor.routenumber) || ' not found.';
                pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 2);
              end;
          end;
        end if;
        if vcursor.invoicenumber is null then
          ninvoicenumber := 0;
        else
          ninvoicenumber := vcursor.invoicenumber;
        end if;
        -- remit batch
        if vcursor.remitbatchno is not null then
          begin
            errorplace      := 'insert remit batch';
            lv_remitbatchid := cfbinsertupdateremitbatch(vcursor.businessunit_id,
                                                         vcursor.remitbatchno,
                                                         vcursor.artransactiondate, vcursor.amount,
                                                         nstatusid);
          end;
        else
          begin
            lv_remitbatchid := null;
          end;
        end if;
        begin
          begin
            select seq_artransaction.nextval into nartransactionid from dual;
            -- AR transaction
            errorplace := 'insert insert into artransaction 1x';
            insert into artransaction
              (artransaction_id, businessunit_id, billtocustomer_link_id, deltocustomer_link_id,
               artransactiondate, debitcredit, artransactiontype_id, currency_id, amount, totalappliedamount, route_id,
               paymenttype, remitidentification, invoicenumber, invoiceheader_id, closingamount,
               remark, systemuser_id, timestamp, exportstatus, processbusinessunit_id,
               originaltransaction_id, remitbatch_id)
            values
              (nartransactionid, vcursor.businessunit_id, vcursor.billto, vcursor.delto,
               vcursor.artransactiondate, vcursor.debitcredit, vcursor.artransactiontype_id,
               vcursor.currency_id, vcursor.amount, vcursor.totalappliedamount, nrouteid, vcursor.paymenttype,
               vcursor.remitidentification, ninvoicenumber, vcursor.invoiceheader_id, 0,
               vcursor.remark, pack_import.lvnsystemuserid, sysdate, 2, vcursor.businessunit_id,
               nartransactionid, lv_remitbatchid);
          exception
            when dup_val_on_index then
              begin
                if vcursor.debitcredit = 'C' then
                  ninvoicenumber := vcursor.artransactionno;
                end if;
                if vcursor.debitcredit = 'D' then
                  vcursor.remitidentification := vcursor.artransactionno;
                end if;
                errorplace := 'insert into artransaction 2x';
                insert into artransaction
                  (artransaction_id, businessunit_id, billtocustomer_link_id, deltocustomer_link_id,
                   artransactiondate, debitcredit, artransactiontype_id, currency_id, amount, totalappliedamount,
                   route_id, paymenttype, remitidentification, invoicenumber, invoiceheader_id,
                   closingamount, remark, systemuser_id, timestamp, exportstatus,
                   processbusinessunit_id, originaltransaction_id, remitbatch_id)
                values
                  (nartransactionid, vcursor.businessunit_id, vcursor.billto, vcursor.delto,
                   vcursor.artransactiondate, vcursor.debitcredit, vcursor.artransactiontype_id,
                   vcursor.currency_id, vcursor.amount, vcursor.totalappliedamount, nrouteid, vcursor.paymenttype,
                   vcursor.remitidentification, ninvoicenumber, vcursor.invoiceheader_id, 0,
                   vcursor.remark, pack_import.lvnsystemuserid, sysdate, 2, vcursor.businessunit_id,
                   nartransactionid, lv_remitbatchid);
              end;
          end;
          update i_artransaction
          set    artransaction_id = nartransactionid
          where  rowid = vcursor.rowid;
          --count rows
          countinsertedrows := countinsertedrows + 1;
        exception
          when others then
            begin
              errormsg := 'CFbImportARTransaction: Fail to import AR transaction no/date/customer/type/invoicenumber/remitidentification ';
              errormsg := errormsg || vcursor.artransactionno || '/' || vcursor.artransactiondate || '/' ||
                          vcursor.billtocustomernumber || '/' || vcursor.artransactiontype || ' ' ||
                          vcursor.debitcredit || '/' || vcursor.invoicenumber || '/' ||
                          vcursor.remitidentification || ' see debug info';
              pack_import.write_log(errormsg, 3);
              pack_import.write_log(errorplace || chr(10) || sqlerrm, 5);
            end;
        end;
      end;
    end loop;
    if countinsertedrows > 0 then
      begin
        commit;
        pack_import.write_log('Succesfully imported ' || to_char(countinsertedrows) ||
                              ' artransaction records');
      end;
    else
      rollback; --nothing was done anyway..
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('Fail to import AR transaction. ' || errorplace, 3);
        pack_import.write_log('Error: ' || substr(sqlerrm, 1, 200), 3);
      end;
  end cfbimportartransaction;
  ---------------------------------------------------------------------------------
  procedure cfbimportcashapplication is
    lv_counter  number := 0;
    lv_errorcnt number := 0;
  begin
    --cfbimportcashapplication
    for x in (select icash.*, idebit.artransaction_id debit_id, icredit.artransaction_id credit_id
              from   i_cashapplication icash, i_artransaction idebit, i_artransaction icredit
              where  icash.debitartransaction_no = idebit.artransactionno
              and    icash.creditartransaction_no = icredit.artransactionno) loop
      begin
        insert into cashapplication
          (cashapplication_id, debitartransaction_id, creditartransaction_id, applydate,
           applytimestamp, applysystemuser_id, amount, unapplied_yn, unapplydate, unapplytimestamp,
           unapplysystemuser_id, origin)
        values
          (seq_cashapplication.nextval, x.debit_id, x.credit_id, x.applydate, x.applydate,
           pack_import.lvnsystemuserid, x.amount, 'N', null, null, null, 4);
        --update artransaction
        update artransaction d
        set    d.totalappliedamount = d.totalappliedamount + x.amount,
               d.isopen_yn = case
                               when d.totalappliedamount + x.amount = d.amount then
                                'N'
                               else
                                'Y'
                             end, d.timestamp = sysdate,
               d.systemuser_id = pack_import.lvnsystemuserid
        where  d.artransaction_id = x.debit_id;
        --update artransaction
        update artransaction c
        set    c.totalappliedamount = c.totalappliedamount + x.amount,
               c.isopen_yn = case
                               when c.totalappliedamount + x.amount = c.amount then
                                'N'
                               else
                                'Y'
                             end,
               c.originaltransaction_id = case
                                            when c.originaltransaction_id = c.artransaction_id then
                                             x.debit_id
                                            else
                                             c.originaltransaction_id
                                          end, c.timestamp = sysdate,
               c.systemuser_id = pack_import.lvnsystemuserid
        where  c.artransaction_id = x.credit_id;
        lv_counter := lv_counter + 1;
      exception
        when others then
          begin
            lv_errorcnt := lv_errorcnt + 1;
            pack_import.write_log('Error during loop cfbimportcashapplication debit transaction no ' ||
                                  to_char(x.debitartransaction_no) || ' credit transaction no ' ||
                                  to_char(x.creditartransaction_no) ||
                                  ' see debug info error cnt ' || to_char(lv_errorcnt), 3);
            pack_import.write_log('Error during loop cfbimportcashapplication error cnt: ' ||
                                  to_char(lv_errorcnt) || ' ' || sqlerrm, 5);
          end;
      end;
    end loop; --x
    commit;
    if lv_counter > 0 then
      pack_import.write_log('Succesfully imported ' || to_char(lv_counter) ||
                            ' cash application records');
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('Fail to import Cash Application data, see debug info', 3);
        pack_import.write_log('Error cfbimportcashapplication: ' || sqlerrm, 5);
      end;
  end cfbimportcashapplication;
end pack_import_artransaction;
/
create or replace package pack_import_businessunit is
  -- Author  : PVD
  -- Created : 09-Jul-2018
  -- Name    ; Pack_Import_Businessunit
  -- Purpose : Import from I_DEPOT, I_PLANT and I_BUSINESSUNIT
  -- Version : 09-Jul-2018
  --           23-Jul-2018 fix for 1 to N legalentity
  --           13-Mar-2023 ABS-149315 I-tables: extend with ADRESSLINE 3 and 40 characters
  --import_plants
  procedure import_plants;
  -- import_plantproductsettings
  procedure import_plantproductsettings;
  -- import_plantproductsizesettings
  procedure import_plantproductsizesettings;
  --import_depots
  procedure import_depots;
  --import_businesusnits
  procedure import_businesusnits;
  --import_all
  procedure import_all;
end pack_import_businessunit;
/
create or replace package body pack_import_businessunit is
  --global variables
  gv_message abslog.message%type;
  --global functions/procedures
  function create_addressid(fp_street      in address.street%type,
                            fp_street2     in address.street2%type,
                            fp_street3     in address.street3%type,
                            fp_housenumber in address.housenumber%type,
                            fp_city        in address.city%type,
                            fp_zipcode     in address.zipcode%type,
                            fp_state       in address.state%type,
                            fp_county      in address.county%type) return number is
    lv_addressid address.address_id%type;
  begin
    --create_addressid
    insert into address
      (address_id, street, street2, street3, housenumber, zipcode, city, state, county,
       systemuser_id, timestamp)
    values
      (seq_address.nextval, fp_street, fp_street2, fp_street3, nvl(fp_housenumber, 0),
       nvl(fp_zipcode, ' '), nvl(fp_city, ' '), fp_state, fp_county, pack_import.lvnsystemuserid,
       sysdate)
    returning address_id into lv_addressid;
    return lv_addressid;
  exception
    when others then
      begin
        pack_import.write_log(gv_message || ' Fail to create address for street ' || fp_street ||
                              ' house# ' || fp_housenumber || ' zipcode ' || fp_zipcode ||
                              ' city ' || fp_city || ' ' || substr(sqlerrm, 1, 512), 3);
        return null;
      end;
  end create_addressid;
  procedure import_plants is
    lv_tot_count number;
    procedure convert_iplants is
      lv_addressid       address.address_id%type;
      lv_plantid         plant.plant_id%type;
      lv_plants_added    number := 0;
      lv_plants_existing number;
    begin
      --convert_iplants
      for y in (select ipt.*, ct.country_id, l.language_id
                from   i_plant ipt
                join   country ct
                on     ct.code = ipt.plant_country
                join   languages l
                on     l.code = ipt.plant_languagecode
                where  not exists (select 1 from plant pt where pt.code = ipt.plant_code)) loop
        begin
          --create_addressid
          lv_addressid := create_addressid(y.plant_street, y.plant_street2, y.plant_street3,
                                           y.plant_housenumber, y.plant_city, y.plant_zipcode,
                                           y.plant_state, y.plant_county);
          --get plant id
          select seq_plant.nextval into lv_plantid from dual;
          --insert into plant
          insert into plant
            (plant_id, code, name, active, phoneno, systemuser_id, faxno, address_id, language_id,
             headoffice_id, email, country_id, timestamp, financechargepercentage, website,
             creditsqueezeturnovergroup_id, roundingamntturnovergroup_id, timezone)
          values
            (lv_plantid, y.plant_code, y.plant_name, 'Y', y.plant_phoneno,
             pack_import.lvnsystemuserid, y.plant_faxno, lv_addressid, y.language_id, lv_plantid,
             y.plant_email, y.country_id, sysdate, nvl(y.plant_financechargepercent, 0),
             y.plant_website, null, null, y.plant_timezone);
          --count records converted
          lv_plants_added := lv_plants_added + 1;
        end;
      end loop; --y
      --log messages related to conversion, checking converted numbers
      if lv_plants_added > 0 then
        begin
          commit;
          pack_import.write_log(to_char(lv_plants_added) || ' i_plant records converted this run',
                                1);
        end;
      end if;
      if lv_tot_count <> lv_plants_added then
        begin
          select count(1)
          into   lv_plants_existing
          from   i_plant ipt
          where  exists (select 1 from plant pt where pt.code = ipt.plant_code);
          if nvl(lv_plants_existing, 0) = lv_tot_count then
            begin
              pack_import.write_log('i_plant; all plants from i_plant were converted or did already exist',
                                    1);
            end;
          else
            begin
              pack_import.write_log(to_char(lv_tot_count - nvl(lv_plants_existing, 0)) ||
                                    ' i_plant records still to be converted', 2);
            end;
          end if;
        end;
      end if;
    end convert_iplants;
  begin
    --import_plants
    gv_message := 'import_plants';
    select count(1) into lv_tot_count from i_plant ipt;
    if lv_tot_count > 0 then
      begin
        --convert_iplants
        convert_iplants;
        --commit
        commit;
      end;
    end if; --lv_tot_count > 0
  exception
    when others then
      begin
        rollback;
        pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 3);
      end;
  end import_plants;
  procedure import_plantproductsettings is
    lvntreatmentcheckscheme_id treatmentcheckscheme.treatmentcheckscheme_id%type := null;
    lv_rec_added               number := 0;
  begin
    gv_message := 'import_plantproductsettings';
    for y in (select ipps.*, p.plant_id, prod.product_id, w.washingprocess_id, sr.stockroom_id
              from   i_plantproductsettings ipps
              join   plant p
              on     ipps.plant_code = p.code
              join   product prod
              on     prod.code = ipps.productcode
              left   outer join washingprocess w
              on     w.code = ipps.washingprocesscode
              left   outer join stockroom sr
              on     sr.code = ipps.defaultstockroomcode
              where  not exists (select 1
                      from   plantproductsettings pps
                      where  pps.plant_id = p.plant_id
                      and    pps.product_id = prod.product_id)) loop
      begin
        --get lvntreatmentcheckscheme_id
        if y.treatmentcheckschemecode is not null then
          begin
            select tcs.treatmentcheckscheme_id
            into   lvntreatmentcheckscheme_id
            from   treatmentcheckscheme tcs
            where  tcs.code = y.treatmentcheckschemecode;
          exception
            when others then
              begin
                -- this code must already exist in DB will not be created during conversion!
                pack_import.write_log(' treatmentcheck code ' || y.treatmentcheckschemecode ||
                                      ' does not exist.', 3);
              end;
          end;
        else
          lvntreatmentcheckscheme_id := null;
        end if;
        insert into plantproductsettings
          (plant_id, product_id, packingsequence, maxcartqty, systemuser_id, timestamp,
           fulfillmentgroup, fillpercentage, putuptype, active, washingprocess_id,
           treatmentcheckscheme_id, defaultstockroom_id, fixedstockroom, allowrouteassistantadd,
           minapprovalqty, packinggroup, packingproducttype, cleanroombatchpairscan)
        values
          (y.plant_id, y.product_id, y.packingsequence, y.maxcartqty, pack_import.lvnsystemuserid,
           sysdate, y.fulfillmentgroup, y.fillpercentage, y.putuptype, y.active, y.washingprocess_id,
           lvntreatmentcheckscheme_id, y.stockroom_id, y.fixedstockroom, y.allowrouteassistantadd,
           y.minapprovalqty, y.packinggroup, y.packingproducttype, y.cleanroombatchpairscan);
        --count how many records were added
        lv_rec_added := lv_rec_added + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          begin
            gv_message := 'import_plantproductsettings: Fail to import plantproductsettings for plant ' ||
                          y.plant_code || ', product ' || y.productcode;
            pack_import.write_log(gv_message || ' ' || substr(sqlerrm, 1, 512), 3);
          end;
      end;
    end loop;
    if lv_rec_added > 0 then
      begin
        commit;
        pack_import.write_log(to_char(lv_rec_added) ||
                              ' i_plantproductsettings records added this run', 1);
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log(gv_message || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
  end import_plantproductsettings;
  procedure import_plantproductsizesettings is
    lv_rec_added number := 0;
  begin
    gv_message := 'import_plantproductsizesettings';
    for y in (select ippss.*, p.plant_id, prod.product_id, sd.sizedefinition_id, sr.stockroom_id
              from   i_plantproductsizesettings ippss
              join   plant p
              on     ippss.plant_code = p.code
              join   product prod
              on     prod.code = ippss.productcode
              join   sizedefinition sd
              on     sd.code = ippss.sizecode
              left   outer join stockroom sr
              on     sr.code = ippss.defaultstockroomcode
              where  not exists (select 1
                      from   plantproductsizesettings ppss
                      where  ppss.plant_id = p.plant_id
                      and    ppss.product_id = prod.product_id
                      and    ppss.sizedefinition_id = sd.sizedefinition_id)) loop
      begin
        insert into plantproductsizesettings
          (plant_id, product_id, sizedefinition_id, packingamount, systemuser_id, timestamp,
           defaultstockroom_id, fixedstockroom, maxcartqty)
        values
          (y.plant_id, y.product_id, y.sizedefinition_id, y.packingamount,
           pack_import.lvnsystemuserid, sysdate, y.stockroom_id, y.fixedstockroom, y.maxcartqty);
        --count how many records were added
        lv_rec_added := lv_rec_added + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          begin
            gv_message := 'import_plantproductsizesettings: Fail to import plantproductsizesettings for plant ' ||
                          y.plant_code || ', product ' || y.productcode || ', size ' || y.sizecode;
            pack_import.write_log(gv_message || ' ' || substr(sqlerrm, 1, 512), 3);
          end;
      end;
    end loop;
    if lv_rec_added > 0 then
      begin
        commit;
        pack_import.write_log(to_char(lv_rec_added) ||
                              ' i_plantproductsizesettings records added this run', 1);
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log(gv_message || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
  end import_plantproductsizesettings;
  procedure import_depots is
    lv_tot_count number;
    procedure convert_idepots is
      lv_addressid       address.address_id%type;
      lv_depots_added    number := 0;
      lv_depots_existing number;
    begin
      --convert_idepots
      for x in (select idp.*, pt.plant_id
                from   i_depot idp
                join   plant pt
                on     pt.code = idp.plant_code
                where  not exists (select 1
                        from   depot dp
                        where  dp.code = idp.depot_code
                        and    dp.plant_id = pt.plant_id)) loop
        begin
          --log message
          gv_message := 'Depot ' || x.depot_code || ' Plant ' || x.plant_code;
          --create_addressid
          lv_addressid := create_addressid(x.depot_street, x.depot_street2, x.depot_street3,
                                           x.depot_housenumber, x.depot_city, x.depot_zipcode,
                                           x.depot_state, x.depot_county);
          --insert into depot
          insert into depot
            (depot_id, plant_id, code, description, systemuser_id, address_id, timestamp, phoneno,
             faxno)
          values
            (seq_depot.nextval, x.plant_id, x.depot_code, nvl(x.description, x.depot_code),
             pack_import.lvnsystemuserid, lv_addressid, sysdate, x.phoneno, x.faxno);
          --count records converted
          lv_depots_added := lv_depots_added + 1;
        end;
      end loop; --x
      --log messages related to conversion, checking converted numbers
      if lv_depots_added > 0 then
        begin
          commit;
          pack_import.write_log(to_char(lv_depots_added) || ' i_depot records converted this run',
                                1);
        end;
      end if;
      if lv_tot_count <> lv_depots_added then
        begin
          select count(1)
          into   lv_depots_existing
          from   i_depot idp
          join   plant pt
          on     pt.code = idp.plant_code
          where  exists (select 1
                  from   depot dp
                  where  dp.code = idp.depot_code
                  and    dp.plant_id = pt.plant_id);
          if nvl(lv_depots_existing, 0) = lv_tot_count then
            begin
              pack_import.write_log('i_depot; all depots from i_depot were converted or did already exist',
                                    1);
            end;
          else
            begin
              pack_import.write_log(to_char(lv_tot_count - nvl(lv_depots_existing, 0)) ||
                                    ' i_depot records still to be converted', 2);
            end;
          end if;
        end;
      end if;
    end convert_idepots;
  begin
    --import_depots
    gv_message := 'import_depots';
    select count(1) into lv_tot_count from i_depot idp;
    if lv_tot_count > 0 then
      begin
        --convert_idepots
        convert_idepots;
        --commit
        commit;
      end;
    end if; --lv_tot_count > 0
  exception
    when others then
      begin
        rollback;
        pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 3);
      end;
  end import_depots;
  procedure import_businesusnits is
    lv_tot_count      number;
    lv_user_exception exception;
    procedure get_defaults is
      lv_uniqueid number;
    begin
      --get_defaults contactcategory
      gv_message := 'get_defaults contactcategory';
      for a in (select ibu.contactcategory_code code
                from   i_businessunit ibu
                where  ibu.contactcategory_code is not null
                and    not exists
                 (select 1 from contactcategory cc where cc.code = ibu.contactcategory_code)
                group  by ibu.contactcategory_code) loop
        begin
          --insert into contactcategory
          insert into contactcategory
            (contactcategory_id, code, defaultcontactcategory, systemuser_id, timestamp)
          values
            (seq_contactcategory.nextval, a.code, 'N', pack_import.lvnsystemuserid, sysdate)
          returning contactcategory_id into lv_uniqueid;
          --insert into contactcategory_desc
          insert into contactcategory_desc
            (contactcategory_id, language_id, description, systemuser_id, timestamp)
          values
            (lv_uniqueid, pack_import.lvnlanguageid, a.code, pack_import.lvnsystemuserid, sysdate);
        end;
      end loop; --a contactcategory_code
      --get_defaults labellayoutstock
      gv_message := 'get_defaults labellayoutstock';
      for b in (select ibu.labellayoutstock code
                from   i_businessunit ibu
                where  ibu.labellayoutstock is not null
                and    not exists (select 1
                        from   labellayout ll
                        where  ll.code = ibu.labellayoutstock
                        and    ll.labeltype = 1)
                group  by ibu.labellayoutstock) loop
        begin
          insert into labellayout
            (labellayout_id, code, description, labeltype, defaultlayout, systemuser_id, timestamp,
             layoutreceiveonstock, sterile, usedforpool)
          values
            (seq_labellayout.nextval, b.code, b.code, 1, 'N', pack_import.lvnsystemuserid, sysdate,
             'N', 'N', 'N');
        end;
      end loop; --b labellayoutstock
      --get_defaults bundlesortlabellayout
      gv_message := 'get_defaults bundlesortlabellayout';
      for c in (select ibu.bundlesortlabellayout_code code
                from   i_businessunit ibu
                where  ibu.bundlesortlabellayout_code is not null
                and    not exists (select 1
                        from   labellayout ll
                        where  ll.code = ibu.bundlesortlabellayout_code
                        and    ll.labeltype = 1)
                group  by ibu.bundlesortlabellayout_code) loop
        begin
          insert into labellayout
            (labellayout_id, code, description, labeltype, defaultlayout, systemuser_id, timestamp,
             layoutreceiveonstock, sterile, usedforpool)
          values
            (seq_labellayout.nextval, c.code, c.code, 1, 'N', pack_import.lvnsystemuserid, sysdate,
             'N', 'N', 'N');
        end;
      end loop; --c bundlesortlabellayout
      --get_defaults orproductionlabellayout
      gv_message := 'get_defaults bundlesortlabellayout';
      for d in (select ibu.orproductionlabellayout code
                from   i_businessunit ibu
                where  ibu.orproductionlabellayout is not null
                and    not exists (select 1
                        from   labellayout ll
                        where  ll.code = ibu.orproductionlabellayout
                        and    ll.labeltype = 6)
                group  by ibu.orproductionlabellayout) loop
        begin
          insert into labellayout
            (labellayout_id, code, description, labeltype, defaultlayout, systemuser_id, timestamp,
             layoutreceiveonstock, sterile, usedforpool)
          values
            (seq_labellayout.nextval, d.code, d.code, 6, 'N', pack_import.lvnsystemuserid, sysdate,
             'N', 'N', 'N');
        end;
      end loop; --d orproductionlabellayout
      --get_defaults orplantdepartment_code
      gv_message := 'get_defaults bundlesortlabellayout';
      for e in (select ibu.orplantdepartment_code code, pt.plant_id,
                       max(ibu.orplantdepartment_descr) orplantdepartment_descr
                from   i_businessunit ibu
                join   plant pt
                on     pt.code = ibu.plant_code
                where  ibu.orplantdepartment_code is not null
                and    not exists (select 1
                        from   plantdepartment pd
                        where  pd.code = ibu.orplantdepartment_code
                        and    pd.plant_id = pt.plant_id)
                group  by ibu.orplantdepartment_code, pt.plant_id) loop
        begin
          insert into plantdepartment
            (plantdepartment_id, code, description, systemuser_id, plant_id, timestamp,
             defaultplantdepartment)
          values
            (seq_plantdepartment.nextval, e.code, nvl(e.orplantdepartment_descr, e.code),
             pack_import.lvnsystemuserid, e.plant_id, sysdate, 'N');
        end;
      end loop; --e orplantdepartment_code
      --get defaults orcontentsreasoncode
      gv_message := 'get_defaults orcontentsreasoncode';
      for f in (select ibu.orcontentsreasoncode
                from   i_businessunit ibu
                where  ibu.orcontentsreasoncode is not null
                and    not exists
                 (select 1 from reasoncode rs where rs.code = ibu.orcontentsreasoncode)
                group  by ibu.orcontentsreasoncode) loop
        begin
          pack_import.cfbcreate_reasoncode(lv_uniqueid, f.orcontentsreasoncode);
          pack_import.cfbcreate_reasoncode_desc(lv_uniqueid, f.orcontentsreasoncode);
        end;
      end loop; --f orcontentsreasoncode
      --get default region
      gv_message := 'get defaults region';
      for g in (select ibu.region_code
                from   i_businessunit ibu
                where  not exists (select 1 from region rg where rg.code = ibu.region_code)
                group  by ibu.region_code) loop
        begin
          insert into region
            (region_id, code, systemuser_id, timestamp)
          values
            (seq_region.nextval, g.region_code, pack_import.lvnsystemuserid, sysdate)
          returning region_id into lv_uniqueid;
          insert into region_desc
            (region_id, language_id, description, systemuser_id, timestamp)
          values
            (lv_uniqueid, pack_import.lvnlanguageid, g.region_code, pack_import.lvnsystemuserid,
             sysdate);
        end;
      end loop; --g region_code
      --get default division
      gv_message := 'get defaults division';
      for h in (select ibu.division_code
                from   i_businessunit ibu
                where  not exists (select 1 from division dv where dv.code = ibu.division_code)
                group  by ibu.division_code) loop
        begin
          insert into division
            (division_id, code, systemuser_id, timestamp)
          values
            (seq_division.nextval, h.division_code, pack_import.lvnsystemuserid, sysdate)
          returning division_id into lv_uniqueid;
          insert into division_desc
            (division_id, language_id, description, systemuser_id, timestamp)
          values
            (lv_uniqueid, pack_import.lvnlanguageid, h.division_code, pack_import.lvnsystemuserid,
             sysdate);
        end;
      end loop; --h division_code
    end get_defaults;
    procedure convert_ibusinessunits is
      lv_addressid         address.address_id%type;
      lv_legalentityid     legalentity.legalentity_id%type;
      lv_buunits_added     number := 0;
      lv_buunits_existing  number;
      lv_legalentity_added number := 0;
      procedure create_legalentity(fp_code              in legalentity.code%type,
                                   fp_name              in legalentity.name%type,
                                   fp_legalname         in legalentity.legalname%type,
                                   fp_addressid         in legalentity.address_id%type,
                                   fp_countryid         in legalentity.country_id%type,
                                   fp_phone             in legalentity.phone%type,
                                   fp_fax               in legalentity.fax%type,
                                   fp_email             in legalentity.email%type,
                                   fp_website           in legalentity.website%type,
                                   fp_vatnumber         in legalentity.vatnumber%type,
                                   fp_cocnumber         in legalentity.cocnumber%type,
                                   fp_bankinstitutionid in legalentity.bankinstitution_id%type,
                                   fp_active            in legalentity.active%type,
                                   fp_extraname1        in legalentity.extraname1%type,
                                   fp_extraname2        in legalentity.extraname2%type) is
      begin
        --create_legalentity
        select lg.legalentity_id into lv_legalentityid from legalentity lg where lg.code = fp_code;
      exception
        when no_data_found then
          begin
            insert into legalentity
              (legalentity_id, code, name, legalname, address_id, country_id, phone, fax, email,
               website, vatnumber, cocnumber, bankinstitution_id, active, systemuser_id, timestamp,
               extraname1, extraname2)
            values
              (seq_legalentity.nextval, fp_code, coalesce(fp_name, fp_code),
               coalesce(fp_legalname, fp_name, fp_code), fp_addressid, fp_countryid, fp_phone,
               fp_fax, fp_email, fp_website, fp_vatnumber, nvl(fp_cocnumber, 0),
               fp_bankinstitutionid, nvl(fp_active, 'Y'), pack_import.lvnsystemuserid, sysdate,
               fp_extraname1, fp_extraname2)
            returning legalentity_id into lv_legalentityid;
            --count added legalentity
            lv_legalentity_added := lv_legalentity_added + 1;
          end;
      end create_legalentity;
    begin
      --convert_ibusinessunits
      for z in (select ibu.*, pt.plant_id, dv.division_id, rg.region_id,
                       (select cc.contactcategory_id
                         from   contactcategory cc
                         where  cc.code = ibu.contactcategory_code) contactcategory_id,
                       (select su.systemuser_id
                         from   systemuser su
                         where  su.username = ibu.followupuser_name) followupuser_id,
                       (select bi.bankinstitution_id
                         from   bankinstitution bi
                         where  bi.idcode = ibu.defaultbankinst_idcode) defaultbankinstitution_id,
                       (select lbs.labellayout_id
                         from   labellayout lbs
                         where  lbs.code = ibu.labellayoutstock
                         and    lbs.labeltype = 1) labellayoutstock_id,
                       (select lbb.labellayout_id
                         from   labellayout lbb
                         where  lbb.code = ibu.bundlesortlabellayout_code
                         and    lbb.labeltype = 1) bundlesortlabellayout_id,
                       (select lbo.labellayout_id
                         from   labellayout lbo
                         where  lbo.code = ibu.orproductionlabellayout
                         and    lbo.labeltype = 6) orproductionlabellayout_id,
                       (select pdo.plantdepartment_id
                         from   plantdepartment pdo
                         where  pdo.code = ibu.orplantdepartment_code
                         and    pdo.plant_id = pt.plant_id) orplantdepartment_id,
                       (select rs.reasoncode_id
                         from   reasoncode rs
                         where  rs.code = ibu.orcontentsreasoncode) orcontentsreasoncode_id,
                       (select lg.legalentity_id
                         from   legalentity lg
                         where  lg.code = ibu.legalentity_code) legalentity_id,
                       (select bi.bankinstitution_id
                         from   bankinstitution bi
                         where  bi.idcode = ibu.legalentity_bankinst_idcode) legalentity_bankinst_id,
                       nvl((select ct.country_id
                            from   country ct
                            where  ct.code = ibu.legalentity_country), pt.country_id) legalentity_country_id
                from   i_businessunit ibu
                join   plant pt
                on     pt.code = ibu.plant_code
                join   division dv
                on     dv.code = ibu.division_code
                join   region rg
                on     rg.code = ibu.region_code
                where  not exists (select 1 from businessunit bu where bu.code = ibu.businessunit)) loop
        begin
          --Check/create legalentity
          gv_message := 'Legalentity ' || z.legalentity_code || ' for plant code ' || z.plant_code;
          if z.legalentity_code is null then
            begin
              lv_addressid     := null;
              lv_legalentityid := null;
            end;
          else
            begin
              if z.legalentity_id is not null then
                begin
                  lv_legalentityid := z.legalentity_id;
                end;
              else
                begin
                  if z.legalentity_bankinst_id is null then
                    begin
                      gv_message := 'Legalentity ' || z.legalentity_code || ' for plant code ' ||
                                    z.plant_code || ' unknown bankinstitution idcod ' ||
                                    nvl(z.legalentity_bankinst_idcode, 'NULL') || ' please add it';
                      raise lv_user_exception;
                    end;
                  end if;
                  --create new legal entity because if did not yet exist
                  --create_addressid
                  lv_addressid := create_addressid(z.legalentity_street, z.legalentity_street2,
                                                   z.legalentity_street3, z.legalentity_housenumber,
                                                   z.legalentity_city, z.legalentity_zipcode,
                                                   z.legalentity_state, z.legalentity_county);
                  --create_legalentity
                  create_legalentity(z.legalentity_code, z.legalentity_name,
                                     z.legalentity_legalname, lv_addressid, z.legalentity_country_id,
                                     z.legalentity_phone, z.legalentity_fax, z.legalentity_email,
                                     z.legalentity_website, z.legalentity_vatnumber,
                                     z.legalentity_cocnumber, z.legalentity_bankinst_id,
                                     z.legalentity_active, z.legalentity_extraname1,
                                     z.legalentity_extraname2);
                end;
              end if;
            end;
          end if;
          --log message
          gv_message := 'businessunit ' || z.businessunit || ' Plant ' || z.plant_code;
          --insert into businessunit
          insert into businessunit
            (businessunit_id, code, description, division_id, region_id, systemuser_id, timestamp,
             plant_id, ilnnumber, internalvatnumber, vatnumber, labellayoutoutscanactstock_id,
             contactcategory_id, followupuser_id, defaultbankinstitution_id, orservicingbu,
             merchantid, orplantdepartment_id, orproductionlabellayout_id, orcontentsreasoncode_id,
             legalentity_id, bundlesortlabellayout_id)
          values
            (seq_businessunit.nextval, z.businessunit, z.description, z.division_id, z.region_id,
             pack_import.lvnsystemuserid, sysdate, z.plant_id, z.ilnnumber, z.internalvatnumber,
             z.vatnumber, z.labellayoutstock_id, z.contactcategory_id, z.followupuser_id,
             z.defaultbankinstitution_id, nvl(z.orservicingbu, 0), z.merchantid,
             z.orplantdepartment_id, z.orproductionlabellayout_id, z.orcontentsreasoncode_id,
             lv_legalentityid, z.bundlesortlabellayout_id);
          --count records converted
          lv_buunits_added := lv_buunits_added + 1;
        exception
          when lv_user_exception then
            begin
              pack_import.write_log(gv_message, 3);
            end;
          when others then
            begin
              pack_import.write_log(gv_message || ' ' || sqlerrm, 3);
            end;
        end;
      end loop; --x
      --log messages related to conversion, checking converted numbers
      if lv_buunits_added > 0 then
        begin
          commit;
          pack_import.write_log(to_char(lv_buunits_added) ||
                                ' i_businessunit records converted this run', 1);
        end;
      end if;
      if lv_legalentity_added > 0 then
        begin
          pack_import.write_log(to_char(lv_legalentity_added) ||
                                ' legalentity records converted this run', 1);
        end;
      end if;
      if lv_tot_count <> lv_buunits_added then
        begin
          select count(1)
          into   lv_buunits_existing
          from   i_businessunit ibu
          join   plant pt
          on     pt.code = ibu.plant_code
          where  exists (select 1 from businessunit bu where bu.code = ibu.businessunit);
          if nvl(lv_buunits_existing, 0) = lv_tot_count then
            begin
              pack_import.write_log('i_businessunit; all businessunits from i_businessunit were converted or did already exist',
                                    1);
            end;
          else
            begin
              pack_import.write_log(to_char(lv_tot_count - nvl(lv_buunits_existing, 0)) ||
                                    ' i_businessunit records still to be converted', 2);
            end;
          end if;
        end;
      end if;
    end convert_ibusinessunits;
  begin
    --import_businesusnits
    gv_message := 'import_businesusnits';
    select count(1) into lv_tot_count from i_businessunit ibu;
    if lv_tot_count > 0 then
      begin
        --get defaults
        get_defaults;
        --convert_ibusinessunits
        convert_ibusinessunits;
        --commit
        commit;
      end;
    end if; --lv_tot_count > 0
  exception
    when lv_user_exception then
      begin
        rollback;
        pack_import.write_log(gv_message, 3);
      end;
    when others then
      begin
        rollback;
        pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 3);
      end;
  end import_businesusnits;
  procedure import_all is
  begin
    --import_all
    --import_plants
    import_plants;
    --import_depots
    import_depots;
    --import_businesusnits
    import_businesusnits;
    --import_plantproductsettings
    import_plantproductsettings;
    --import_plantproductsizesettings
    import_plantproductsizesettings;
  end import_all;
end pack_import_businessunit;
/
create or replace package pack_import_container is
  -- Author  : PVD
  -- Created : 25-Apr-2005 16:31:46
  -- Version : 1.0
  -- Purpose : Import container/containertype
  procedure cfbimport_container;
end pack_import_container;
/
create or replace package body pack_import_container is
  lverrormsg varchar2(512);
  procedure cfbimport_containertype is
    lvcounter number := 0;
  begin
    --- add all new container types
    for x in (select i.containertype_code, max(i.containertype_desc) containertype_desc,
                     nvl(max(i.containertype_tareweight), 0) containertype_tareweight,
                     nvl(max(i.containertype_disinfect), 'N') containertype_disinfect
              from   i_container i
              where  not exists (select t.containertype_id
                      from   containertype t
                      where  t.code = i.containertype_code)
              group  by i.containertype_code) loop
      begin
        ---insert containertype
        insert into containertype
          (containertype_id, code, defaulttaraweight, systemuser_id, timestamp, active,
           disinfectbeforedelivery)
        values
          (seq_containertype.nextval, x.containertype_code, x.containertype_tareweight,
           pack_import.lvnsystemuserid, sysdate, 'Y', x.containertype_disinfect);
        ---insert containertype_desc
        insert into containertype_desc
          (containertype_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_containertype.currval, pack_import.lvnlanguageid, x.containertype_desc,
           pack_import.lvnsystemuserid, sysdate);
        lvcounter := lvcounter + 1;
      end;
    end loop;
    if lvcounter > 0 then
      pack_import.write_log(lvcounter || ' containertype rows imported.');
    end if;
  exception
    when others then
      begin
        lverrormsg := 'cfbimport_containertype: Failed to import.';
        pack_import.write_log(lverrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_containertype;
  procedure cfbimport_container is
    lvcounter             number := 0;
    lvseccounter          number := 0;
    lvcontainertypeid     containertype.containertype_id%type;
    lvownercustomerid     customer.customer_id%type;
    lvownerbusinessunitid businessunit.businessunit_id%type;
    lvcustomerid          customer.customer_id%type;
    lvdepartmentid        department.department_id%type;
    lvdistributionpointid distributionpoint.distributionpoint_id%type;
    lvstayid              stay.stay_id%type;
  begin
    --- add all new container types
    cfbimport_containertype;
    --- loop containers
    for x in (select i.primaryid, i.secondaryid, i.containertype_code, i.stay,
                     nvl(i.dateactive, trunc(sysdate - 1)) dateactive,
                     nvl(i.dateinactive, to_date('31/12/2099', 'dd/mm/yyyy')) dateinactive,
                     nvl(i.tareweight, 0) tareweight, i.ownercustomernumber, i.ownerbusinessunitcode,
                     nvl(i.usedbyotherbu, 'N') usedbyotherbu, i.customernumber, i.departmentnumber,
                     i.distributionpoint, i.lastinscandate, i.lastoutscandate, i.lastdisinfectiondate,
                     nvl(i.numberofdifinfections, 0) numberofdifinfections,
                     nvl(i.numberofshipments, 0) numberofshipments
              from   i_container i
              where  not exists
               (select c.container_id from container c where c.primaryid = i.primaryid)) loop
      begin
        --- get containertype_id
        lverrormsg := 'error, containertype ' || x.containertype_code;
        select t.containertype_id
        into   lvcontainertypeid
        from   containertype t
        where  t.code = x.containertype_code;
        --- get stay id
        lverrormsg := 'error, stay ' || x.stay;
        select s.stay_id
        into   lvstayid
        from   stay s
        where  s.staynr = x.stay
        and    s.staytype = 2;
        if x.ownercustomernumber > 0 then
          begin
            --- get owner customer id
            lverrormsg := 'error, ownercustomer ' || x.ownercustomernumber;
            select c.customer_id
            into   lvownercustomerid
            from   customer c
            where  c.customernumber = x.ownercustomernumber;
          end;
        end if;
        if x.ownerbusinessunitcode is not null then
          begin
            --- get owner businessunit id
            lverrormsg := 'error, ownerbusinessunitcode ' || x.ownerbusinessunitcode;
            select b.businessunit_id
            into   lvownerbusinessunitid
            from   businessunit b
            where  b.code = x.ownerbusinessunitcode;
          end;
        end if;
        --- get customer_id
        if x.customernumber > 0 then
          begin
            lverrormsg := 'error, customer ' || x.customernumber;
            select c.customer_id
            into   lvcustomerid
            from   customer c
            where  c.customernumber = x.customernumber;
            if x.departmentnumber > 0 then
              begin
                --- get department_id
                lverrormsg := lverrormsg || ' department ' || x.departmentnumber;
                select d.department_id
                into   lvdepartmentid
                from   department d
                where  d.customer_id = lvcustomerid
                and    d.departmentnumber = x.departmentnumber;
                if x.distributionpoint > 0 then
                  begin
                    --- get distributionpoint_id
                    lverrormsg := lverrormsg || ' distributionpoint ' || x.distributionpoint;
                    select p.distributionpoint_id
                    into   lvdistributionpointid
                    from   distributionpoint p
                    where  x.distributionpoint = p.distributionpointnumber
                    and    p.department_id = lvdepartmentid;
                  end;
                else
                  lvdistributionpointid := null;
                end if;
              end;
            else
              begin
                lvdepartmentid        := null;
                lvdistributionpointid := null;
              end;
            end if;
          end;
        else
          begin
            lvcustomerid          := null;
            lvdepartmentid        := null;
            lvdistributionpointid := null;
          end;
        end if;
        --insert container
        insert into container
          (container_id, primaryid, containertype_id, tareweight, ownercustomer_id,
           ownerbusinessunit_id, usedbyotherbu, stay_id, distributionpoint_id, businessunit_id,
           prevstay_id, staychangedate, lastinscandate, lastoutscandate, lastdisinfectiondate,
           lastdistributionpoint_link_id, lastbusinessunit_id, lastnotenumber, numberofdisinfections,
           numberofshipments, numberofdaysatcustprev, dateactive, dateinactive, systemuser_id,
           timestamp)
        values
          (seq_container.nextval, x.primaryid, lvcontainertypeid, x.tareweight, lvownercustomerid,
           lvownerbusinessunitid, x.usedbyotherbu, lvstayid, lvdistributionpointid,
           lvownerbusinessunitid, null, null, x.lastinscandate, x.lastoutscandate,
           x.lastdisinfectiondate, null, null, null, x.numberofdifinfections, x.numberofshipments, 0,
           x.dateactive, x.dateinactive, pack_import.lvnsystemuserid, sysdate);
        if x.secondaryid is not null then
          begin
            --- insert secondary container id
            insert into secondarycontainer
              (container_id, secondaryid, systemuser_id, timestamp)
            values
              (seq_container.currval, x.secondaryid, pack_import.lvnsystemuserid, sysdate);
            lvseccounter := lvseccounter + 1;
          exception
            when dup_val_on_index then
              begin
                lverrormsg := ' warning secondary container id could not be inserted, it already exists ' ||
                              x.secondaryid;
                pack_import.write_log(lverrormsg, 2);
              end;
          end;
        end if;
        lvcounter := lvcounter + 1;
      exception
        when no_data_found then
          begin
            lverrormsg := lverrormsg || ' warning not found, primaryid ' || x.primaryid;
            pack_import.write_log(lverrormsg, 2);
          end;
      end;
    end loop;
    commit;
    if lvcounter > 0 then
      pack_import.write_log(lvcounter || ' container rows imported.');
    end if;
    if lvseccounter > 0 then
      pack_import.write_log(lvseccounter || ' secondary container rows imported.');
    end if;
  exception
    when others then
      begin
        rollback;
        lverrormsg := 'cfbimport_container: Failed to import.';
        pack_import.write_log(lverrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_container;
end pack_import_container;
/
create or replace package pack_import_contract is
  -- Author  : PVD
  -- Created : 05-03-2007
  -- Purpose : Convert customer contract tables
  -- Version : 1.0
  -- Updated : 07-07-2017 added contractproduct
  --           12-07-2017 added contractcomponent
  --           Sept-2018  ABS-70281 Extend Conversion with customer purchase orders
  --                      ABS-70483 Add install dates into the Contract customer table
  --           14-dec-2018 ABS-73322 Extend Conversion with MBYO options ABS-76341
  --           16-Jan-2019 ABS-77461 Conversion contract emblem template
  --           07-Feb-2019 ABS-75638 Contract Compliancy enhancements - Garment charges fields
  --           20-Feb-2019 ABS-78654 add new fields into conversion and change document
  --           02-Apr-2019 ABS-78834 pricelist description not copied for contract price list
  --           14-May-2019 ABS-82145 Conversion of percentages into contract product and PLPC
  --           23-May-2019 ABS-84076 Contract Product/Common compliancy
  --           27-06-2019  ABS-85459 Extend Conversion => contract prep charge
  --           23-02-2021  Added column not to do i_contractemblemtemplate more then once
  --           09-07-2021  ABS-119343 link emblemtemplate there were it did not work before not checking colors
  --           10-10-2022  ABS-141486 Fill contractproduct create date with contract install date
  function get_imageid(fp_imagecode in image.code%type, fp_imagetype in image.imagetype%type)
    return image.image_id%type;
  procedure import_contractcomponent;
  procedure import_contract;
  procedure import_contractcustomer;
  procedure import_contractusergroup;
  procedure import_contractpricelist;
  procedure import_contractprice;
  procedure import_contractproduct;
  procedure import_contractproductqmgroup;
  procedure import_contractpurchaseorder;
  procedure import_contractpocustomer;
  procedure import_contractemblemtemplate;
end pack_import_contract;
/
create or replace package body pack_import_contract is
  gv_message varchar2(256);
  lvnplantid plant.plant_id%type;
  function get_imageid(fp_imagecode in image.code%type, fp_imagetype in image.imagetype%type)
    return image.image_id%type is
    lv_imageid image.image_id%type;
  begin
    if fp_imagecode is null then
      begin
        return null;
      end;
    end if;
    --get_imageid
    gv_message := 'Get image code ' || fp_imagecode || ' for image type  ' || fp_imagetype;
    select ig.image_id
    into   lv_imageid
    from   image ig
    where  ig.code = fp_imagecode
    and    ig.imagetype = fp_imagetype;
    return lv_imageid;
  end get_imageid;
  procedure import_contract_foreignkeys is
    lgainlostreasonid gainlostreason.gainlostreason_id%type;
  begin
    gv_message := ' during import_contract_foreignkeys ';
    --import contract type
    insert into contracttype
      (contracttype_id, code, description, systemuser_id, timestamp)
      select seq_contracttype.nextval, x.code, x.description, pack_import.lvnsystemuserid, sysdate
      from   (select i.contracttypecode code,
                      nvl(max(i.contracttypedesc), i.contracttypecode) description
               from   i_contract i
               where  i.contracttypecode is not null
               and    not exists
                (select t.contracttype_id from contracttype t where t.code = i.contracttypecode)
               group  by i.contracttypecode) x;
    --import user group
    insert into usergroup
      (usergroup_id, groupname, description, active, systemuser_id, timestamp, contactmanageractive,
       singletask)
      select seq_usergroup.nextval, x.usergroupname, x.usergroupname, 'Y',
             pack_import.lvnsystemuserid, sysdate, 'N', 'Y'
      from   (select i.usergroupname
               from   i_contract i
               where  i.usergroupname is not null
               and    not exists
                (select g.usergroup_id from usergroup g where g.groupname = i.usergroupname)
               group  by i.usergroupname) x;
    --import contact person
    --were already converted with i_contactperson. added there first.
    --import gain/lost reason
    for x in (select i.gainreasoncode code,
                     nvl(max(i.gainreasondescription), i.gainreasoncode) description, 'Y' gainreason,
                     'N' lostreason
              from   i_contract i
              where  i.gainreasoncode is not null
              and    not exists (select g.gainlostreason_id
                      from   gainlostreason g
                      where  g.code = i.gainreasoncode)
              group  by i.gainreasoncode
              union
              select i.lostreasoncode code,
                     nvl(max(i.lostreasondescription), i.lostreasoncode) description, 'N' gainreason,
                     'Y' lostreason
              from   i_contract i
              where  i.lostreasoncode is not null
              and    not exists (select g.gainlostreason_id
                      from   gainlostreason g
                      where  g.code = i.lostreasoncode)
              group  by i.lostreasoncode) loop
      begin
        insert into gainlostreason
          (gainlostreason_id, code, systemuser_id, gainreason, timestamp, lostreason)
        values
          (seq_gainlostreason.nextval, x.code, pack_import.lvnsystemuserid, x.gainreason, sysdate,
           x.lostreason)
        returning gainlostreason_id into lgainlostreasonid;
        insert into gainlostreason_desc
          (gainlostreason_id, language_id, description, systemuser_id, timestamp)
        values
          (lgainlostreasonid, pack_import.lvnlanguageid, x.description, pack_import.lvnsystemuserid,
           sysdate);
      exception
        when dup_val_on_index then
          null;
      end;
    end loop;
    --import gain/lost competitor
    insert into competitor
      (competitor_id, code, name, systemuser_id, timestamp)
      select seq_competitor.nextval, y.code, y.name, pack_import.lvnsystemuserid, sysdate
      from   (select x.code, max(x.name) name
               from   (select i.gaincompetitorcode code,
                               nvl(max(i.gaincompetitorname), i.gaincompetitorcode) name
                        from   i_contract i
                        where  i.gaincompetitorcode is not null
                        group  by i.gaincompetitorcode
                        union
                        select i.lostcompetitorcode code,
                               nvl(max(i.lostcompetitorname), i.lostcompetitorcode) name
                        from   i_contract i
                        where  i.lostcompetitorcode is not null
                        group  by i.lostcompetitorcode) x
               group  by x.code) y
      where  not exists (select t.competitor_id from competitor t where t.code = y.code);
    --import agreed price index
    insert into priceindex
      (priceindex_id, code, description, systemuser_id, timestamp)
      select seq_priceindex.nextval, x.code, x.description, pack_import.lvnsystemuserid, sysdate
      from   (select i.agreedpriceindexcode code,
                      nvl(max(i.agreedpriceindexdesc), i.agreedpriceindexcode) description
               from   i_contract i
               where  i.agreedpriceindexcode is not null
               group  by i.agreedpriceindexcode) x
      where  not exists (select p.priceindex_id from priceindex p where p.code = x.code);
    --import not agreed price index
    insert into priceindex
      (priceindex_id, code, description, systemuser_id, timestamp)
      select seq_priceindex.nextval, x.code, x.description, pack_import.lvnsystemuserid, sysdate
      from   (select i.notagreedpriceindexcode code,
                      nvl(max(i.notagreedpriceindexdesc), i.notagreedpriceindexcode) description
               from   i_contract i
               where  i.notagreedpriceindexcode is not null
               group  by i.notagreedpriceindexcode) x
      where  not exists (select p.priceindex_id from priceindex p where p.code = x.code);
    commit;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 3);
      end;
  end import_contract_foreignkeys;
  procedure import_contractcomponent is
    lv_count             number := 0;
    lv_subcount          number := 0;
    lv_firstdaysgradeid  qualitygrade.qualitygrade_id%type;
    lv_firstissuegradeid qualitygrade.qualitygrade_id%type;
    lv_qualitygradeid    qualitygrade.qualitygrade_id%type;
    lv_paymenttermsid    paymentterms.paymentterms_id%type;
    procedure init_contractcomponent is
    begin
      --init_contractcomponent
      lv_count := 0;
      for pt in (select trim(upper(i.paymenttermcode)) paymenttermcode
                 from   i_contractcomponent i
                 where  trim(upper(i.paymenttermcode)) is not null
                 and    not exists
                  (select 1 from paymentterms pt where pt.code = trim(upper(i.paymenttermcode)))
                 group  by trim(upper(i.paymenttermcode))) loop
        begin
          insert into paymentterms
            (defaultpaymentterm, active, code, paymentterms_id, timestamp, systemuser_id,
             netpaymentdays, discountdays, discountdays2, paymentdiscount, paymentdiscount2)
          values
            ('N', 'Y', pt.paymenttermcode, seq_paymentterms.nextval, sysdate,
             pack_import.lvnsystemuserid, 0, 0, 0, 0, 0)
          returning paymentterms_id into lv_paymenttermsid;
          insert into paymentterms_desc
            (paymentterms_id, language_id, description, systemuser_id, timestamp)
          values
            (lv_paymenttermsid, pack_import.lvnlanguageid, pt.paymenttermcode,
             pack_import.lvnsystemuserid, sysdate);
          lv_count := lv_count + 1;
        exception
          when others then
            begin
              pack_import.write_log('init_contractcomponent: Fail to import paymentterms code ' ||
                                    pt.paymenttermcode || ' ' || substr(sqlerrm, 1, 512), 3);
            end;
        end;
      end loop;
      if lv_count > 0 then
        begin
          commit;
          pack_import.write_log(lv_count || ' paymentterm(s) imported.');
          lv_count := 0;
        end;
      end if;
    end init_contractcomponent;
  begin
    --init_contractcomponent
    init_contractcomponent;
    --import_contractcomponent
    for ccc in (select cc.*, c.contract_id, c.startdate, c.enddate,
                       (select a.customer_id
                         from   customer a
                         where  a.customernumber = cc.relatedcustomernumber) relatedcustomer_id,
                       (select g.contract_id
                         from   contractcomponentgrmsettings g
                         where  g.contract_id = c.contract_id) contractcompgrmsettings_id,
                       (select z.contract_id
                         from   contractcomponentgrmcharges z
                         where  z.contract_id = c.contract_id) contractcompgrmcharges_id,
                       (select b.contract_id
                         from   contractcomponentbilling b
                         where  b.contract_id = c.contract_id) contractcompbilling_id,
                       (select p.contract_id
                         from   contractcomponentpayment p
                         where  p.contract_id = c.contract_id) contractcomppayment_id,
                       (select m.contract_id
                         from   contractcomponentmisc m
                         where  m.contract_id = c.contract_id) contractcompmisc_id,
                       (select ma.maatemplateheader_id
                         from   maatemplateheader ma
                         where  ma.code = cc.raatemplateheader) maatemplateheader_id,
                       (select ccp.contract_id
                         from   contractcomponentbgprotection ccp
                         where  ccp.contract_id = c.contract_id) contractcomponentbgprot_id,
                       (select cbc.contractbillingcomments_id
                         from   contractbillingcomments cbc
                         where  cbc.contract_id = c.contract_id) contractbillingcomments_id
                from   i_contractcomponent cc
                join   contract c
                on     c.code = cc.contractcode) loop
      begin
        gv_message := 'Converting i_contractcomponent contract ' || ccc.contractcode;
        if ccc.contractcompgrmsettings_id is null then
          begin
            --get quality grades
            lv_firstdaysgradeid  := pack_import.getqualitygradeid(ccc.firstdaysgrade_code);
            lv_firstissuegradeid := pack_import.getqualitygradeid(ccc.firstissuegrade_code);
            lv_qualitygradeid    := pack_import.getqualitygradeid(ccc.qualitygrade_code);
            --contractcomponentgrmsettings
            if (ccc.allowautomaticsales is not null or ccc.depositstockallowed is not null or
               ccc.chargewashfirstissue is not null or ccc.allowchargereturnrent is not null or
               ccc.returnrentweeks is not null or ccc.allowchargeminrent is not null or
               ccc.minrentweeks is not null or ccc.chargeservicecosts is not null or
               ccc.daysspecialgrade is not null or lv_firstdaysgradeid is not null or
               lv_firstissuegradeid is not null or lv_qualitygradeid is not null or
               ccc.garmentrentspecification is not null) then
              begin
                insert into contractcomponentgrmsettings
                  (contract_id, allowautomaticsales, depositstockallowed, chargewashfirstissue,
                   allowchargereturnrent, returnrentweeks, allowchargeminrent, minrentweeks,
                   chargeservicecosts, daysspecialgrade, firstdaysgrade_id, firstissuegrade_id,
                   qualitygrade_id, systemuser_id, timestamp)
                values
                  (ccc.contract_id, ccc.allowautomaticsales, ccc.depositstockallowed,
                   ccc.chargewashfirstissue, ccc.allowchargereturnrent, ccc.returnrentweeks,
                   ccc.allowchargeminrent, ccc.minrentweeks, ccc.chargeservicecosts,
                   ccc.daysspecialgrade, lv_firstdaysgradeid, lv_firstissuegradeid,
                   lv_qualitygradeid, pack_import.lvnsystemuserid, sysdate);
                --count if something is inserted
                lv_subcount := lv_subcount + 1;
              end;
            end if; --contractcompgrmsettings_id
          end;
        end if;
        if ccc.contractcompgrmcharges_id is null then
          begin
            --contractcomponentgrmcharges
            if (ccc.chargeprepcharge is not null or ccc.customgarmentcharge is not null or
               ccc.useprodsizesurchargepricing is not null or
               ccc.garmentrentspecification is not null or ccc.merchandisebuyoutcharge is not null or
               ccc.variableservices is not null or ccc.chargerepaircog is not null or
               ccc.chargerepairs is not null or ccc.chargelosscharge is not null or
               ccc.chargeresidualvalue is not null or ccc.specialsizecharge = 'Y' or
               ccc.chargeexchangecharge is not null) then
              begin
                insert into contractcomponentgrmcharges
                  (contract_id, chargeprepcharge, systemuser_id, timestamp, customgarmentcharge,
                   useprodsizesurchargepricing, garmentrentspecification, merchandisebuyoutcharge,
                   variableservices, chargerepaircog, chargerepairs, chargelosscharge,
                   chargeresidualvalue, specialsizecharge, chargeexchangecharge)
                values
                  (ccc.contract_id, nvl(ccc.chargeprepcharge, 'N'), pack_import.lvnsystemuserid,
                   sysdate, nvl(ccc.customgarmentcharge, 'N'),
                   nvl(ccc.useprodsizesurchargepricing, 'N'), ccc.garmentrentspecification,
                   ccc.merchandisebuyoutcharge, ccc.variableservices, ccc.chargerepaircog,
                   ccc.chargerepairs, ccc.chargelosscharge, ccc.chargeresidualvalue,
                   nvl(ccc.specialsizecharge, 'N'), ccc.chargeexchangecharge);
                --count if something is inserted
                lv_subcount := lv_subcount + 1;
              end;
            end if;
          end;
        end if; --contractcompgrmcharges_id
        if ccc.contractcompbilling_id is null then
          begin
            --contractcomponentbilling
            if (ccc.invoicefrequency is not null or ccc.minimuminvoiceamount is not null or
               ccc.sendstatement is not null or ccc.statementfrequency is not null or
               ccc.attachinvoicecopies is not null or ccc.statementpercustomer is not null or
               ccc.sendstatementbyemail is not null or ccc.splitinvoicesperactivity is not null or
               ccc.chargelossforpoolitems is not null or
               ccc.chargelossforuniquepooldays is not null) then
              begin
                insert into contractcomponentbilling
                  (contract_id, invoicefrequency_id, minimuminvoiceamount, sendstatement,
                   statementfrequency_id, attachinvoicecopies, statementpercustomer, systemuser_id,
                   timestamp, sendstatementbyemail, splitinvoicesperactivity, chargelossforpoolitems,
                   chargelossforuniquepooldays)
                values
                  (ccc.contract_id, ccc.invoicefrequency, ccc.minimuminvoiceamount,
                   ccc.sendstatement, ccc.statementfrequency, ccc.attachinvoicecopies,
                   ccc.statementpercustomer, pack_import.lvnsystemuserid, sysdate,
                   ccc.sendstatementbyemail, ccc.splitinvoicesperactivity,
                   ccc.chargelossforpoolitems, ccc.chargelossforuniquepooldays);
                --count if something is inserted
                lv_subcount := lv_subcount + 1;
              end;
            end if;
          end;
        end if; --contractcompbilling_id
        if ccc.contractcomppayment_id is null then
          begin
            if ccc.paymenttermcode is null then
              begin
                lv_paymenttermsid := null;
              end;
            else
              begin
                --get payment term
                gv_message := 'payment term code ' || trim(upper(ccc.paymenttermcode));
                select pt.paymentterms_id
                into   lv_paymenttermsid
                from   paymentterms pt
                where  pt.code = trim(upper(ccc.paymenttermcode));
              end;
            end if;
            if (lv_paymenttermsid is not null or ccc.financechargedays is not null or
               ccc.putfinancechargeon is not null) then
              begin
                insert into contractcomponentpayment
                  (contract_id, paymentterms_id, financechargedays, putfinancechargeon,
                   systemuser_id, timestamp)
                values
                  (ccc.contract_id, lv_paymenttermsid, ccc.financechargedays,
                   ccc.putfinancechargeon, pack_import.lvnsystemuserid, sysdate);
                --count if something is inserted
                lv_subcount := lv_subcount + 1;
              end;
            end if;
          end;
        end if; --contractcomppayment_id
        if ccc.contractcompmisc_id is null then
          begin
            --contractcomponentmisc
            if (ccc.customerrelated is not null or ccc.relatedcustomer_id is not null or
               ccc.porequired is not null or ccc.soilcount is not null or
               ccc.internetordering is not null or ccc.autosoilpercentage <> 0 or
               ccc.maatemplateheader_id is not null) then
              begin
                insert into contractcomponentmisc
                  (contract_id, customerrelated, relatedcustomer_link_id, porequired, soilcount,
                   internetordering, systemuser_id, timestamp, autosoilpercentage,
                   raatemplateheader_id)
                values
                  (ccc.contract_id, ccc.customerrelated, ccc.relatedcustomer_id, ccc.porequired,
                   ccc.soilcount, ccc.internetordering, pack_import.lvnsystemuserid, sysdate,
                   nvl(ccc.autosoilpercentage, 0), ccc.maatemplateheader_id);
                --count if something is inserted
                lv_subcount := lv_subcount + 1;
              end;
            end if;
          end;
        end if; --contractcompmisc_id
        if ccc.contractcomponentbgprot_id is null and
           (ccc.materialmaintenancepercentage is not null or ccc.garmentsetup is not null or
           ccc.garmentmaintenance is not null or ccc.garmentlosspercentage > 0 or
           ccc.garmentloss is not null or ccc.garmentrepair is not null or
           ccc.mbyoppercentage is not null or ccc.garmentemblem is not null) then
          begin
            insert into contractcomponentbgprotection
              (contract_id, materialmaintenancepercentage, garmentsetup, garmentmaintenance,
               garmentloss, garmentrepair, systemuser_id, timestamp, mbyoppercentage,
               garmentlosspercentage, garmentemblem)
            values
              (ccc.contract_id, ccc.materialmaintenancepercentage, ccc.garmentsetup,
               ccc.garmentmaintenance, ccc.garmentloss, ccc.garmentrepair,
               pack_import.lvnsystemuserid, sysdate, ccc.mbyoppercentage,
               nvl(ccc.garmentlosspercentage, 100), ccc.garmentemblem);
            --count if something is inserted
            lv_subcount := lv_subcount + 1;
          end;
        end if;
        if ccc.contractbillingcomments_id is null and ccc.invoicebilling_description is not null then
          begin
            insert into contractbillingcomments
              (contractbillingcomments_id, contract_id, type, startdate, enddate, description,
               systemuser_id, timestamp)
            values
              (seq_contractbillingcomments.nextval, ccc.contract_id,
               nvl(ccc.invoicebilling_type, 1), nvl(ccc.invoicebilling_startdate, ccc.startdate),
               nvl(ccc.invoicebilling_enddate, ccc.enddate), ccc.invoicebilling_description,
               pack_import.lvnsystemuserid, sysdate);
            --count if something is inserted
            lv_subcount := lv_subcount + 1;
          end;
        end if;
        if lv_subcount >= 1 then
          begin
            lv_count    := lv_count + 1;
            lv_subcount := 0;
          end;
        end if;
      end;
      begin
        insert into contractcomponentnongrmcharges
          (contract_id, chargeresidualvalue, chargelosscharge, systemuser_id, timestamp)
        values
          (ccc.contract_id, nvl(ccc.nongarmentchargeresidualvalue, 'N'),
           nvl(ccc.nongarmentchargelosscharge, 'N'), pack_import.lvnsystemuserid, sysdate);
      exception
        when others then
          begin
            pack_import.write_log('import_contractcomponent: Fail to import contractcomponentnongrmcharges for conractcode ' ||
                                  ccc.contractcode || ' ' || substr(sqlerrm, 1, 512), 3);
          end;
      end;
    end loop;
    if lv_count > 0 then
      begin
        --output to show how many records are converted
        commit;
        pack_import.write_log(lv_count || ' contract component rows imported.');
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 3);
      end;
  end import_contractcomponent;
  procedure import_contract is
    lcontractconverted      number := 0;
    lcontracttypeid         contracttype.contracttype_id%type;
    lcontactpersonid        contactperson.contactperson_id%type;
    lusergroupid            usergroup.usergroup_id%type;
    lsalesemployeeid        employee.employee_id%type;
    lsalesemployee2id       employee.employee_id%type;
    lsalesleademployeeid    employee.employee_id%type;
    laccountmanagerid       employee.employee_id%type;
    lcustomerid             customer.customer_id%type;
    laddressid              address.address_id%type;
    lcountryid              country.country_id%type;
    lgainreasondid          gainlostreason.gainlostreason_id%type;
    llostreasondid          gainlostreason.gainlostreason_id%type;
    lgaincompetitorid       competitor.competitor_id%type;
    llostcompetitorid       competitor.competitor_id%type;
    lagreedpriceindexid     priceindex.priceindex_id%type;
    lnotagreedpriceindexid  priceindex.priceindex_id%type;
    lplantid                plant.plant_id%type;
    lv_statusid             status.status_id%type;
    lv_currencyid           currency.currency_id%type;
    lv_compliancytemplateid compliancytemplate.compliancytemplate_id%type;
    lv_contractid           contract.contract_id%type;
    lv_contractattributes   boolean;
    procedure get_compliancytemplateid(fp_code in compliancytemplate.code%type) is
    begin
      --get_compliancytemplateid
      select ct.compliancytemplate_id
      into   lv_compliancytemplateid
      from   compliancytemplate ct
      where  ct.code = fp_code;
    exception
      when no_data_found then
        begin
          lv_compliancytemplateid := null;
          pack_import.write_log('Error no data found compliancytemplate code ' || fp_code, 3);
        end;
      when others then
        begin
          lv_compliancytemplateid := null;
          pack_import.write_log('get compliancytemplate code ' || fp_code || ' ' ||
                                substr(sqlerrm, 1, 512), 3);
        end;
    end get_compliancytemplateid;
    procedure createcontractcompliancy(fp_rec_i_contract in i_contract%rowtype) is
      --internal procedure
      procedure insert_contractcompliancy(fp_contractattributeid in contractcompliancy.contractattribute_id%type,
                                          fp_compliancyrule      in contractcompliancy.compliancyrule%type) is
      begin
        --insert_contractcompliancy
        gv_message := 'insert into contractcompliancy fp_contractattributeid ' ||
                      to_char(fp_contractattributeid);
        insert into contractcompliancy
          (contractcompliancy_id, contract_id, contractattribute_id, compliancyrule, systemuser_id,
           timestamp)
        values
          (seq_contractcompliancy.nextval, lv_contractid, fp_contractattributeid, fp_compliancyrule,
           pack_import.lvnsystemuserid, sysdate);
        --insert into compliancygroupattributes
        insert into compliancygroupattributes
          (contract_id, contractattribute_id, systemuser_id, timestamp)
          select lv_contractid, caa.contractattribute_id, pack_import.lvnsystemuserid, sysdate
          from   contractattribute caa
          where  caa.sequencenumber <> 0
          and    exists (select cat.groupnumber
                  from   contractattribute cat
                  where  cat.contractattribute_id = fp_contractattributeid
                  and    cat.groupnumber = caa.groupnumber);
      end insert_contractcompliancy;
    begin
      --createcontractcompliancy from i_contract
      --ContractProductBilling
      if fp_rec_i_contract.common_productbilling_compl is not null then
        begin
          insert_contractcompliancy(100, fp_rec_i_contract.common_productbilling_compl);
        end;
      end if;
      --ContractProductPricing
      if fp_rec_i_contract.common_productpricing_compl is not null then
        begin
          insert_contractcompliancy(101, fp_rec_i_contract.common_productpricing_compl);
        end;
      end if;
      --ContractProductPricing
      if fp_rec_i_contract.common_productlogisti_compl is not null then
        begin
          insert_contractcompliancy(102, fp_rec_i_contract.common_productlogisti_compl);
        end;
      end if;
      --ContractProductMiscellaneous
      if fp_rec_i_contract.common_productmiscell_compl is not null then
        begin
          insert_contractcompliancy(103, fp_rec_i_contract.common_productmiscell_compl);
        end;
      end if;
      --ContractProductBudgetProtection
      if fp_rec_i_contract.common_productbudgetp_compl is not null then
        begin
          insert_contractcompliancy(106, fp_rec_i_contract.common_productbudgetp_compl);
        end;
      end if;
      --EmblemTemplate
      if fp_rec_i_contract.common_emblemtemplate_compl is not null then
        begin
          insert_contractcompliancy(180, fp_rec_i_contract.common_emblemtemplate_compl);
        end;
      end if;
      --WearerFunction
      if fp_rec_i_contract.common_wearerfunction_compl is not null then
        begin
          insert_contractcompliancy(181, fp_rec_i_contract.common_wearerfunction_compl);
        end;
      end if;
    end createcontractcompliancy;
    procedure link_primarycontract2secondary is
      lv_rowcount number := 0;
      procedure ins_contractprimarytoseclink(fp_primarycontractid   in contract.contract_id%type,
                                             fp_secondarycontractid in contract.contract_id%type) is
      begin
        --ins_contractprimarytoseclink
        insert into contractprimarytoseclink
          (secondarycontract_id, primarycontract_id, timestamp, systemuser_id)
        values
          (fp_secondarycontractid, fp_primarycontractid, sysdate, pack_import.lvnsystemuserid);
      exception
        when dup_val_on_index then
          begin
            lv_rowcount := lv_rowcount - 1;
          end;
      end ins_contractprimarytoseclink;
    begin
      --link_primarycontract2secondary
      for y in (select secondarycontract.contract_id secondarycontractid,
                       max(primarycontract.contract_id) primarycontractid
                from   i_contract ic
                join   contract primarycontract
                on     primarycontract.code = ic.primarycontractcode
                join   contract secondarycontract
                on     secondarycontract.code = ic.contractcode
                where  ic.category = 1
                group  by secondarycontract.contract_id) loop
        begin
          --ins_contractprimarytoseclink
          ins_contractprimarytoseclink(y.primarycontractid, y.secondarycontractid);
          lv_rowcount := lv_rowcount + 1;
        end;
      end loop; --y
      if lv_rowcount > 0 then
        begin
          commit;
          pack_import.write_log(lv_rowcount ||
                                ' primary contract(s) linked to secondary contract(s).');
        end;
      end if;
    exception
      when others then
        begin
          rollback;
          pack_import.write_log(' Error linking primary contract to secondary contracts! ' ||
                                substr(sqlerrm, 1, 512), 3);
        end;
    end link_primarycontract2secondary;
  begin
    --import_contract_foreignkeys
    import_contract_foreignkeys;
    commit;
    --get contract status 20 , Approved
    gv_message := 'Status type CO , 20 approved';
    select st.status_id
    into   lv_statusid
    from   status st
    where  st.statustype = 'CO'
    and    st.code = '20';
    --import contracts
    for x in (select * from i_contract) loop
      begin
        --select contracttype
        gv_message := 'import_contract ' || x.contractcode || ' contracttypecode ' ||
                      x.contracttypecode;
        select t.contracttype_id
        into   lcontracttypeid
        from   contracttype t
        where  t.code = x.contracttypecode;
        --select user group
        if x.usergroupname is null then
          lusergroupid := null;
        else
          begin
            gv_message := 'import_contract ' || x.contractcode || ' usergroupname ' ||
                          x.usergroupname;
            select g.usergroup_id
            into   lusergroupid
            from   usergroup g
            where  g.groupname = x.usergroupname;
          end;
        end if; --usergroupname
        --get plant id
        gv_message := 'get plant for customer ' || x.customernumber;
        select max(bu.plant_id)
        into   lplantid
        from   customer c
        join   businessunit bu
        on     bu.businessunit_id = c.defaultbusinessunit_id
        where  c.customernumber = x.customernumber;
        --sales employee
        if x.salesemployeenumber is null and lplantid is not null then
          lsalesemployeeid := null;
        else
          begin
            gv_message := 'get create sales employee ' || x.salesemployeenumber;
            pack_import.cfbgetcreate_employee(lplantid, lsalesemployeeid, x.salesemployeenumber,
                                              x.salesemployeename, null, null, null, null, null,
                                              null, null);
          end;
        end if;
        --sales employee2
        if x.salesemployeenumber2 is null and lplantid is not null then
          lsalesemployee2id := null;
        else
          begin
            gv_message := 'get create sales employee 2 ' || x.salesemployeenumber2;
            pack_import.cfbgetcreate_employee(lplantid, lsalesemployee2id, x.salesemployeenumber2,
                                              x.salesemployeename2, null, null, null, null, null,
                                              null, null);
          end;
        end if;
        --sales lead employee
        if x.salesleademployeenumber is null and lplantid is not null then
          lsalesleademployeeid := null;
        else
          begin
            gv_message := 'get create sales lead employee ' || x.salesleademployeenumber;
            pack_import.cfbgetcreate_employee(lplantid, lsalesleademployeeid,
                                              x.salesleademployeenumber, x.salesleademployeename,
                                              null, null, null, null, null, null, null);
          end;
        end if;
        --account manager
        if x.accountmanagernumber is null and lplantid is not null then
          laccountmanagerid := null;
        else
          begin
            gv_message := 'get create account manager ' || x.accountmanagernumber;
            pack_import.cfbgetcreate_employee(lplantid, laccountmanagerid, x.accountmanagernumber,
                                              x.accountmanagername, null, null, null, null, null,
                                              null, null);
          end;
        end if;
        --customer/owner
        if x.customernumber is null then
          begin
            lcustomerid      := null;
            lcontactpersonid := null;
            --get/create extra owner info
            gv_message := 'import_contract ' || x.contractcode || ' insert into address';
            insert into address
              (address_id, street, zipcode, city, state, county, systemuser_id, timestamp)
            values
              (seq_address.nextval, x.owner_street, x.owner_zipcode, x.owner_city, x.owner_state,
               x.owner_county, pack_import.lvnsystemuserid, sysdate)
            returning address_id into laddressid;
            begin
              select c.country_id
              into   lcountryid
              from   country c
              where  c.code = x.owner_countrycode;
            exception
              when no_data_found then
                begin
                  lcountryid := pack_import.lvncountrydefaultid;
                end;
            end;
          end; --x.customernumber is null then
        else
          begin
            laddressid := null;
            lcountryid := null;
            --get customer
            gv_message := 'get customer ' || x.customernumber;
            select c.customer_id, c.currency_id
            into   lcustomerid, lv_currencyid
            from   customer c
            where  c.customernumber = x.customernumber;
            --contactperson
            if x.customercontactpersonnumber is null then
              lcontactpersonid := null;
            else
              begin
                gv_message := 'Contactperson ' || x.customercontactpersonnumber || ' for customer ' ||
                              x.customernumber;
                select p.contactperson_id
                into   lcontactpersonid
                from   contactperson p
                where  p.customer_id = lcustomerid
                and    p.contactpersonnumber = x.customercontactpersonnumber;
              exception
                when no_data_found then
                  begin
                    lcontactpersonid := null;
                    pack_import.write_log(gv_message || ' not found.', 3);
                  end;
              end;
            end if; --x.customercontactpersonnumber is null then
          end;
        end if; --else x.customernumber is null then
        --gainreason
        if x.gainreasoncode is null then
          lgainreasondid := null;
        else
          begin
            gv_message := 'import_contract ' || x.contractcode || ' gainlostreason ' ||
                          x.gainreasoncode;
            select g.gainlostreason_id
            into   lgainreasondid
            from   gainlostreason g
            where  g.code = x.gainreasoncode;
          end;
        end if;
        --lostreason
        if x.lostreasoncode is null then
          llostreasondid := null;
        else
          begin
            gv_message := 'import_contract ' || x.contractcode || ' lostreasoncode ' ||
                          x.lostreasoncode;
            select g.gainlostreason_id
            into   llostreasondid
            from   gainlostreason g
            where  g.code = x.lostreasoncode;
          end;
        end if;
        --gain competitor
        if x.gaincompetitorcode is null then
          lgaincompetitorid := null;
        else
          begin
            gv_message := 'import_contract ' || x.contractcode || ' competitor ' ||
                          x.gaincompetitorcode;
            select t.competitor_id
            into   lgaincompetitorid
            from   competitor t
            where  t.code = x.gaincompetitorcode;
          end;
        end if;
        --lost competitor
        if x.lostcompetitorcode is null then
          llostcompetitorid := null;
        else
          begin
            gv_message := 'import_contract ' || x.contractcode || ' lostcompetitorcode ' ||
                          x.lostcompetitorcode;
            select t.competitor_id
            into   llostcompetitorid
            from   competitor t
            where  t.code = x.lostcompetitorcode;
          end;
        end if;
        --agreed price index
        gv_message := 'import_contract ' || x.contractcode || ' agreedpriceindexcode ' ||
                      x.agreedpriceindexcode;
        select i.priceindex_id
        into   lagreedpriceindexid
        from   priceindex i
        where  i.code = x.agreedpriceindexcode;
        --not agreed price index
        if x.notagreedpriceindexcode is null then
          lnotagreedpriceindexid := null;
        else
          begin
            gv_message := 'import_contract ' || x.contractcode || ' notagreedpriceindexcode ' ||
                          x.notagreedpriceindexcode;
            select i.priceindex_id
            into   lnotagreedpriceindexid
            from   priceindex i
            where  i.code = x.notagreedpriceindexcode;
          end;
        end if;
        if x.currency is not null then
          begin
            --get lv_currencyid
            gv_message := 'import_contract ' || x.contractcode || ' currency ' ||
                          nvl(x.currency, 'NULL');
            select cu.currency_id into lv_currencyid from currency cu where cu.code = x.currency;
          end;
        end if;
        if trim(x.compliancytemplate_code) is null then
          begin
            lv_compliancytemplateid := null;
          end;
        else
          begin
            --get_compliancytemplateid
            get_compliancytemplateid(x.compliancytemplate_code);
          end;
        end if;
        begin
          --insert contract information
          gv_message := 'import_contract ' || x.contractcode;
          select ct.contract_id into lv_contractid from contract ct where ct.code = x.contractcode;
        exception
          when no_data_found then
            begin
              insert into contract
                (contract_id, code, description, contracttype_id, contractdocument,
                 salesemployee_id, commisionpayablesales, accountmanager_id, commisionpayableaccmgr,
                 customer_link_id, owner, address_id, country_id, cvrnumber, phonenumber, signdate,
                 startdate, enddate, duration, termofnotice, terminationdate, autextensionperiod,
                 contactperson_id, contactpersonname, gainreason_id, gaincompetitor_id,
                 lostreason_id, lostcompetitor_id, startdatepriceincrease, updateevery,
                 previouspriceincrease, nextschedulepriceincrease, agreedpriceindex_id,
                 notagreedpriceindex_id, allownotagreedpricelists, purchaseorder, purchaseordervalue,
                 purchaseorderexpirationdate, estimatedweeklysales, remark, systemuser_id, timestamp,
                 renegotiationdate, warndayspriceincrease, warnpriceincrease, status_id, category,
                 currency_id, email, garmentscontract, salesleademployee_id, salesemployee2_id,
                 salesemployee1percentage, salesemployee2percentage, useprodsizesurchargepricing,
                 allownoncontractproducts, allownoncontractembtemp, allownoncontractwearerfunc,
                 compliancytemplate_id, contractdocumenturl)
              values
                (seq_contract.nextval, x.contractcode, x.contractdescription, lcontracttypeid,
                 x.contractdocument, lsalesemployeeid, x.commissionpayablesalesyn, laccountmanagerid,
                 x.commissionpayableaccmgryn, lcustomerid, x.owner, laddressid, lcountryid,
                 x.cvrnumber, x.phonenumber, x.signdate, x.startdate, x.enddate, x.duration,
                 x.termofnotice, x.terminationdate, x.autextensionperiod, lcontactpersonid,
                 x.contactpersonname, lgainreasondid, lgaincompetitorid, llostreasondid,
                 llostcompetitorid, x.startdatepriceincrease, x.updateevery, x.previouspriceincrease,
                 x.nextscheduledpriceincrease, lagreedpriceindexid, lnotagreedpriceindexid,
                 x.allownotagreedpriceindexyn, x.purchaseorder, x.purchaseordervalue,
                 x.purchaseorderexpirationdate, x.estimatedweeklysales, x.remark,
                 pack_import.lvnsystemuserid, sysdate,
                 nvl(x.renegotiationdate, to_date('31/12/2099', 'DD/MM/YYYY')),
                 nvl(x.warndayspriceincrease, 0), nvl(x.warnpriceincrease, 'N'), lv_statusid,
                 nvl(x.category, 3), lv_currencyid, x.email, nvl(x.garmentscontract, 0),
                 lsalesleademployeeid, lsalesemployee2id, nvl(x.salesemployee1percentage, 0),
                 nvl(x.salesemployee2percentage, 0), nvl(x.useprodsizesurchargepricing, 'N'),
                 nvl(x.allownoncontractproducts, 'Y'), nvl(x.allownoncontractembtemp, 'Y'),
                 nvl(x.allownoncontractwearerfunc, 'Y'), lv_compliancytemplateid,
                 x.contractdocumenturl)
              returning contract_id into lv_contractid;
            end;
        end;
        --createcontractcompliancy
        lv_contractattributes := false;
        for y in (select * from i_contractattribute ica where ica.contractcode = x.contractcode) loop
          begin
            insert into contractcompliancy
              (contractcompliancy_id, contract_id, contractattribute_id, compliancyrule,
               systemuser_id, timestamp)
            values
              (seq_contractcompliancy.nextval, lv_contractid, y.attributeid, y.compliancerule,
               pack_import.lvnsystemuserid, sysdate);
            lv_contractattributes := true;
          exception
            when dup_val_on_index then
              null; --ok already exists
          end;
        end loop;
        if lv_contractattributes = false then
          createcontractcompliancy(x);
        end if;
        if lusergroupid is not null then
          begin
            insert into contractusergroup
              (contract_id, usergroup_id, systemuser_id, timestamp)
            values
              (lv_contractid, lusergroupid, pack_import.lvnsystemuserid, sysdate);
          exception
            when dup_val_on_index then
              null; --ok already exists
          end;
        end if;
        --counter
        lcontractconverted := lcontractconverted + 1;
      exception
        when dup_val_on_index then
          -- do not give message when it already exists
          null;
        when no_data_found then
          begin
            rollback;
            pack_import.write_log('No data found ' || gv_message, 3);
          end;
        when others then
          begin
            rollback;
            pack_import.write_log(gv_message || ' ' || substr(sqlerrm, 1, 512), 3);
          end;
      end;
    end loop;
    commit;
    --output to show how many records are converted
    pack_import.write_log(lcontractconverted || ' contract rows imported.');
    --import_contractcomponent
    import_contractcomponent;
    --import_contractpurchaseorder
    import_contractpurchaseorder;
    --import_contractcustomer
    import_contractcustomer;
    --import_contractusergroup
    import_contractusergroup;
    --import_contractpocustomer
    import_contractpocustomer;
    --link_prinarycontract2secondary
    link_primarycontract2secondary;
    --import_contractemblemtemplate
    import_contractemblemtemplate;
    --commit
    commit;
  exception
    when no_data_found then
      begin
        rollback;
        pack_import.write_log('No data found ' || gv_message, 3);
      end;
    when others then
      begin
        rollback;
        pack_import.write_log(gv_message || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
  end import_contract;
  procedure import_contractcustomer is
    lcustomercontractconverted number := 0;
  begin
    gv_message := ' during import_contractcustomer ';
    for x in (select i.*, c.customer_id, cc.contract_id
              from   i_contractcustomer i
              join   customer c
              on     c.customernumber = i.customernumber
              join   contract cc
              on     cc.code = i.contractcode
              where  not exists (select 1
                      from   contractcustomer cct
                      where  cct.contract_id = cc.contract_id
                      and    cct.customer_link_id = c.customer_id)) loop
      begin
        --customer.contractusage
        --0 = Single customer contract, 1 = Predefined contract
        update customer c
        set    c.contractusage = x.contractusage
        where  c.customer_id = x.customer_id
        and    c.contractusage <> x.contractusage;
        --insert contractcustomer
        insert into contractcustomer
          (contractcustomer_id, contract_id, customer_link_id, startdate, enddate, systemuser_id,
           timestamp, expirationdate, postartdate, installdate)
        values
          (seq_contractcustomer.nextval, x.contract_id, x.customer_id, x.startdate, x.enddate,
           pack_import.lvnsystemuserid, sysdate, x.expirationdate, x.postartdate, x.installdate);
        --counter
        lcustomercontractconverted := lcustomercontractconverted + 1;
      exception
        when others then
          begin
            pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 3);
          end;
      end;
    end loop;
    if lcustomercontractconverted > 0 then
      begin
        commit;
        --output to show how many records are converted
        pack_import.write_log(lcustomercontractconverted || ' customer contract rows imported.');
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 3);
      end;
  end import_contractcustomer;
  procedure import_contractusergroup is
    lv_countrows number := 0;
  begin
    --import contractusergroup
    insert into contractusergroup
      (contract_id, usergroup_id, systemuser_id, timestamp)
      select c.contract_id, u.usergroup_id, pack_import.lvnsystemuserid, sysdate
      from   i_contractusergroup i
      join   contract c
      on     c.code = i.contractcode
      join   usergroup u
      on     u.groupname = i.usergroupname
      where  not exists (select 1
              from   contractusergroup cug
              where  cug.contract_id = c.contract_id
              and    cug.usergroup_id = u.usergroup_id);
    lv_countrows := sql%rowcount;
    if lv_countrows > 0 then
      begin
        commit;
        pack_import.write_log('Contract User group' || to_char(lv_countrows) ||
                              ' records imported');
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('Error import Contractusergroup ' || substr(sqlerrm, 1, 512), 3);
      end;
  end import_contractusergroup;
  procedure import_contractpricelist is
    lcontractpricelistconverted number := 0;
    lcontractid                 contract.contract_id%type;
    lcurrencyid                 currency.currency_id%type;
    lgeneralpricelistid         generalpricelist.generalpricelist_id%type;
  begin
    gv_message := ' during import_contractpricelist ';
    for x in (select *
              from   i_contractpricelist i
              where  not exists (select cpl.contractpricelist_id
                      from   contractpricelist cpl
                      join   generalpricelist l
                      on     l.generalpricelist_id = cpl.generalpricelist_id
                      join   contract c
                      on     c.contract_id = cpl.contract_id
                      where  c.code = i.contractcode
                      and    l.code = i.generalpricelistcode
                      and    l.pricetype = i.generalpricetype)) loop
      begin
        --select contract
        gv_message := ' error getting contract ' || x.contractcode;
        select c.contract_id into lcontractid from contract c where c.code = x.contractcode;
        begin
          --select generalpricelist
          gv_message := ' error getting generalpricelist ' || x.generalpricelistcode;
          select l.generalpricelist_id
          into   lgeneralpricelistid
          from   generalpricelist l
          where  l.code = x.generalpricelistcode
          and    l.pricetype = x.generalpricetype;
          --update the generalpricelist for contract if needed, only for converted generalpricelists
          gv_message := ' error update generalpricelist ' || x.generalpricelistcode;
          update generalpricelist l
          set    l.usage = x.usage,
                 l.priceindexcode = nvl(x.generalpriceindexcode, l.priceindexcode),
                 l.description = nvl(x.pricelistdescription, l.description), l.timestamp = sysdate
          where  l.generalpricelist_id = lgeneralpricelistid
          and    l.systemuser_id = pack_import.lvnsystemuserid
          and    (l.usage <> x.usage or
                l.priceindexcode <> nvl(x.generalpriceindexcode, l.priceindexcode) or
                l.description <> nvl(x.pricelistdescription, l.description));
        exception
          when no_data_found then
            begin
              --select currency
              gv_message := ' error getting generalpricecurrency ' || x.generalpricecurrency;
              select c.currency_id
              into   lcurrencyid
              from   currency c
              where  c.code = x.generalpricecurrency;
              --creating the generalpricelist
              gv_message := ' error creating generalpricelist ' || x.generalpricelistcode;
              pack_import.cfbcreate_generalpricelist(lgeneralpricelistid,
                                                     --fpngeneralpricelist_id,
                                                     x.generalpricetype,
                                                     --fpnpricetype,
                                                     x.generalpricelistcode,
                                                     --fpscode,
                                                     nvl(x.pricelistdescription,
                                                          x.generalpricelistcode),
                                                     --fpsdescription,
                                                     'Y',
                                                     --fpsactive,
                                                     'Y',
                                                     --fpsautopriceupdate,
                                                     x.generalpriceindexcode,
                                                     --fpspriceindexcode,
                                                     lcurrencyid,
                                                     --fpncurrency_id,usage
                                                     x.usage);
            end;
        end;
        --insert contractpricelist
        gv_message := ' error creating contractpricelist ';
        insert into contractpricelist
          (contractpricelist_id, contract_id, generalpricelist_id, startdate, enddate, agreed,
           systemuser_id, timestamp, priority, pricetype)
        values
          (seq_contractpricelist.nextval, lcontractid, lgeneralpricelistid, x.startdate, x.enddate,
           x.agreed, pack_import.lvnsystemuserid, sysdate, x.priority, x.pricetype);
        --counter
        lcontractpricelistconverted := lcontractpricelistconverted + 1;
      exception
        when others then
          begin
            pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 3);
          end;
      end;
    end loop;
    commit;
    if lcontractpricelistconverted > 0 then
      begin
        --output to show how many records are converted
        pack_import.write_log(lcontractpricelistconverted || ' contract pricelists rows imported.');
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 3);
      end;
  end import_contractpricelist;
  procedure import_contractprice is
    lcontractpriceconverted number := 0;
    lcontractid             contract.contract_id%type;
    lv_reasoncode_id        reasoncode.reasoncode_id%type;
  begin
    gv_message := ' during import_contractprice ';
    for x in (select *
              from   i_contractprice i
              where  not exists (select cp.contractprice_id
                      from   contractprice cp, contract c
                      where  cp.contract_id = c.contract_id
                      and    c.code = i.contractcode
                      and    cp.category = i.category)) loop
      begin
        --select contract
        gv_message := ' error getting contract ' || x.contractcode;
        select c.contract_id into lcontractid from contract c where c.code = x.contractcode;
        if x.reasoncode is null then
          lv_reasoncode_id := null;
        else
          begin
            gv_message := 'import_contractprice ' || x.contractcode || ' reasoncode ' ||
                          x.reasoncode;
            select r.reasoncode_id
            into   lv_reasoncode_id
            from   reasoncode r
            where  r.code = x.reasoncode;
          end;
        end if;
        gv_message := ' error creating contractprice ';
        insert into contractprice
          (contractprice_id, contract_id, category, pricetype, reasoncode_id, startdate, price,
           creationuser_id, creationtimestamp, systemuser_id, timestamp)
        values
          (seq_contractprice.nextval, lcontractid, x.category, x.pricetype, lv_reasoncode_id,
           x.startdate, x.price, pack_import.lvnsystemuserid, sysdate, pack_import.lvnsystemuserid,
           sysdate);
        --counter
        lcontractpriceconverted := lcontractpriceconverted + 1;
      exception
        when others then
          begin
            pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 3);
          end;
      end;
    end loop;
    commit;
    if lcontractpriceconverted > 0 then
      begin
        --output to show how many records are converted
        pack_import.write_log(lcontractpriceconverted || ' contractprice rows imported.');
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 3);
      end;
  end import_contractprice;
  procedure import_contractproduct is
    lv_counter number := 0;
    ---internal procedures
    procedure init_contractproduct is
      lv_uniqueid number;
    begin
      --init_contractproduct
      gv_message := 'init_contractproduct';
      --sizedefinition
      gv_message := 'import size';
      for sx in (select icp.sizecode sizecode
                 from   i_contractproduct icp
                 where  not exists (select 1 from sizedefinition s where s.code = icp.sizecode)
                 group  by icp.sizecode) loop
        begin
          pack_import.cfbcreate_sizedefinition(lv_uniqueid, sx.sizecode, 'N', null, null, null, 'N');
          pack_import.cfbcreate_sizedefinition_desc(lv_uniqueid, sx.sizecode);
          lv_counter := lv_counter + 1;
        exception
          when others then
            pack_import.write_log('init_contractproduct: error import sizecode ' || sx.sizecode || ' ' ||
                                  substr(sqlerrm, 1, 512), 3);
        end;
      end loop;
      if lv_counter > 0 then
        begin
          commit;
          pack_import.write_log('contractproduct ' || lv_counter || ' size(s) imported.');
          lv_counter := 0;
        end;
      end if;
      -- sizes per size type, product size
      gv_message := 'import sizes per size type, product size';
      for st in (select p.product_id, s.sizedefinition_id, max(p.sizetype_id) sizetype_id,
                        max(p.packingamount) packingamount,
                        max(p.theoreticalweight) theoreticalweight
                 from   i_contractproduct icp
                 join   product p
                 on     p.code = icp.productcode
                 join   sizedefinition s
                 on     s.code = icp.sizecode
                 where  not exists (select ps.product_id, ps.sizedefinition_id
                         from   productsize ps
                         where  ps.product_id = p.product_id
                         and    ps.sizedefinition_id = s.sizedefinition_id)
                 group  by p.product_id, s.sizedefinition_id) loop
        begin
          -- sizespersizetypesizedefinition_id
          pack_import.cfbcreate_sizespersizetype(st.sizedefinition_id, st.sizetype_id);
          -- product size
          pack_import.cfbcreate_productsize(st.product_id, st.sizedefinition_id, 'N',
                                            st.packingamount, st.theoreticalweight, null);
          lv_counter := lv_counter + 1;
        exception
          when others then
            pack_import.write_log('init_contractproduct: error import product_id/size_id ' ||
                                  to_char(st.product_id) || '/' || to_char(st.sizedefinition_id) ||
                                  substr(sqlerrm, 1, 512), 3);
        end;
      end loop;
      if lv_counter > 0 then
        begin
          commit;
          pack_import.write_log('contractproduct ' || lv_counter || ' productsize(s) imported.');
          lv_counter := 0;
        end;
      end if;
      -- finishing method
      gv_message := 'import finishing method';
      for fx in (select icp.finishingmethod
                 from   i_contractproduct icp
                 where  not exists
                  (select 1 from finishingmethod f where f.code = icp.finishingmethod)
                 group  by icp.finishingmethod
                 order  by icp.finishingmethod) loop
        begin
          insert into finishingmethod
            (finishingmethod_id, code, active, systemuser_id, timestamp)
          values
            (seq_finishingmethod.nextval, fx.finishingmethod, 'Y', pack_import.lvnsystemuserid,
             sysdate)
          returning finishingmethod_id into lv_uniqueid;
          insert into finishingmethod_desc
            (finishingmethod_id, language_id, description, systemuser_id, timestamp)
          values
            (lv_uniqueid, pack_import.lvnlanguageid, fx.finishingmethod,
             pack_import.lvnsystemuserid, sysdate);
          lv_counter := lv_counter + 1;
        exception
          when others then
            pack_import.write_log('init_contractproduct: error import  finishingmethod ' ||
                                  fx.finishingmethod || ' ' || substr(sqlerrm, 1, 512), 3);
        end;
      end loop;
      if lv_counter > 0 then
        begin
          commit;
          pack_import.write_log('contractproduct ' || lv_counter ||
                                ' finishingmethod(s) imported.');
          lv_counter := 0;
        end;
      end if;
      --residualvalue
      gv_message := 'import residualvalue';
      for rx in (select upper(trim(icp.residualvalueschemecode)) residualvalueschemecode
                 from   i_contractproduct icp
                 where  icp.residualvalueschemecode is not null
                 and    not exists
                  (select rs.code
                         from   residualvaluescheme rs
                         where  rs.code = upper(trim(icp.residualvalueschemecode)))
                 group  by upper(trim(icp.residualvalueschemecode))
                 order  by upper(trim(icp.residualvalueschemecode))) loop
        begin
          insert into residualvaluescheme
            (residualvaluescheme_id, code, calculationweeks, systemuser_id, timestamp,
             calculationbasis)
          values
            (seq_residualvaluescheme.nextval, rx.residualvalueschemecode, 1,
             pack_import.lvnsystemuserid, sysdate, 1)
          returning residualvaluescheme_id into lv_uniqueid;
          insert into residualvaluescheme_desc
            (residualvaluescheme_id, language_id, description, systemuser_id, timestamp)
          values
            (lv_uniqueid, pack_import.lvnlanguageid, '-', pack_import.lvnsystemuserid, sysdate);
          lv_counter := lv_counter + 1;
        exception
          when others then
            pack_import.write_log('init_contractproduct: error residualvaluescheme ' ||
                                  rx.residualvalueschemecode || substr(sqlerrm, 1, 512), 3);
        end;
      end loop;
      if lv_counter > 0 then
        begin
          commit;
          pack_import.write_log('contractproduct ' || lv_counter ||
                                ' residualvaluescheme(s) imported.');
          lv_counter := 0;
        end;
      end if;
      --import gain/lost reason
      gv_message := 'import gain/lost reason';
      for gx in (select trim(upper(i.gainreasoncode)) code,
                        nvl(max(i.gainreasondescription), trim(upper(i.gainreasoncode))) description,
                        'Y' gainreason, 'N' lostreason
                 from   i_contractproduct i
                 where  i.gainreasoncode is not null
                 and    not exists (select g.gainlostreason_id
                         from   gainlostreason g
                         where  g.code = trim(upper(i.gainreasoncode)))
                 group  by trim(upper(i.gainreasoncode))
                 union
                 select trim(upper(i.lostreasoncode)) code,
                        nvl(max(i.lostreasondescription), trim(upper(i.lostreasoncode))) description,
                        'N' gainreason, 'Y' lostreason
                 from   i_contractproduct i
                 where  i.lostreasoncode is not null
                 and    not exists (select g.gainlostreason_id
                         from   gainlostreason g
                         where  g.code = trim(upper(i.lostreasoncode)))
                 group  by trim(upper(i.lostreasoncode))) loop
        begin
          insert into gainlostreason
            (gainlostreason_id, code, systemuser_id, gainreason, timestamp, lostreason)
          values
            (seq_gainlostreason.nextval, gx.code, pack_import.lvnsystemuserid, gx.gainreason,
             sysdate, gx.lostreason)
          returning gainlostreason_id into lv_uniqueid;
          insert into gainlostreason_desc
            (gainlostreason_id, language_id, description, systemuser_id, timestamp)
          values
            (lv_uniqueid, pack_import.lvnlanguageid, gx.description, pack_import.lvnsystemuserid,
             sysdate);
          lv_counter := lv_counter + 1;
        exception
          when others then
            pack_import.write_log('init_contractproduct: error gainlostreason ' || gx.code ||
                                  substr(sqlerrm, 1, 512), 3);
        end;
      end loop;
      if lv_counter > 0 then
        begin
          commit;
          pack_import.write_log('contractproduct ' || lv_counter || ' gainlostreason(s) imported.');
          lv_counter := 0;
        end;
      end if;
      --import gain/lost competitor
      gv_message := 'import gain/lost competitor';
      insert into competitor
        (competitor_id, code, name, systemuser_id, timestamp)
        select seq_competitor.nextval, y.code, y.name, pack_import.lvnsystemuserid, sysdate
        from   (select x.code, max(x.name) name
                 from   (select i.gaincompetitorcode code,
                                 nvl(max(i.gaincompetitorname), i.gaincompetitorcode) name
                          from   i_contractproduct i
                          where  i.gaincompetitorcode is not null
                          group  by i.gaincompetitorcode
                          union
                          select i.lostcompetitorcode code,
                                 nvl(max(i.lostcompetitorname), i.lostcompetitorcode) name
                          from   i_contractproduct i
                          where  i.lostcompetitorcode is not null
                          group  by i.lostcompetitorcode) x
                 group  by x.code) y
        where  not exists (select t.competitor_id from competitor t where t.code = y.code);
      lv_counter := sql%rowcount;
      if lv_counter > 0 then
        begin
          commit;
          pack_import.write_log('contractproduct ' || lv_counter || ' competitor(s) imported.');
          lv_counter := 0;
        end;
      end if;
      -- adding salesemployee,1,2
      for sx in (select icp.salesemployeenumber, max(icp.salesemployeename) salesemployeename,
                        pt.plant_id
                 from   i_contractproduct icp
                 join   plant pt
                 on     pt.code = icp.salesemployeeplantcode
                 where  not exists (select e.employee_id
                         from   employee e
                         where  e.employeenumber = icp.salesemployeenumber
                         and    e.plant_id = pt.plant_id)
                 group  by icp.salesemployeenumber, pt.plant_id
                 union
                 select icp.salesemployee2number salesemployeenumber,
                        max(icp.salesemployee2name) salesemployeename, pt2.plant_id
                 from   i_contractproduct icp
                 join   plant pt2
                 on     pt2.code = icp.salesemployee2plantcode
                 where  not exists (select e.employee_id
                         from   employee e
                         where  e.employeenumber = icp.salesemployee2number
                         and    e.plant_id = pt2.plant_id)
                 group  by icp.salesemployee2number, pt2.plant_id) loop
        begin
          pack_import.cfbgetcreate_employee(sx.plant_id, lv_uniqueid, sx.salesemployeenumber,
                                            sx.salesemployeename, null, null, null, null, null, null,
                                            null);
          lv_counter := lv_counter + 1;
        exception
          when others then
            pack_import.write_log('init_contractproduct: error employee ' ||
                                  sx.salesemployeenumber || substr(sqlerrm, 1, 512), 3);
        end;
      end loop;
      if lv_counter > 0 then
        begin
          commit;
          pack_import.write_log('contractproduct ' || lv_counter || ' employee(s) imported.');
          lv_counter := 0;
        end;
      end if;
    exception
      when others then
        begin
          pack_import.write_log('init_contractproduct: ' || gv_message || substr(sqlerrm, 1, 512),
                                3);
          raise;
        end;
    end init_contractproduct;
    procedure process_contractproduct is
      lv_contractproductid     contractproduct.contractproduct_id%type;
      lv_seasontypeid          seasontype.seasontype_id%type;
      lv_residualvalueschemeid residualvaluescheme.residualvaluescheme_id%type;
      lv_salesemployeeid       employee.employee_id%type;
      lv_salesemployee2id      employee.employee_id%type;
      lv_gainreasonid          gainlostreason.gainlostreason_id%type;
      lv_gaincompetitorid      competitor.competitor_id%type;
      lv_lostreasonid          gainlostreason.gainlostreason_id%type;
      lv_lostcompetitorid      competitor.competitor_id%type;
    begin
      --process_contractproduct
      lv_counter := 0;
      gv_message := 'import_contractproduct';
      for x in (select icp.*, c.contract_id, p.product_id, s.sizedefinition_id, f.finishingmethod_id,
                       c.startdate contractstartdate
                from   i_contractproduct icp
                join   contract c
                on     c.code = icp.contractcode
                join   product p
                on     p.code = icp.productcode
                join   sizedefinition s
                on     s.code = icp.sizecode
                join   finishingmethod f
                on     f.code = icp.finishingmethod
                where  not exists (select 1
                        from   contractproduct cp
                        where  cp.contract_id = c.contract_id
                        and    cp.product_id = p.product_id
                        and    cp.sizedefinition_id = s.sizedefinition_id
                        and    cp.finishingmethod_id = f.finishingmethod_id)
                order  by icp.contractcode, icp.productcode, icp.sizecode, icp.finishingmethod) loop
        begin
          --Import loop start
          --insert into contractproduct
          gv_message := 'contractproduct';
          insert into contractproduct
            (contractproduct_id, contract_id, finishingmethod_id, startdate, enddate, systemuser_id,
             timestamp, product_id, sizedefinition_id, released, createddate)
          values
            (seq_contractproduct.nextval, x.contract_id, x.finishingmethod_id, x.startdate,
             x.enddate, pack_import.lvnsystemuserid, sysdate, x.product_id, x.sizedefinition_id,
             nvl(x.released, 'N'), x.contractstartdate)
          returning contractproduct_id into lv_contractproductid;
          --insert into contractproductbilling
          if (x.billingmethod is not null or x.changesperweek is not null or
             x.chargeoveruse is not null or x.rentpriceperfrequency is not null or
             x.chargewashesonlyforcog is not null or x.inventorybillingtype is not null or
             x.minimumturnaround is not null or x.minimumquantity is not null or
             x.minimumfrequency is not null or x.chargelossforpool_yn is not null or
             x.chargelossuniquepooldays is not null or x.priceusage is not null or
             x.chargerentnoreturnpoolafterwks is not null or x.chargerentnotreturned is not null or
             x.percentageafterdepreciation is not null or x.compliancyrulebilling is not null or
             x.invoicefreqrelatedrentprice is not null or x.invwashbasedonsoilcount is not null or
             x.chargewashespack is not null or x.returnstockallowed is not null) then
            begin
              gv_message := 'contractproductbilling';
              insert into contractproductbilling
                (contractproduct_id, billingmethod, changesperweek, chargeoveruse,
                 rentpriceperfrequency, chargewashesonlyforcog, inventorybillingtype,
                 minimumturnaround, minimumquantity, minimumfrequency, chargelossforpool_yn,
                 chargelossuniquepooldays, priceusage, chargerentnoreturnpoolafterwks,
                 chargerentnotreturned, percentageafterdepreciation, invoicefreqrelatedrentprice,
                 invwashbasedonsoilcount, chargewashespack, returnstockallowed, systemuser_id,
                 timestamp, compliancyrule, compliancyrulepricing)
              values
                (lv_contractproductid, x.billingmethod, x.changesperweek, x.chargeoveruse,
                 x.rentpriceperfrequency, x.chargewashesonlyforcog, x.inventorybillingtype,
                 x.minimumturnaround, x.minimumquantity, x.minimumfrequency, x.chargelossforpool_yn,
                 x.chargelossuniquepooldays, x.priceusage, x.chargerentnoreturnpoolafterwks,
                 x.chargerentnotreturned, x.percentageafterdepreciation,
                 x.invoicefreqrelatedrentprice, x.invwashbasedonsoilcount,
                 nvl(x.chargewashespack, 1), x.returnstockallowed, pack_import.lvnsystemuserid,
                 sysdate, x.compliancyrulebilling, x.compliancyrulepricing);
            end;
          end if;
          --season type
          if trim(x.seasontypecode) is null then
            begin
              lv_seasontypeid := null;
            end;
          else
            begin
              gv_message := 'seasontypecode ' || x.seasontypecode;
              pack_import.cfbcreate_seasontype(lv_seasontypeid, trim(x.seasontypecode));
            end;
          end if;
          --residualvalueschemecode
          if x.residualvalueschemecode is null then
            begin
              lv_residualvalueschemeid := null;
            end;
          else
            begin
              gv_message := 'residualvaluescheme ' || x.residualvalueschemecode;
              select rs.residualvaluescheme_id
              into   lv_residualvalueschemeid
              from   residualvaluescheme rs
              where  rs.code = x.residualvalueschemecode;
            end;
          end if;
          --insert into contractproductaddbilling
          if (lv_seasontypeid is not null or x.seasonalrent is not null or
             x.chargewashinactiveseason is not null or lv_residualvalueschemeid is not null or
             x.srcmethod is not null or x.srcpercentagesoilcount is not null or
             x.srcpercentageinventory is not null or x.srcpercentagebilledqty is not null or
             x.deliverreplacementqty is not null or x.srcfrequency is not null or
             x.srcchargerent is not null or x.showfocrentoninvoice is not null or
             x.resetrvuponreissue is not null) then
            begin
              gv_message := 'contractproductaddbilling';
              insert into contractproductaddbilling
                (contractproduct_id, seasontype_id, seasonalrent, chargewashinactiveseason,
                 residualvaluescheme_id, srcmethod, srcpercentagesoilcount, srcpercentageinventory,
                 srcpercentagebilledqty, deliverreplacementqty, srcfrequency, srcchargerent,
                 showfocrentoninvoice, resetrvuponreissue, systemuser_id, timestamp)
              values
                (lv_contractproductid, lv_seasontypeid, x.seasonalrent, x.chargewashinactiveseason,
                 lv_residualvalueschemeid, x.srcmethod, x.srcpercentagesoilcount,
                 x.srcpercentageinventory, x.srcpercentagebilledqty, x.deliverreplacementqty,
                 x.srcfrequency, x.srcchargerent, x.showfocrentoninvoice, x.resetrvuponreissue,
                 pack_import.lvnsystemuserid, sysdate);
            end;
          end if;
          --insert into contractproductorderdelivery
          if (x.delayedevenexchange is not null or x.deedeliveryscheme is not null or
             x.straightevenexchange is not null or x.orderviaweb is not null or
             x.soilcountmethod is not null or x.cleancount is not null or
             x.codeuniquely is not null or x.onsiteinventorycount is not null or
             x.automaticsales is not null or x.customerrelated is not null or
             x.autoreplafterlifetime is not null or x.allowreturntostock is not null or
             x.raggeditemaction is not null or x.autosoilpercentage <> 0 or
             x.compliancyruleorderdelivery is not null) then
            begin
              gv_message := 'contractproductorderdelivery';
              insert into contractproductorderdelivery
                (contractproduct_id, delayedevenexchange, deedeliveryscheme, straightevenexchange,
                 orderviaweb, soilcountmethod, cleancount, codeuniquely, onsiteinventorycount,
                 automaticsales, customerrelated, autoreplafterlifetime, allowreturntostock,
                 raggeditemaction, systemuser_id, timestamp, autosoilpercentage, compliancyrule)
              values
                (lv_contractproductid, x.delayedevenexchange, x.deedeliveryscheme,
                 x.straightevenexchange, x.orderviaweb, x.soilcountmethod, x.cleancount,
                 x.codeuniquely, x.onsiteinventorycount, x.automaticsales, x.customerrelated,
                 x.autoreplafterlifetime, x.allowreturntostock, x.raggeditemaction,
                 pack_import.lvnsystemuserid, sysdate, nvl(x.autosoilpercentage, 0),
                 x.compliancyruleorderdelivery);
            end;
          end if;
          --insert into contractproductbgprotection
          insert into contractproductbgprotection
            (contractproduct_id, garmentsetup, garmentmaintenance, garmentloss, garmentrepair,
             compliancyrule, systemuser_id, timestamp, mmpspecificpercentage, mbyoppercentage,
             garmentlosspercentage, garmentemblem)
          values
            (lv_contractproductid, x.garmentsetup, x.garmentmaintenance, x.garmentloss,
             x.garmentrepair, x.compliancyrulebgprotection, pack_import.lvnsystemuserid, sysdate,
             x.mmpspecificpercentage, x.mbyoppercentage, nvl(x.garmentlosspercentage, 100),
             x.garmentemblem);
          --insert into contractproductimagecare
          if (x.imagecare is not null or x.compliancyruleimagecare is not null) then
            begin
              gv_message := 'contractproductimagecare';
              insert into contractproductimagecare
                (contractproduct_id, compliancyrule, imagecare, systemuser_id, timestamp)
              values
                (lv_contractproductid, x.compliancyruleimagecare, x.imagecare,
                 pack_import.lvnsystemuserid, sysdate);
            end;
          end if;
          --insert into contractproductpricing
          if (x.losschargepercentage is not null or x.srchargepercentage is not null) then
            begin
              gv_message := 'insert into contractproductpricing';
              insert into contractproductpricing
                (contractproduct_id, losschargepercentage, srchargepercentage, systemuser_id,
                 timestamp)
              values
                (lv_contractproductid, nvl(x.losschargepercentage, 100),
                 nvl(x.srchargepercentage, 100), pack_import.lvnsystemuserid, sysdate);
            end;
          end if;
          if x.salesemployeenumber is null then
            begin
              lv_salesemployeeid := null;
            end;
          else
            begin
              --get sales employee 1
              gv_message := 'get sales employee 1 ' || x.salesemployeenumber || ' plant ' ||
                            x.salesemployeeplantcode;
              pack_import.cfbgetcreate_employee(x.salesemployeeplantcode, lv_salesemployeeid,
                                                x.salesemployeenumber, x.salesemployeename, null,
                                                null, null, null, null, null, null);
            end;
          end if;
          if x.salesemployee2number is null then
            begin
              lv_salesemployee2id := null;
            end;
          else
            begin
              --get sales employee 2
              gv_message := 'get sales employee 2 ' || x.salesemployee2number || ' plant ' ||
                            x.salesemployee2plantcode;
              pack_import.cfbgetcreate_employee(x.salesemployee2plantcode, lv_salesemployee2id,
                                                x.salesemployee2number, x.salesemployee2name, null,
                                                null, null, null, null, null, null);
            end;
          end if;
          if x.gainreasoncode is null then
            begin
              lv_gainreasonid := null;
            end;
          else
            begin
              --get gainreason id
              gv_message := 'get gain reason code ' || x.gainreasoncode;
              select glr.gainlostreason_id
              into   lv_gainreasonid
              from   gainlostreason glr
              where  glr.code = x.gainreasoncode;
            end;
          end if;
          if x.lostreasoncode is null then
            begin
              lv_lostreasonid := null;
            end;
          else
            begin
              --get lostreason id
              gv_message := 'get lost reason code ' || x.lostreasoncode;
              select glr.gainlostreason_id
              into   lv_lostreasonid
              from   gainlostreason glr
              where  glr.code = x.lostreasoncode;
            end;
          end if;
          if x.gaincompetitorcode is null then
            begin
              lv_gaincompetitorid := null;
            end;
          else
            begin
              --get gain competitor
              gv_message := 'get gain competitor ' || x.gaincompetitorcode;
              select ct.competitor_id
              into   lv_gaincompetitorid
              from   competitor ct
              where  ct.code = x.gaincompetitorcode;
            end;
          end if;
          if x.lostcompetitorcode is null then
            begin
              lv_lostcompetitorid := null;
            end;
          else
            begin
              --get lost competitor
              gv_message := 'get lost competitor ' || x.lostcompetitorcode;
              select ct.competitor_id
              into   lv_lostcompetitorid
              from   competitor ct
              where  ct.code = x.lostcompetitorcode;
            end;
          end if;
          --insert into contractproductmiscellaneous
          gv_message := 'insert into contractproductmiscellaneous';
          insert into contractproductmiscellaneous
            (contractproduct_id, customcode, customdescription, eannumber, nannumber,
             salesemployee_id, commissionpayable, salesemployee2_id, contractpurchaseorder_id,
             contractpurchaseorderline_id, gainreason_id, gaincompetitor_id, lostreason_id,
             lostcompetitor_id, remark, systemuser_id, timestamp, compliancyrule)
          values
            (lv_contractproductid, x.customcode, x.customdescription, x.eannumber, x.nannumber,
             lv_salesemployeeid, x.commissionpayable, lv_salesemployee2id, null, null,
             lv_gainreasonid, lv_gaincompetitorid, lv_lostreasonid, lv_lostcompetitorid, x.remark,
             pack_import.lvnsystemuserid, sysdate, x.compliancyrulemisc);
          --count converted contractproducts
          lv_counter := lv_counter + 1;
        exception
          when others then
            begin
              pack_import.write_log('process_contractproduct: error ' || gv_message || ' ' ||
                                    substr(sqlerrm, 1, 512), 3);
            end;
        end;
      end loop;
    end process_contractproduct;
    procedure final_contractproduct is
    begin
      --final_contractproduct
      gv_message := 'final_contractproduct';
      if lv_counter > 0 then
        begin
          commit;
          pack_import.write_log(lv_counter || ' contract product rows imported.');
        end;
      end if;
    end final_contractproduct;
  begin
    --main procedure import_contractproduct
    --init_contractproduct
    init_contractproduct;
    --process_contractproduct
    process_contractproduct;
    --final_contractproduct
    final_contractproduct;
    --import_contractproductqmgroup
    import_contractproductqmgroup;
    --commit
    commit;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 3);
      end;
  end import_contractproduct;
  procedure import_contractproductqmgroup is
    lv_counter number := 0;
    ---internal procedures
    procedure process_contractproductqmgroup is
      lv_contractqmgroupid contractqmgroup.contractqmgroup_id%type;
    begin
      --process_contractproduct
      lv_counter := 0;
      gv_message := 'import_contractproduct';
      for x in (select icpq.*, cp.contractproduct_id, c.contract_id
                from   i_contractproductqmgroup icpq
                join   contract c
                on     c.code = icpq.contractcode
                join   product p
                on     p.code = icpq.productcode
                join   sizedefinition s
                on     s.code = icpq.sizecode
                join   finishingmethod f
                on     f.code = icpq.finishingmethod
                join   contractproduct cp
                on     (cp.contract_id = c.contract_id and cp.product_id = p.product_id and
                       cp.sizedefinition_id = s.sizedefinition_id and
                       cp.finishingmethod_id = f.finishingmethod_id)
                order  by icpq.contractcode, icpq.productcode, icpq.sizecode, icpq.finishingmethod) loop
        begin
          --Import loop start
          --insert into contractqmgroup
          gv_message := 'contractqmgroup';
          begin
            select cqg.contractqmgroup_id
            into   lv_contractqmgroupid
            from   contractqmgroup cqg
            where  cqg.contract_id = x.contract_id
            and    cqg.code = x.contractqmgrpcode;
          exception
            when no_data_found then
              begin
                insert into contractqmgroup
                  (contractqmgroup_id, contract_id, code, description, systemuser_id, timestamp)
                values
                  (seq_contractqmgroup.nextval, x.contract_id, x.contractqmgrpcode,
                   x.contractqmgrpdesc, pack_import.lvnsystemuserid, sysdate)
                returning contractqmgroup_id into lv_contractqmgroupid;
              end;
          end;
          --insert into CONTRACTPRODUCTQMGLIMIT
          gv_message := 'CONTRACTPRODUCTQMGLIMIT';
          begin
            insert into contractproductqmglimit
              (contractproductqmglimit_id, contractproduct_id, contractqmgroup_id,
               maxcirculatinginventory, maxbillingquantity, maxdeliveryquantity, systemuser_id,
               timestamp)
            values
              (seq_contractproductqmglimit.nextval, x.contractproduct_id, lv_contractqmgroupid,
               x.maxcirculatinginventory, x.maxbillingquantity, x.maxdeliveryquantity,
               pack_import.lvnsystemuserid, sysdate);
          exception
            when dup_val_on_index then
              null;
            when others then
              pack_import.write_log('import_contractproductqmgroup: fail to create CONTRACTPRODUCTQMGLIMIT ' ||
                                    substr(sqlerrm, 1, 512), 3);
          end;
        exception
          when others then
            begin
              pack_import.write_log('process_contractproductqmgroup: error ' || gv_message || ' ' ||
                                    substr(sqlerrm, 1, 512), 3);
            end;
        end;
      end loop;
    end process_contractproductqmgroup;
    procedure final_contractproductqmgrp is
    begin
      --final_contractproduct
      gv_message := 'final_contractproductqmgroup';
      if lv_counter > 0 then
        begin
          commit;
          pack_import.write_log(lv_counter || ' contractproduct QM Group rows imported.');
        end;
      end if;
    end final_contractproductqmgrp;
  begin
    --main procedure import_contractproductqmgroup
    --process_contractproductqmgroup
    process_contractproductqmgroup;
    --final_contractproductqmgrp
    final_contractproductqmgrp;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 3);
      end;
  end import_contractproductqmgroup;
  procedure import_contractpurchaseorder is
    lv_contractid              contract.contract_id%type;
    lv_businessunitid          businessunit.businessunit_id%type;
    lv_contractpurchaseorderid contractpurchaseorder.contractpurchaseorder_id%type;
    lv_headercount             number := 0;
    lv_linecount               number := 0;
    procedure get_create_contractpo(fp_rec_i_contractpo in i_contractpurchaseorder%rowtype) is
    begin
      --get_create_contractpo
      gv_message := 'get_create_contractpo contract ' || fp_rec_i_contractpo.contractcode || ' PO ' ||
                    fp_rec_i_contractpo.purchaseordernumber;
      select cpo.contractpurchaseorder_id
      into   lv_contractpurchaseorderid
      from   contractpurchaseorder cpo
      where  cpo.contract_id = lv_contractid
      and    cpo.purchaseordernumber = fp_rec_i_contractpo.purchaseordernumber;
    exception
      when no_data_found then
        begin
          insert into contractpurchaseorder
            (contractpurchaseorder_id, contract_id, purchaseordernumber, startdate, expirationdate,
             value, invoicedamount, warnpercentage, warndays, closeaction, maxpercentage,
             invoicelinetypesperpo, businessunit_id, systemuser_id, timestamp, manualpo,
             singlecustomerpo)
          values
            (seq_contractpurchaseorder.nextval, lv_contractid,
             fp_rec_i_contractpo.purchaseordernumber, fp_rec_i_contractpo.startdate,
             fp_rec_i_contractpo.expirationdate, fp_rec_i_contractpo.value,
             fp_rec_i_contractpo.invoicedamount, fp_rec_i_contractpo.warnpercentage,
             fp_rec_i_contractpo.warndays, fp_rec_i_contractpo.closeaction,
             fp_rec_i_contractpo.maxpercentage, fp_rec_i_contractpo.invoicelinetypesperpo,
             lv_businessunitid, pack_import.lvnsystemuserid, sysdate, fp_rec_i_contractpo.manualpo,
             fp_rec_i_contractpo.singlecustomerpo)
          returning contractpurchaseorder_id into lv_contractpurchaseorderid;
          --count header insert
          lv_headercount := lv_headercount + 1;
        end;
    end get_create_contractpo;
    procedure create_contractpoline(fp_contractcode        in i_contractpurchaseorder.contractcode%type,
                                    fp_purchaseordernumber in i_contractpurchaseorder.purchaseordernumber%type) is
      lv_customerid                  customer.customer_id%type;
      lv_productid                   product.product_id%type;
      lv_sizeid                      sizedefinition.sizedefinition_id%type;
      lv_finishingmethodid           finishingmethod.finishingmethod_id%type;
      lv_wearerid                    wearer.wearer_id%type;
      lv_contractpurchaseorderlineid contractpurchaseorderline.contractpurchaseorderline_id%type;
    begin
      --create_contractpoline
      gv_message := 'create_contractpoline';
      for ycpol in (select cpol.*
                    from   i_contractpurchaseorderline cpol
                    where  cpol.contractcode = fp_contractcode
                    and    cpol.purchaseordernumber = fp_purchaseordernumber
                    order  by cpol.linenumber, cpol.customernumber, cpol.productcode) loop
        begin
          --get customer id
          gv_message := 'create_contractpoline customer ' || ycpol.customernumber;
          select c.customer_id
          into   lv_customerid
          from   customer c
          where  c.customernumber = ycpol.customernumber;
          --get product id
          gv_message := 'create_contractpoline product ' || ycpol.productcode;
          select p.product_id into lv_productid from product p where p.code = ycpol.productcode;
          --get size id
          gv_message := 'create_contractpoline size ' || ycpol.sizecode;
          select s.sizedefinition_id
          into   lv_sizeid
          from   sizedefinition s
          where  s.code = ycpol.sizecode;
          --get finishingmethod id
          if ycpol.finishingmethod is null then
            begin
              lv_finishingmethodid := null;
            end;
          else
            begin
              gv_message := 'create_contractpoline finishingmethod ' || ycpol.finishingmethod;
              select f.finishingmethod_id
              into   lv_finishingmethodid
              from   finishingmethod f
              where  f.code = ycpol.finishingmethod;
            end;
          end if;
          --wearer
          if ycpol.wearernumber is null then
            begin
              lv_wearerid := null;
            end;
          else
            begin
              gv_message := 'create_contractpoline customer ' || ycpol.customernumber || ' wearer ' ||
                            ycpol.wearernumber;
              select w.wearer_id
              into   lv_wearerid
              from   wearer w
              where  w.customer_id = lv_customerid
              and    w.wearernumber = ycpol.wearernumber;
            end;
          end if;
          --see if it already exists if so, do not create nor update it!
          select max(cpol.contractpurchaseorderline_id)
          into   lv_contractpurchaseorderlineid
          from   contractpurchaseorderline cpol
          where  cpol.contractpurchaseorder_id = lv_contractpurchaseorderid
          and    cpol.customer_link_id = lv_customerid
          and    cpol.product_link_id = lv_productid
          and    cpol.sizedefinition_link_id = lv_sizeid
          and    (cpol.finishingmethod_id = lv_finishingmethodid or
                (cpol.finishingmethod_id is null and lv_finishingmethodid is null))
          and    (cpol.wearer_id = lv_wearerid or (cpol.wearer_id is null and lv_wearerid is null));
          if lv_contractpurchaseorderlineid is null then
            begin
              --insert into contractpurchaseorderline
              gv_message := 'create_contractpoline, insert into contractpurchaseorderline';
              insert into contractpurchaseorderline
                (contractpurchaseorderline_id, contractpurchaseorder_id, linenumber,
                 customer_link_id, product_link_id, sizedefinition_link_id, finishingmethod_id,
                 wearer_id, quantity, price, systemuser_id, timestamp)
              values
                (seq_contractpurchaseorderline.nextval, lv_contractpurchaseorderid,
                 ycpol.linenumber, lv_customerid, lv_productid, lv_sizeid, lv_finishingmethodid,
                 lv_wearerid, ycpol.quantity, ycpol.price, pack_import.lvnsystemuserid, sysdate);
              --count line insert
              lv_linecount := lv_linecount + 1;
            end;
          end if;
        end;
      end loop; --ycpol.
    end create_contractpoline;
    procedure finalize is
    begin
      --finalize
      commit;
      if lv_headercount > 0 then
        begin
          pack_import.write_log(lv_headercount || ' contractpurchaseorder records inserted', 1);
        end;
      end if;
      if lv_linecount > 0 then
        begin
          pack_import.write_log(lv_linecount || ' contractpurchaseorderline records inserted', 1);
        end;
      end if;
    end finalize;
  begin
    --import_contractpurchaseorder
    gv_message := 'import_contractpurchaseorder';
    for xcpo in (select lcpo.* from i_contractpurchaseorder lcpo) loop
      begin
        --get contract id
        gv_message := 'contract code ' || xcpo.contractcode;
        select c.contract_id into lv_contractid from contract c where c.code = xcpo.contractcode;
        --get businessunit id
        gv_message := 'businessunit code ' || nvl(xcpo.businessunit, 'NULL');
        if xcpo.businessunit is null then
          begin
            lv_businessunitid := null;
          end;
        else
          begin
            select bu.businessunit_id
            into   lv_businessunitid
            from   businessunit bu
            where  bu.code = xcpo.businessunit;
          end;
        end if;
        --get_create_contractpo
        get_create_contractpo(xcpo);
        --create_contractpoline
        create_contractpoline(xcpo.contractcode, xcpo.purchaseordernumber);
        --all ok
        commit;
      exception
        when no_data_found then
          begin
            rollback;
            pack_import.write_log(gv_message || ' does not exist!', 3);
          end;
        when others then
          begin
            rollback;
            pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 3);
          end;
      end;
    end loop; --xcpo
    --finalize
    finalize;
  exception
    when no_data_found then
      begin
        rollback;
        pack_import.write_log(gv_message || ' does not exist!', 3);
      end;
    when others then
      begin
        rollback;
        pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 3);
      end;
  end import_contractpurchaseorder;
  procedure import_contractpocustomer is
    lv_count                   number := 0;
    lv_contractid              contract.contract_id%type;
    lv_contractpurchaseorderid contractpurchaseorder.contractpurchaseorder_id%type;
    lv_contractcustomerid      contractcustomer.contractcustomer_id%type;
    lv_contractpocustomerid    contractpocustomer.contractpocustomer_id%type;
    procedure finalize is
    begin
      --finalize
      commit;
      if lv_count > 0 then
        begin
          pack_import.write_log(lv_count || ' contratpocustomer records inserted', 1);
        end;
      end if;
    end finalize;
  begin
    --import_contractpocustomer
    for l in (select cpoc.*, c.customer_id
              from   i_contractpocustomer cpoc
              join   customer c
              on     c.customernumber = cpoc.customernumber) loop
      begin
        --get contract id
        gv_message := 'contract code ' || l.contractcode;
        select c.contract_id into lv_contractid from contract c where c.code = l.contractcode;
        --get contractpurchaseorder
        gv_message := 'get contractpurchaseorder for contract ' || l.contractcode || ' PO ' ||
                      l.purchaseordernumber;
        select cpo.contractpurchaseorder_id
        into   lv_contractpurchaseorderid
        from   contractpurchaseorder cpo
        where  cpo.contract_id = lv_contractid
        and    cpo.purchaseordernumber = l.purchaseordernumber;
        --get contractcustomer
        gv_message := 'get contractcustomer for customer ' || l.customernumber || ' contract ' ||
                      l.contractcode || ' (cus)startdate ' ||
                      to_char(l.cus_startdate, 'dd-mm-yyyy');
        select cc.contractcustomer_id
        into   lv_contractcustomerid
        from   contractcustomer cc
        where  cc.contract_id = lv_contractid
        and    cc.customer_link_id = l.customer_id
        and    trunc(cc.startdate) = trunc(l.cus_startdate);
        --check if it exists
        select max(cpoc.contractpocustomer_id)
        into   lv_contractpocustomerid
        from   contractpocustomer cpoc
        where  cpoc.contractpurchaseorder_id = lv_contractpurchaseorderid
        and    cpoc.contractcustomer_id = lv_contractcustomerid;
        if lv_contractpocustomerid is null then
          begin
            --insert into contractpocustomer
            gv_message := 'insert into contractpocustomer for customer ' || l.customernumber ||
                          ' contract ' || l.contractcode || ' (cus)startdate ' ||
                          to_char(l.cus_startdate, 'dd-mm-yyyy') || ' PO ' || l.purchaseordernumber;
            insert into contractpocustomer
              (contractpocustomer_id, contractpurchaseorder_id, contractcustomer_id, startdate,
               enddate, systemuser_id, timestamp)
            values
              (seq_contractpocustomer.nextval, lv_contractpurchaseorderid, lv_contractcustomerid,
               l.startdate, l.enddate, pack_import.lvnsystemuserid, sysdate);
            --count
            lv_count := lv_count + 1;
          end;
        end if;
      end;
    end loop;
    --finalize
    finalize;
  exception
    when no_data_found then
      begin
        rollback;
        pack_import.write_log(gv_message || ' does not exist!', 3);
      end;
    when others then
      begin
        rollback;
        pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 3);
      end;
  end import_contractpocustomer;
  procedure import_contractemblemtemplate is
    lcounter               number := 0;
    lcontractid            contract.contract_id%type;
    lgeneralpricelistid    generalpricelist.generalpricelist_id%type;
    lcontractembtempid     contractembtemp.contractembtemp_id%type;
    lproductid             product.product_id%type;
    lsizeid                sizedefinition.sizedefinition_id%type;
    lfabricid              fabric.fabric_id%type;
    lplacement_id          placement.placement_id%type;
    lemblemfontid          emblemfont.emblemfont_id%type;
    lcontractembtemplineid contractembtempline.contractembtempline_id%type;
    procedure link_contractembtempcust is
    begin
      --link_contractembtempcust
      gv_message := 'link_contractembtempcust';
      insert into contractembtempcust
        (contractembtemp_id, emblemtemplate_id, systemuser_id, timestamp)
        select cet.contractembtemp_id, et.emblemtemplate_id, pack_import.lvnsystemuserid, sysdate
        from   contractembtemp cet
        join   contractcustomer cc
        on     cc.contract_id = cet.contract_id
        join   emblemtemplate et
        on     (et.code = cet.code and et.customer_id = cc.customer_link_id)
        where  cet.contractembtemp_id = lcontractembtempid
        and    not exists (select 1
                from   contractembtempcust ctc
                where  ctc.contractembtemp_id = cet.contractembtemp_id
                and    et.emblemtemplate_id = ctc.emblemtemplate_id);
    end link_contractembtempcust;
    function get_generalpricelistid(fp_code              in generalpricelist.code%type,
                                    fp_pricetype         in generalpricelist.pricetype%type,
                                    fp_currencycode      in currency.code%type,
                                    fp_priceindexcode    in generalpricelist.priceindexcode%type,
                                    fp_autopriceupdateyn in generalpricelist.autopriceupdate%type)
      return generalpricelist.generalpricelist_id%type is
      lv_generalpricelistid generalpricelist.generalpricelist_id%type;
      lv_currencyid         currency.currency_id%type;
      function get_currencyid(fp_currencycode in currency.code%type) return currency.currency_id%type is
        lv_currencyid currency.currency_id%type;
      begin
        --get_currencyid
        gv_message := ' get currency id for code ' || nvl(fp_currencycode, 'NULL');
        if fp_currencycode is null then
          return null;
        else
          begin
            select cy.currency_id
            into   lv_currencyid
            from   currency cy
            where  cy.code = fp_currencycode;
            return lv_currencyid;
          end;
        end if;
      end get_currencyid;
    begin
      --get_generalpricelistid
      gv_message := ' get generalpricelist id for code ' || nvl(fp_code, 'NULL') ||
                    ' for pricetype ' || nvl(to_char(fp_pricetype), 'NULL');
      if fp_code is null or fp_pricetype is null then
        return null;
      end if;
      --get generalpricelist
      select gpl.generalpricelist_id
      into   lv_generalpricelistid
      from   generalpricelist gpl
      where  gpl.code = fp_code
      and    gpl.pricetype = fp_pricetype;
      return lv_generalpricelistid;
    exception
      when no_data_found then
        begin
          --get currency id
          lv_currencyid := get_currencyid(fp_currencycode);
          --create missing generalpricelist
          gv_message := ' create generalpricelist id for code ' || nvl(fp_code, 'NULL') ||
                        ' for pricetype ' || nvl(to_char(fp_pricetype), 'NULL');
          pack_import.cfbcreate_generalpricelist(lv_generalpricelistid, fp_pricetype, fp_code,
                                                 fp_code, 'Y', nvl(fp_autopriceupdateyn, 'N'),
                                                 fp_priceindexcode, lv_currencyid, null);
          return lv_generalpricelistid;
        end;
    end get_generalpricelistid;
    procedure create_contractembtemplinecust(fp_contractcode in varchar2) is
    begin
      --create_contractembtemplinecust
      gv_message := 'insert into contractembtemplinecust for contract ' || fp_contractcode;
      insert into contractembtemplinecust
        (contractembtempline_id, emblemtemplateline_id, systemuser_id, timestamp)
        select cel.contractembtempline_id, etl.emblemtemplateline_id, pack_import.lvnsystemuserid,
               sysdate
        from   contractembtempcust cec
        join   contractembtempline cel
        on     cel.contractembtemp_id = cec.contractembtemp_id
        join   emblemtemplateline etl
        on     (etl.emblemtemplate_id = cec.emblemtemplate_id and
               (etl.product_id = cel.product_id or
               (etl.product_id is null and cel.product_id is null)) and
               etl.sizedefinition_id = cel.sizedefinition_id and
               (etl.textcolor_id = cel.textcolor_id or
               (etl.textcolor_id is null and cel.textcolor_id is null)) and
               (etl.bordercolor_id = cel.bordercolor_id or
               (etl.bordercolor_id is null and cel.bordercolor_id is null)) and
               (etl.bkgcolor_id = cel.bkgcolor_id or
               (etl.bkgcolor_id is null and cel.bkgcolor_id is null)) and
               etl.fabric_id = cel.fabric_id and
               (etl.placement_id = cel.placement_id or
               (etl.placement_id is null and cel.placement_id is null)) and
               (etl.emblemfont_id = cel.emblemfont_id or
               (etl.emblemfont_id is null and cel.emblemfont_id is null)) and
               etl.emblemtype = cel.emblemtype)
        where  cel.contractembtempline_id = lcontractembtemplineid
        and    not exists (select 1
                from   contractembtemplinecust x
                where  x.contractembtempline_id = cel.contractembtempline_id
                and    x.emblemtemplateline_id = etl.emblemtemplateline_id);
      --link on all except for colors
      --ABS-119343 link emblemtemplate there were it did not work before not checking colors
      insert into contractembtemplinecust
        (contractembtempline_id, emblemtemplateline_id, systemuser_id, timestamp)
        select max(cel.contractembtempline_id), etl.emblemtemplateline_id,
               pack_import.lvnsystemuserid, sysdate
        from   contractembtempcust cec
        join   contractembtempline cel
        on     cel.contractembtemp_id = cec.contractembtemp_id
        join   emblemtemplateline etl
        on     (etl.emblemtemplate_id = cec.emblemtemplate_id and
               (etl.product_id = cel.product_id or
               (etl.product_id is null and cel.product_id is null)) and
               etl.sizedefinition_id = cel.sizedefinition_id and etl.fabric_id = cel.fabric_id and
               (etl.placement_id = cel.placement_id or
               (etl.placement_id is null and cel.placement_id is null)) and
               (etl.emblemfont_id = cel.emblemfont_id or
               (etl.emblemfont_id is null and cel.emblemfont_id is null)) and
               etl.emblemtype = cel.emblemtype)
        where  cel.contractembtempline_id = lcontractembtemplineid
        and    not exists (select 1
                from   contractembtemplinecust x
                where  x.contractembtempline_id = cel.contractembtempline_id
                and    x.emblemtemplateline_id = etl.emblemtemplateline_id)
        group  by etl.emblemtemplateline_id;
    end create_contractembtemplinecust;
  begin
    --import_contractemblemtemplate
    gv_message := 'import_contractemblemtemplate';
    for x in (select cet.*, rowid
              from   i_contractemblemtemplate cet
              where  cet.contractembtempline_id is null) loop
      begin
        --select contract
        gv_message := ' error getting contract ' || x.contractcode;
        select c.contract_id into lcontractid from contract c where c.code = x.contractcode;
        begin
          --get contractembtemp
          gv_message := 'get contractembtemp';
          select cet.contractembtemp_id
          into   lcontractembtempid
          from   contractembtemp cet
          where  cet.contract_id = lcontractid
          and    cet.code = x.templatecode;
        exception
          when no_data_found then
            begin
              --insert into contractembtemp
              gv_message := 'insert into contractembtemp';
              insert into contractembtemp
                (contractembtemp_id, contract_id, code, description, printnamelabel, active,
                 rentemblem, embroidery, compliancyrule, systemuser_id, timestamp)
              values
                (seq_contractembtemp.nextval, lcontractid, x.templatecode, x.templatedescription,
                 nvl(x.printnamelabel, 'N'), nvl(x.active, 'Y'), nvl(x.rentemblem, 'N'),
                 nvl(x.embroidery, 'N'), x.compliancyrule, pack_import.lvnsystemuserid, sysdate)
              returning contractembtemp_id into lcontractembtempid;
            end;
        end;
        if x.contractembtempprice is not null then
          begin
            --insert into contractembtempprice
            gv_message := 'insert into contractembtempprice';
            insert into contractembtempprice
              (contractembtempprice_id, contractembtemp_id, startdate, price, systemuser_id,
               timestamp)
            values
              (seq_contractembtempprice.nextval, lcontractembtempid,
               coalesce(x.contractembtemppricestartdate, trunc(sysdate)), x.contractembtempprice,
               pack_import.lvnsystemuserid, sysdate);
          exception
            when dup_val_on_index then
              null; --no problem do not update existing price
          end;
        end if;
        --link_contractembtempcust
        link_contractembtempcust;
        --continue with contractembtempline
        --product
        gv_message := ' emblem product ' || x.productcode;
        if x.productcode is null then
          lproductid := null;
        else
          begin
            select p.product_id
            into   lproductid
            from   product p, emblemproduct ep
            where  p.code = x.productcode
            and    p.product_id = ep.product_id;
          end;
        end if; --productid
        begin
          --size
          gv_message := ' size ' || x.sizecode;
          select s.sizedefinition_id into lsizeid from sizedefinition s where s.code = x.sizecode;
        exception
          when no_data_found then
            begin
              pack_import.cfbcreate_sizedefinition(lsizeid, x.sizecode, 'N', null, null, null, 'Y');
              pack_import.cfbcreate_sizedefinition_desc(lsizeid, x.sizecode);
            end;
        end;
        --add_generalsalesprice_list
        gv_message := 'add generalsalesprice';
        if (x.contractembtempsalesprice is not null and lcontractid is not null and
           lproductid is not null and lsizeid is not null) then
          begin
            --get_generalpricelistid
            lgeneralpricelistid := get_generalpricelistid(x.contractcode, 4, 'USD', null, 'N');
            --insert into generalsalesprice
            insert into generalsalesprice
              (generalsalesprice_id, generalpricelist_id, product_id, sizedefinition_id, price,
               startdate, systemuser_id, timestamp)
            values
              (seq_generalsalesprice.nextval, lgeneralpricelistid, lproductid, lsizeid,
               x.contractembtempsalesprice, nvl(x.emtempsalespricestartdate, trunc(sysdate)),
               pack_import.lvnsystemuserid, sysdate);
          exception
            when dup_val_on_index then
              null; --did already exist no problem
          end;
        end if;
        --fabric
        begin
          gv_message := ' fabric ' || x.fabriccode;
          select f.fabric_id into lfabricid from fabric f where f.code = x.fabriccode;
        exception
          when no_data_found then
            begin
              -- Call the procedure to add fabric
              pack_import.cfbcreate_fabric(lfabricid, x.fabriccode, 'Y');
              pack_import.cfbcreate_fabric_desc(lfabricid, x.fabriccode);
            end;
        end;
        -- determine the placement if it is not null.
        gv_message := ' placement ' || x.placementcode;
        if x.placementcode is null then
          lplacement_id := null;
        else
          begin
            select p.placement_id
            into   lplacement_id
            from   placement p
            where  p.code = x.placementcode;
          exception
            when no_data_found then
              begin
                pack_import.cfbcreate_placement(lplacement_id, x.placementcode);
                pack_import.cfbcreate_placement_desc(lplacement_id, x.placementdescription);
              end;
          end;
        end if;
        --emblemfont
        gv_message := ' emblemfontdescription ' || x.emblemfontdescription;
        if x.emblemfontdescription is null then
          lemblemfontid := null;
        else
          begin
            select f.emblemfont_id
            into   lemblemfontid
            from   emblemfont f
            where  upper(f.description) = upper(x.emblemfontdescription);
          exception
            when others then
              begin
                begin
                  insert into emblemfont
                    (emblemfont_id, description, active, systemuser_id, timestamp)
                  values
                    (seq_emblemfont.nextval, x.emblemfontdescription, 'Y',
                     pack_import.lvnsystemuserid, sysdate)
                  returning emblemfont_id into lemblemfontid;
                exception
                  when others then
                    begin
                      pack_import.write_log(' insert into emblemfont failed: ' ||
                                            substr(sqlerrm, 1, 512), 3);
                      lemblemfontid := null;
                    end;
                end;
              end;
          end;
        end if;
        --create emblemtemplate line
        gv_message := 'insert into contractembtempline';
        insert into contractembtempline tembtempline
          (contractembtempline_id, contractembtemp_id, product_id, sizedefinition_id, description,
           textcolor_id, bordercolor_id, bkgcolor_id, fabric_id, placement_id, emblemtype,
           attachmentby, qtypergarment, emblemimage_id, placementimage_id, emblemfont_id, fontsize,
           embroideryfilepathoriginal, embroideryfilepathproduction, stitchcount, setupfee,
           colorpalette, embroiderylettering, embroideryletteringline1, embroideryletteringline2,
           embroideryletteringline3, systemuser_id, timestamp, customcolor, customsize, description2,
           stylecode, customersupplied)
        values
          (seq_contractembtempline.nextval, lcontractembtempid, lproductid, lsizeid, x.description,
           pack_import_emblem.cfbdeterminecolor(x.textcolorcode),
           pack_import_emblem.cfbdeterminecolor(x.bordercolorcode),
           pack_import_emblem.cfbdeterminecolor(x.backgroundcolorcode), lfabricid, lplacement_id,
           nvl(x.emblemtype, 3), nvl(x.attachmentby, 0), nvl(x.qtypergarment, 1),
           get_imageid(x.emblemimagecode, 1), get_imageid(x.placementimagecode, 2), lemblemfontid,
           nvl(x.emblemfontsize, 8), x.embroideryfilepathoriginal, x.embroideryfilepathproduction,
           nvl(x.stitchcount, 0), nvl(x.setupfee, 0), x.colorpalette,
           nvl(x.embroiderylettering, 'N'), x.embroideryletteringline1, x.embroideryletteringline2,
           x.embroideryletteringline3, pack_import.lvnsystemuserid, sysdate, x.customcolor,
           x.customsize, x.description2, x.stylecode, x.customersupplied)
        returning contractembtempline_id into lcontractembtemplineid;
        --create_contractembtemplinecust
        create_contractembtemplinecust(x.contractcode);
        --add contract embtempline piece price when used
        if x.contractembtemplinepieceprice is not null then
          begin
            --insert contractembtemplineprice
            gv_message := 'insert contractembtemplineprice';
            insert into contractembtemplineprice
              (contractembtemplineprice_id, contractembtempline_id, startdate, price, systemuser_id,
               timestamp)
            values
              (seq_contractembtemplineprice.nextval, lcontractembtemplineid,
               nvl(x.emtemplinepiecepricestartdate, trunc(sysdate)), x.contractembtemplinepieceprice,
               pack_import.lvnsystemuserid, sysdate);
          end;
        end if;
        update i_contractemblemtemplate ie
        set    ie.contractembtempline_id = lcontractembtemplineid
        where  ie.rowid = x.rowid;
        --count converted records
        lcounter := lcounter + 1;
      exception
        when no_data_found then
          begin
            pack_import.write_log('Error, no data found ' || gv_message, -3);
          end;
        when dup_val_on_index then
          null; --did already exist no problem
        when others then
          pack_import.write_log('Error import_contractemblemtemplate: ' || gv_message ||
                                substr(sqlerrm, 1, 512), -3);
      end;
    end loop; --x
    if lcounter > 0 then
      begin
        commit;
        pack_import.write_log(lcounter || ' contractembtempline(s) imported.');
      end;
    end if;
  exception
    when no_data_found then
      begin
        rollback;
        pack_import.write_log(gv_message || ' does not exist!', 3);
      end;
    when others then
      begin
        rollback;
        pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 3);
      end;
  end import_contractemblemtemplate;
begin
  --initialization
  --get default plant
  select min(t.plant_id) into lvnplantid from plant t;
exception
  when others then
    begin
      gv_message := 'Error intializing: ';
      pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 3);
    end;
end pack_import_contract;
/
create or replace package pack_import_customer is
  -- Author  : TATIANA
  -- Created : 5/24/2002 4:19:47 PM
  -- Version : 1.0
  -- Changes : 4/10/2003 order 500468
  --           8-jun-2003 changes because of fields made null allowed.
  --           29-apr-2005 added weighingcatpercust+custuserinstruction
  --           16-jan-2013 added rs.customer_id = c.customer_id for return routestops
  --           12-Oct-2018 ABS-73087 Update Conversion process for - Route stop sequence does not align
  --           14-dec-2018 ABS-73322 Extend Conversion with MBYO options ABS-76341
  --           18-Jul-2019 ABS-83974 contact calls followup
  --           21-aug-2019 ABS-85341 statementcontactperson added to i_contactperson
  --           12-sep-2019 ABS-87772 customer credit card conversion
  --           08-jan-2020 ABS-93615 Exchange fee conversion
  --           16-apr-2020 ABS-100432 Add Customer ACH conversion
  --           22-Jul-2020 ABS-101435 master account conversion
  --           03-sep-2020 ABS-107430 Tax area_id fields for the customer addresses.
  --           17-sep-2020 ABS-107917 adding GENERATEPAYMENT to I_BILLTOACCOUNT, default 0
  --           25-nov-2021 ABS-127289 I_customer with firstservicedate
  --           21-Dec-2021 ABS-128932 Check on country when converting tax definition
  --           13-Mar-2023 ABS-149315 I-tables: extend with ADRESSLINE 3 and 40 characters
  --           16-Oct-2025 ABSN-11665 Missing field for i-table and conversion
  function getaddressid(pstreet              address.street%type,
                        pzipcode             address.zipcode%type,
                        pcity                address.city%type,
                        pstate               address.state%type,
                        pcounty              address.county%type,
                        pstreet2             address.street2%type,
                        ptaxareaid           addresstaxareaid.taxareaid%type,
                        pconfidenceindicator addresstaxareaid.confidenceindicator%type,
                        pstreet3             address.street3%type) return number;
  procedure import_customeractivities(pcustomerid       customer.customer_id%type,
                                      pcustomernumber   customer.customernumber%type,
                                      pbusinessunitid   businessunit.businessunit_id%type default null,
                                      pcutoffdate       date default null,
                                      pinvoicefrequency customer.invoicefrequency_id%type default null);
  procedure importcontactperson(pcustomerid                in customer.customer_id%type,
                                pcontactpersonid           in out contactperson.contactperson_id%type,
                                pcontactpersonnumber       in contactperson.contactpersonnumber%type,
                                pcontactpersonname         in contactperson.name%type,
                                pcontactpersonfunctioncode in contactpersonfunction.code%type,
                                pcontactpersonfunctiondesc in contactpersonfunction_desc.description%type,
                                pcontactpersonphone        in contactperson.phone%type,
                                pcontactpersonmobilephone  in contactperson.mobilephone%type,
                                pcontactpersonemail        in contactperson.email%type,
                                pinvoicecontactperson      in contactperson.invoicecontactperson%type,
                                pcontactpersonfax          in contactperson.fax%type,
                                pstatementcontactperson    in contactperson.statementcontactperson%type);
  procedure cfbimportcontactpersons(fp_customerid in customer.customer_id%type default null);
  procedure import_customercreditcard;
  function cfbimport_deliverypoint(fpncustomerid customer.customer_id%type) return number;
  procedure cfbimportcustomerfixedinfo;
  procedure cfbimport_customerbudget;
  procedure imp_customer_budgetprotection;
  procedure cfbprocess_sortcustomer;
  procedure cfbprocess_maindeliverypoint;
  procedure cfbimport_customerprepcharge;
  procedure link_common_customer;
  procedure link_other_customer;
  procedure import_customerach;
  procedure cfbimportcustomer;
  procedure cfbimportcustomerdeliverydays;
  procedure cfbimportcontractspercustomer;
  procedure cfbimporttaxauthorities;
  procedure import_contactcalls_followup;
  procedure cfbimportcontactcalls;
  procedure cfbimport_weighingcategpercust;
  procedure cfbimport_generaluserinstruction;
  procedure cfbimport_custuserinstruction;
  procedure cfbimportcustomersurvey;
  procedure import_customergarmentcharges;
end pack_import_customer;
/
create or replace package body pack_import_customer is
  errormsg                     varchar2(256);
  formlayoutst                 formlayout.formlayout_id%type;
  formlayoutin                 formlayout.formlayout_id%type;
  formlayoutcn                 formlayout.formlayout_id%type;
  formlayoutdn                 formlayout.formlayout_id%type;
  contactpersonfunctionminusid contactpersonfunction.contactpersonfunction_id%type;
  customerid                   customer.customer_id%type;
  transportarticleid           transportarticle.transportarticle_id%type;
  function getaddressid(pstreet              address.street%type,
                        pzipcode             address.zipcode%type,
                        pcity                address.city%type,
                        pstate               address.state%type,
                        pcounty              address.county%type,
                        pstreet2             address.street2%type,
                        ptaxareaid           addresstaxareaid.taxareaid%type,
                        pconfidenceindicator addresstaxareaid.confidenceindicator%type,
                        pstreet3             address.street3%type) return number is
    addressid address.address_id%type;
  begin
    insert into address
      (address_id, street, zipcode, city, state, systemuser_id, county, timestamp, street2, street3)
    values
      (seq_address.nextval, pstreet, nvl(pzipcode, ' '), nvl(pcity, ' '), pstate,
       pack_import.lvnsystemuserid, pcounty, sysdate, pstreet2, pstreet3)
    returning address_id into addressid;
    if ptaxareaid is not null then
      begin
        insert into addresstaxareaid
          (address_id, taxareaid, systemuser_id, timestamp, confidenceindicator)
        values
          (addressid, ptaxareaid, pack_import.lvnsystemuserid, sysdate,
           nvl(pconfidenceindicator, 0));
      end;
    end if;
    return addressid;
  exception
    when others then
      begin
        errormsg := 'GetAddressID: Fail to import address ' || pstreet || '/' || pzipcode || '/' ||
                    pcity || '/' || pstate || '/' || pcounty || '/' || pstreet2;
        pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
        return null;
      end;
  end getaddressid;
  procedure import_customeractivities(pcustomerid       customer.customer_id%type,
                                      pcustomernumber   customer.customernumber%type,
                                      pbusinessunitid   businessunit.businessunit_id%type,
                                      pcutoffdate       date,
                                      pinvoicefrequency customer.invoicefrequency_id%type) is
    lexists               number := 0;
    lactivityid           activity.activity_id%type;
    lprocessbusinessunit  businessunit.businessunit_id%type;
    linvoicebusinessunit  businessunit.businessunit_id%type;
    lplantid              plant.plant_id%type;
    linternalbusinessunit businessunit.businessunit_id%type;
    lvnsalesemployee1id   customer.salesemployee1_id%type;
    lvnsalesemployee2id   customer.salesemployee2_id%type;
  begin
    for x in (select i.activitycode, i.processbusinessunitcode, i.invoicebusinessunitcode,
                     i.cutoffdate, i.invoicefrequency, i.salesemployeenumber1, i.salesemployeename1,
                     i.salesemployeenumber2, i.salesemployeename2, i.internalbusinessunitcode
              from   i_customeractivities i
              where  i.customernumber = pcustomernumber) loop
      begin
        --there exists activities in the i-table so no default activity type needed
        lexists := lexists + 1;
        --get activity
        pack_import.cfbcreate_activity(lactivityid, x.activitycode);
        --get process businessunit
        select u.businessunit_id
        into   lprocessbusinessunit
        from   businessunit u
        where  u.code = x.processbusinessunitcode;
        --get invoice businessunit
        select u.businessunit_id, u.plant_id
        into   linvoicebusinessunit, lplantid
        from   businessunit u
        where  u.code = x.invoicebusinessunitcode;
        --sales employee 1
        if x.salesemployeenumber1 is null then
          lvnsalesemployee1id := null;
        else
          begin
            pack_import.cfbgetcreate_employee(lplantid, lvnsalesemployee1id, x.salesemployeenumber1,
                                              x.salesemployeename1,
                                              nvl(substr(x.salesemployeename1, 1, 10), '-'),
                                              to_date('1-1-2002', 'DD-MM-YYYY'), null, null, null,
                                              null, null);
          exception
            when others then
              begin
                lvnsalesemployee1id := null;
                errormsg            := 'Warning sales1 employee ' || x.salesemployeenumber1 ||
                                       ' is not linked to customeractivity for customer ' ||
                                       pcustomernumber;
                pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 2);
              end;
          end;
        end if;
        --sales employee 2
        if x.salesemployeenumber2 is null then
          lvnsalesemployee2id := null;
        else
          begin
            pack_import.cfbgetcreate_employee(lplantid, lvnsalesemployee2id, x.salesemployeenumber2,
                                              x.salesemployeename2,
                                              nvl(substr(x.salesemployeename2, 1, 10), '-'),
                                              to_date('1-1-2002', 'DD-MM-YYYY'), null, null, null,
                                              null, null);
          exception
            when others then
              begin
                lvnsalesemployee2id := null;
                errormsg            := 'Warning sales2 employee ' || x.salesemployeenumber1 ||
                                       ' is not linked to customeractivity for customer ' ||
                                       pcustomernumber;
                pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 2);
              end;
          end;
        end if;
        if x.internalbusinessunitcode is null then
          linternalbusinessunit := null;
        else
          begin
            --internalbusinessunitcode
            errormsg := 'business unit code' || x.internalbusinessunitcode;
            select bu.businessunit_id
            into   linternalbusinessunit
            from   businessunit bu
            where  bu.code = x.internalbusinessunitcode;
          end;
        end if;
        -- businessunitactivities
        begin
          insert into businessunitactivities
            (businessunit_id, activity_id, systemuser_id, timestamp, invoicedbybusinessunit_id)
          values
            (lprocessbusinessunit, lactivityid, pack_import.lvnsystemuserid, sysdate,
             linvoicebusinessunit);
        exception
          when dup_val_on_index then
            null;
        end;
        --insert customeractivities
        pack_import.cfbcreate_customeractivities(pcustomerid, lactivityid, linvoicebusinessunit,
                                                 lprocessbusinessunit, x.cutoffdate, 'N',
                                                 nvl(x.invoicefrequency, pinvoicefrequency),
                                                 lvnsalesemployee1id, lvnsalesemployee2id,
                                                 linternalbusinessunit);
        commit;
      exception
        when others then
          errormsg := 'Import_customeractivities: Failed for customernumber ' || pcustomernumber;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    --there exists activities in the i-table so no default activity type needed
    if lexists = 0 then
      begin
        -- get activity type '-'
        pack_import.cfbcreate_activity(lactivityid, '-');
        -- businessunitactivities
        begin
          insert into businessunitactivities
            (businessunit_id, activity_id, systemuser_id, timestamp, invoicedbybusinessunit_id)
          values
            (pbusinessunitid, lactivityid, pack_import.lvnsystemuserid, sysdate, pbusinessunitid);
        exception
          when dup_val_on_index then
            null;
        end;
        --insert customeractivities
        pack_import.cfbcreate_customeractivities(pcustomerid, lactivityid, pbusinessunitid,
                                                 pbusinessunitid, pcutoffdate, 'N',
                                                 pinvoicefrequency);
        commit;
      exception
        when others then
          errormsg := 'Default import_customeractivities: Failed for customernumber ' ||
                      pcustomernumber;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end if;
  end import_customeractivities;
  --import 1 contact person
  procedure importcontactperson(pcustomerid                in customer.customer_id%type,
                                pcontactpersonid           in out contactperson.contactperson_id%type,
                                pcontactpersonnumber       in contactperson.contactpersonnumber%type,
                                pcontactpersonname         in contactperson.name%type,
                                pcontactpersonfunctioncode in contactpersonfunction.code%type,
                                pcontactpersonfunctiondesc in contactpersonfunction_desc.description%type,
                                pcontactpersonphone        in contactperson.phone%type,
                                pcontactpersonmobilephone  in contactperson.mobilephone%type,
                                pcontactpersonemail        in contactperson.email%type,
                                pinvoicecontactperson      in contactperson.invoicecontactperson%type,
                                pcontactpersonfax          in contactperson.fax%type,
                                pstatementcontactperson    in contactperson.statementcontactperson%type) is
    lcontactpersonfunctionid contactpersonfunction.contactpersonfunction_id%type;
    lcustomernumber          customer.customernumber%type;
  begin
    select c.customernumber into lcustomernumber from customer c where c.customer_id = pcustomerid;
    select cp.contactperson_id
    into   pcontactpersonid
    from   contactperson cp
    where  cp.contactpersonnumber = pcontactpersonnumber
    and    cp.customer_id = pcustomerid
    and    cp.supplier_id is null;
  exception
    when no_data_found then
      begin
        begin
          -- contactpersonfunction '-'
          select contactpersonfunction_id
          into   lcontactpersonfunctionid
          from   contactpersonfunction
          where  code = nvl(pcontactpersonfunctioncode, '-');
        exception
          when no_data_found then
            insert into contactpersonfunction
              (contactpersonfunction_id, code, systemuser_id, timestamp)
            values
              (seq_contactpersonfunction.nextval, nvl(pcontactpersonfunctioncode, '-'),
               pack_import.lvnsystemuserid, sysdate)
            returning contactpersonfunction_id into lcontactpersonfunctionid;
            insert into contactpersonfunction_desc
              (contactpersonfunction_id, language_id, description, systemuser_id, timestamp)
            values
              (lcontactpersonfunctionid, pack_import.lvnlanguageid,
               nvl(nvl(pcontactpersonfunctiondesc, pcontactpersonfunctioncode), '-'),
               pack_import.lvnsystemuserid, sysdate);
        end;
        insert into contactperson
          (customer_id, contactperson_id, contactpersonnumber, contactpersonfunction_id, name,
           phone, mobilephone, email, invoicecontactperson, fax, systemuser_id, timestamp,
           statementcontactperson)
        values
          (pcustomerid, seq_contactperson.nextval, pcontactpersonnumber,
           nvl(lcontactpersonfunctionid, contactpersonfunctionminusid),
           nvl(pcontactpersonname, to_char(pcontactpersonnumber)), pcontactpersonphone,
           pcontactpersonmobilephone, pcontactpersonemail, nvl(pinvoicecontactperson, 'N'),
           pcontactpersonfax, pack_import.lvnsystemuserid, sysdate,
           nvl(pstatementcontactperson, 'N'))
        returning contactperson_id into pcontactpersonid;
      exception
        when dup_val_on_index then
          null;
        when others then
          pcontactpersonid := null;
          errormsg         := 'importcontactperson: Fail to import contact person number/customernumber ' ||
                              pcontactpersonnumber || '/' || lcustomernumber;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
  end importcontactperson;
  --import contactpersons
  procedure cfbimportcontactpersons(fp_customerid in customer.customer_id%type default null) is
    lcontactpersonid contactperson.contactperson_id%type;
    lcountrows       integer;
  begin
    --update
    lcountrows := 0;
    for vcursor in (select a.*, c.customer_id, c.contactperson_id
                    from   i_contactperson a, customer b, contactperson c
                    where  a.customernumber = b.customernumber
                    and    b.customer_id = c.customer_id
                    and    c.timestamp > (sysdate - 2 / 24)
                    and    c.systemuser_id = pack_import.lvnsystemuserid
                    and    fp_customerid is null
                    and    a.contactpersonnumber = c.contactpersonnumber) loop
      begin
        update contactperson
        set    name = vcursor.contactpersonname, phone = vcursor.phone,
               mobilephone = vcursor.mobilephone, email = vcursor.email,
               invoicecontactperson = vcursor.invoicecontactperson, fax = vcursor.fax,
               systemuser_id = pack_import.lvnsystemuserid, timestamp = sysdate,
               statementcontactperson = nvl(vcursor.statementcontactperson, 'N')
        where  customer_id = vcursor.customer_id
        and    contactperson_id = vcursor.contactperson_id;
        lcountrows := lcountrows + 1;
      exception
        when others then
          errormsg := 'CFbImportContactPerson: Fail to update contact person number/customernumber ' ||
                      vcursor.contactpersonnumber || '/' || vcursor.customernumber;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 and fp_customerid is null then
      begin
        commit;
        pack_import.write_log(lcountrows || ' contact person(s)  updated.');
      end;
    end if;
    begin
      --insert i_contract contactpersons.
      insert into i_contactperson
        (customernumber, contactpersonnumber, contactpersonname, invoicecontactperson,
         contactpersonfunctioncode, contactpersonfunctiondescr, statementcontactperson)
        select i.customernumber, i.customercontactpersonnumber,
               to_char(i.customercontactpersonnumber), 'N', 999, 'Contract person', 'N'
        from   i_contract i
        where  i.customercontactpersonnumber is not null
        and    not exists
         (select y.customernumber, y.contactpersonnumber
                from   i_contactperson y
                where  y.customernumber = i.customernumber
                and    y.contactpersonnumber = i.customercontactpersonnumber)
        group  by i.customernumber, i.customercontactpersonnumber;
      commit;
    exception
      when others then
        begin
          errormsg := 'Error during insert i_contract contactpersons ';
          pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
        end;
    end;
    --insert
    lcountrows := 0;
    for vcursor in (select a.*, b.customer_id
                    from   i_contactperson a, customer b
                    where  a.customernumber = b.customernumber
                    and    (fp_customerid = b.customer_id or fp_customerid is null)
                    and    not exists
                     (select contactpersonnumber
                            from   contactperson
                            where  customer_id = b.customer_id
                            and    contactpersonnumber = a.contactpersonnumber)) loop
      begin
        importcontactperson(vcursor.customer_id, lcontactpersonid, vcursor.contactpersonnumber,
                            vcursor.contactpersonname, vcursor.contactpersonfunctioncode,
                            vcursor.contactpersonfunctiondescr, vcursor.phone, vcursor.mobilephone,
                            vcursor.email, vcursor.invoicecontactperson, vcursor.fax,
                            vcursor.statementcontactperson);
        lcountrows := lcountrows + 1;
      exception
        when others then
          begin
            errormsg := 'Error during cfbimportcontactpersons ';
            pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
          end;
      end;
    end loop;
    if lcountrows > 0 and fp_customerid is null then
      begin
        commit;
        pack_import.write_log(lcountrows || ' contact person(s)  imported.');
      end;
    end if;
  end cfbimportcontactpersons;
  procedure import_visitmonths is
    countrows number := 0;
  begin
    --import visitmonths
    for x in (select i.month, c.customer_id
              from   i_visitmonth i, customer c
              where  c.customernumber = i.customernumber
              and    not exists (select v.customer_id, v.month
                      from   visitingmonth v
                      where  v.customer_id = c.customer_id
                      and    v.month = i.month)) loop
      begin
        insert into visitingmonth
          (month, customer_id, systemuser_id, timestamp)
        values
          (x.month, x.customer_id, pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(to_char(countrows) || ' visitmonths records inserted.');
      end;
    end if;
  exception
    when others then
      begin
        pack_import.write_log('import_visitmonths: Fail to import.' || substr(sqlerrm, 1, 512), 3);
      end;
  end import_visitmonths;
  procedure import_customerenvinfo is
    countrows          number := 0;
    fpnmunicipality_id municipality.municipality_id%type;
    fpnwastesite_id    wastesite.wastesite_id%type;
  begin
    --import customerenvinfo
    for x in (select c.customer_id, e.*
              from   i_customerenvinfo e, customer c
              where  e.customernumber = c.customernumber) loop
      begin
        if x.municipalitycode is null then
          fpnmunicipality_id := null;
        else
          begin
            --get municipality
            select m.municipality_id
            into   fpnmunicipality_id
            from   municipality m
            where  m.code = x.municipalitycode;
          exception
            when no_data_found then
              begin
                insert into municipality
                  (municipality_id, code, description, systemuser_id, timestamp)
                values
                  (seq_municipality.nextval, x.municipalitycode,
                   nvl(x.municipalitydescription, x.municipalitycode), pack_import.lvnsystemuserid,
                   sysdate)
                returning municipality_id into fpnmunicipality_id;
              end;
          end;
        end if; --municipality
        if x.wastcode is null then
          fpnwastesite_id := null;
        else
          begin
            --get wastesite
            select w.wastesite_id into fpnwastesite_id from wastesite w where w.code = x.wastcode;
          exception
            when no_data_found then
              begin
                insert into wastesite
                  (wastesite_id, code, description, systemuser_id, timestamp)
                values
                  (seq_wastesite.nextval, x.wastcode, nvl(x.wastdescription, x.wastcode),
                   pack_import.lvnsystemuserid, sysdate)
                returning wastesite_id into fpnwastesite_id;
              end;
          end;
        end if; --wastesite
        --create customerenvinfo
        insert into customerenvinfo
          (customer_id, wasteperyear, systemuser_id, timestamp, municipality_id, wastesite_id,
           startdatepowerofatt, enddatepowerofatt)
        values
          (x.customer_id, nvl(x.wasteperyear, 0), pack_import.lvnsystemuserid, sysdate,
           fpnmunicipality_id, fpnwastesite_id, x.startdatepowerofatt, x.enddatepowerofatt);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(to_char(countrows) || ' customerenvinfo records inserted.');
    end if;
  exception
    when others then
      begin
        pack_import.write_log('import_customerenvinfo: Fail to import.' || substr(sqlerrm, 1, 512),
                              3);
      end;
  end import_customerenvinfo;
  procedure cfbimport_creditcards is
    countrows     number := 0;
    fpncustomerid customer.customer_id%type;
  begin
    --import creditcards
    for x in (select * from i_creditcard) loop
      begin
        select c.customer_id
        into   fpncustomerid
        from   customerbillinginfo b, customer c
        where  c.customernumber = x.customernumber
        and    b.customer_id = c.customer_id;
        --update data
        update customerbillinginfo b
        set    b.creditcardinfo = x.creditcardtype || ' ' || x.creditcardnumber || ' ' ||
                                   x.experationyear || ' ' || x.experationmonth || ' ' ||
                                   x.verificationvalue || ' ' || x.creditcardname || ' ' ||
                                   x.createtransactionfromstatement
        where  b.customer_id = fpncustomerid;
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when no_data_found then
          pack_import.write_log(' cfbimport_creditcards, error missing customer billinfo: ' ||
                                to_char(x.customernumber) || '!');
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(to_char(countrows) || ' creditcardinfo updated.');
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('cfbimport_creditcards: Failed to import.' ||
                              substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_creditcards;
  procedure import_customercreditcard is
    lv_countrows number := 0;
    procedure add_creditcardchargeschedule is
    begin
      --add missing creditcardchargeschedule records
      insert into creditcardchargeschedule
        (creditcardchargeschedule_id, type, dayofmonth, dayofweek, dayofweekinmonth, systemuser_id,
         timestamp)
        select seq_creditcardchargeschedule.nextval, ix.type, ix.dayofmonth, ix.dayofweek,
               ix.dayofweekinmonth, pack_import.lvnsystemuserid, sysdate
        from   (select icc.type, nvl(icc.dayofmonth, 0) dayofmonth, nvl(icc.dayofweek, 0) dayofweek,
                        nvl(icc.dayofweekinmonth, 0) dayofweekinmonth
                 from   i_customercreditcard icc
                 where  icc.type is not null
                 group  by icc.type, nvl(icc.dayofmonth, 0), nvl(icc.dayofweek, 0),
                           nvl(icc.dayofweekinmonth, 0)) ix
        where  not exists (select 1
                from   creditcardchargeschedule cx
                where  cx.type = ix.type
                and    cx.dayofmonth = ix.dayofmonth
                and    cx.dayofweek = ix.dayofweek
                and    cx.dayofweekinmonth = ix.dayofweekinmonth);
      lv_countrows := sql%rowcount;
      if lv_countrows > 0 then
        begin
          commit;
          pack_import.write_log('Credit Card Charge Schedule ' || to_char(lv_countrows) ||
                                ' records imported');
        end;
      end if;
    exception
      when others then
        begin
          rollback;
          pack_import.write_log('add_creditcardchargeschedule: Failed to import.' ||
                                substr(sqlerrm, 1, 512), 3);
        end;
    end add_creditcardchargeschedule;
    procedure add_customerccchargeschedule is
    begin
      --add_customerccchargeschedule
      insert into customerccchargeschedule
        (customer_id, creditcardchargeschedule_id, systemuser_id, timestamp)
        select c.customer_id, ccs.creditcardchargeschedule_id, pack_import.lvnsystemuserid, sysdate
        from   i_customercreditcard icc
        join   customer c
        on     c.customernumber = icc.customernumber
        join   creditcardchargeschedule ccs
        on     (ccs.type = icc.type and ccs.dayofmonth = nvl(icc.dayofmonth, 0) and
               ccs.dayofweek = nvl(icc.dayofweek, 0) and
               ccs.dayofweekinmonth = nvl(icc.dayofweekinmonth, 0))
        where  not exists
         (select 1 from customerccchargeschedule btx where btx.customer_id = c.customer_id);
      lv_countrows := sql%rowcount;
      if lv_countrows > 0 then
        begin
          commit;
          pack_import.write_log('Customer Card Charge Schedule ' || to_char(lv_countrows) ||
                                ' records imported');
        end;
      end if;
    exception
      when others then
        begin
          rollback;
          pack_import.write_log('add_customerccchargeschedule: Failed to import.' ||
                                substr(sqlerrm, 1, 512), 3);
        end;
    end add_customerccchargeschedule;
  begin
    --add missing creditcardchargeschedule records
    add_creditcardchargeschedule;
    --add_customerccchargeschedule
    add_customerccchargeschedule;
    --import_customercreditcard
    insert into customercreditcard
      (customer_id, maskedcardnumber, token, tokencreatedate, tokenexpirydate, cardexpirymonth,
       cardexpiryyear, systemuser_id, timestamp)
      select c.customer_id, icc.maskedcardnumber, icc.token, icc.tokencreatedate,
             icc.tokenexpirydate, icc.cardexpirymonth, icc.cardexpiryyear,
             pack_import.lvnsystemuserid, sysdate
      from   i_customercreditcard icc
      join   customer c
      on     c.customernumber = icc.customernumber
      where  (icc.maskedcardnumber is not null or icc.token is not null)
      and    not exists
       (select 1 from customercreditcard ccc where ccc.customer_id = c.customer_id);
    lv_countrows := sql%rowcount;
    if lv_countrows > 0 then
      begin
        commit;
        pack_import.write_log('Customer Creditcard ' || to_char(lv_countrows) ||
                              ' records imported');
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('cfbimport_creditcards: Failed to import.' ||
                              substr(sqlerrm, 1, 512), 3);
      end;
  end import_customercreditcard;
  procedure cfbcreate_delpointopeninghours(fpndeliverypointid deliverypoint.deliverypoint_id%type,
                                           fpndayid           day.day_id%type,
                                           fpnopeningstime    deliverypointopeninghour.starttime%type,
                                           fpnclosingtime     deliverypointopeninghour.endtime%type) is
  begin
    insert into deliverypointopeninghour
      (deliverypoint_id, day_id, starttime, endtime, systemuser_id, timestamp)
    values
      (fpndeliverypointid, fpndayid, fpnopeningstime, fpnclosingtime, pack_import.lvnsystemuserid,
       sysdate);
  end cfbcreate_delpointopeninghours;
  function cfbimport_deliverypoint(fpncustomerid customer.customer_id%type) return number is
    countrows            number := 0;
    fpndeliverypointid   deliverypoint.deliverypoint_id%type;
    fpndeliveryaddressid address.address_id%type;
  begin
    --import deliverypoints
    for x in (select i.*, c.visitaddress_id
              from   i_deliverypoint i, customer c
              where  i.customernumber = c.customernumber
              and    c.customer_id = fpncustomerid
              and    not exists (select 1
                      from   deliverypoint dp
                      where  dp.customer_id = c.customer_id
                      and    dp.code = i.deliverypointcode)) loop
      begin
        if x.deliveryaddress_city is null then
          fpndeliveryaddressid := x.visitaddress_id;
        else
          --get address, will be unique per deliverypoint!
          fpndeliveryaddressid := pack_import_customer.getaddressid(x.deliveryaddress_street,
                                                                    x.deliveryaddress_zipcode,
                                                                    x.deliveryaddress_city, null,
                                                                    null, x.deliveryaddress_street2,
                                                                    null, null,
                                                                    x.deliveryaddress_street3);
        end if;
        --create deliverypoint
        pack_import.cfbcreate_deliverypoint(fpndeliverypointid, fpncustomerid, x.deliverypointcode,
                                            x.deliverypointdescription, fpndeliveryaddressid,
                                            x.sortaddress);
        if x.breakfrom is not null then
          update deliverypoint d
          set    d.breakstarttime = x.breakfrom, d.breakendtime = x.breakto
          where  d.deliverypoint_id = fpndeliverypointid;
        end if;
        --create deliverypoint openinghours
        if x.mondayopen is not null then
          cfbcreate_delpointopeninghours(fpndeliverypointid, 1, x.mondayopen, x.mondayclosed);
        end if;
        if x.tuesdayopen is not null then
          cfbcreate_delpointopeninghours(fpndeliverypointid, 2, x.tuesdayopen, x.tuesdayclosed);
        end if;
        if x.wednesdayopen is not null then
          cfbcreate_delpointopeninghours(fpndeliverypointid, 3, x.wednesdayopen, x.wednesdayclosed);
        end if;
        if x.thursdayopen is not null then
          cfbcreate_delpointopeninghours(fpndeliverypointid, 4, x.thursdayopen, x.thursdayclosed);
        end if;
        if x.fridayopen is not null then
          cfbcreate_delpointopeninghours(fpndeliverypointid, 5, x.fridayopen, x.fridayclosed);
        end if;
        if x.saterdayopen is not null then
          cfbcreate_delpointopeninghours(fpndeliverypointid, 6, x.saterdayopen, x.saterdayclosed);
        end if;
        if x.sundayopen is not null then
          cfbcreate_delpointopeninghours(fpndeliverypointid, 7, x.sundayopen, x.sundayclosed);
        end if;
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
      end;
    end loop;
    return countrows;
  exception
    when others then
      begin
        return countrows;
        pack_import.write_log('cfbimport_deliverypoint: Failed to import.' ||
                              substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_deliverypoint;
  procedure convert_i_deliverypoint as
    lv_countrows number := 0;
  begin
    --convert_i_deliverypoint
    errormsg := 'convert_i_deliverypoint';
    for jj in (select c.customer_id
               from   i_deliverypoint ip
               join   customer c
               on     c.customernumber = ip.customernumber
               where  not exists (select 1
                       from   deliverypoint dp
                       where  dp.customer_id = c.customer_id
                       and    dp.code = ip.deliverypointcode)
               group  by c.customer_id) loop
      begin
        lv_countrows := pack_import_customer.cfbimport_deliverypoint(jj.customer_id);
      end;
    end loop;
    if lv_countrows > 0 then
      begin
        commit;
        pack_import.write_log('convert_i_deliverypoint imported ' || to_char(lv_countrows) ||
                              ' deliverypoints');
      end;
    end if;
  end convert_i_deliverypoint;
  procedure cfbimportcustomerfixedinfo is
    divisionid               division.division_id%type;
    qualitygradeid           qualitygrade.qualitygrade_id%type;
    lpriority                customerranking.priority%type;
    lvnemployee_id           employee.employee_id%type;
    cleanroomcustomertype_id cleanroomcustomertype.cleanroomcustomertype_id%type;
    lcountrows               integer := 0;
  begin
    pack_import.write_log('Start import customer fixedinfo.');
    --customerfixedinfo
    update i_customer c
    set    c.remark = replace(c.remark, '|', chr(10))
    where  c.remark <> replace(c.remark, '|', chr(10));
    update i_customer c
    set    c.routedescription = replace(c.routedescription, '|', chr(10))
    where  c.routedescription <> replace(c.routedescription, '|', chr(10));
    update i_billtoaccount a
    set    a.remarkonstatement = replace(a.remarkonstatement, '|', chr(10))
    where  a.remarkonstatement <> replace(a.remarkonstatement, '|', chr(10));
    commit;
    begin
      for x in (select i.deliverynotelayout from i_customer i group by i.deliverynotelayout) loop
        begin
          pack_import.cbcreate_formlayout(formlayoutdn, 'DN', x.deliverynotelayout, null, 'Y', '-');
        exception
          when dup_val_on_index then
            null;
        end;
      end loop;
    exception
      when others then
        errormsg := 'CFbImportCustomer: Fail to insert default formlayout DN ';
        pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
    end; --formlayoutdn
    begin
      select formlayout_id
      into   formlayoutcn
      from   formlayout
      where  code = '1'
      and    formtype = 'CN';
    exception
      when no_data_found then
        begin
          pack_import.cbcreate_formlayout(formlayoutcn, 'CN', '1', null, 'Y', '-');
        exception
          when dup_val_on_index then
            null;
          when others then
            errormsg := 'CFbImportCustomer: Fail to insert default formlayout CN ';
            pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
        end;
    end; --formlayoutcn
    begin
      select formlayout_id
      into   formlayoutin
      from   formlayout
      where  code = '1'
      and    formtype = 'IN';
    exception
      when no_data_found then
        begin
          pack_import.cbcreate_formlayout(formlayoutin, 'IN', '1', null, 'Y', '-');
        exception
          when dup_val_on_index then
            null;
          when others then
            errormsg := 'CFbImportCustomer: Fail to import insert formlayout IN ';
            pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
        end;
    end; --formlayoutin
    begin
      for x in (select i.statementlayout
                from   i_billtoaccount i
                where  i.statementlayout is not null
                and    not exists (select 1
                        from   formlayout fl
                        where  fl.code = i.statementlayout
                        and    fl.formtype = 'ST')
                group  by i.statementlayout) loop
        begin
          pack_import.cbcreate_formlayout(formlayoutst, 'ST', x.statementlayout, null, 'N',
                                          x.statementlayout);
        exception
          when dup_val_on_index then
            null;
          when others then
            errormsg := 'CFbImportCustomer: Fail to import insert formlayout ST ' ||
                        x.statementlayout;
            pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
        end;
      end loop;
      for x in (select i.consolidatedinvoicelayout
                from   i_billtoaccount i
                where  i.consolidatedinvoicelayout is not null
                and    not exists (select 1
                        from   formlayout fl
                        where  fl.code = i.consolidatedinvoicelayout
                        and    fl.formtype = 'CI')
                group  by i.consolidatedinvoicelayout) loop
        begin
          pack_import.cbcreate_formlayout(formlayoutst, 'CI', x.consolidatedinvoicelayout, null,
                                          'N', x.consolidatedinvoicelayout);
        exception
          when dup_val_on_index then
            null;
          when others then
            errormsg := 'CFbImportCustomer: Fail to import insert formlayout CI ' ||
                        x.consolidatedinvoicelayout;
            pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
        end;
      end loop;
    end;
    begin
      select formlayout_id
      into   formlayoutst
      from   formlayout
      where  code = '1'
      and    formtype = 'ST';
    exception
      when no_data_found then
        begin
          pack_import.cbcreate_formlayout(formlayoutst, 'ST', '1', null, 'Y', '-');
        exception
          when dup_val_on_index then
            null;
          when others then
            errormsg := 'CFbImportCustomer: Fail to insert default formlayout ST ';
            pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
        end;
    end; --formlayoutst
    begin
      -- contactpersonfunction '-'
      select contactpersonfunction_id
      into   contactpersonfunctionminusid
      from   contactpersonfunction
      where  code = '-';
    exception
      when no_data_found then
        begin
          insert into contactpersonfunction
            (contactpersonfunction_id, code, systemuser_id, timestamp)
          values
            (seq_contactpersonfunction.nextval, '-', pack_import.lvnsystemuserid, sysdate)
          returning contactpersonfunction_id into contactpersonfunctionminusid;
          insert into contactpersonfunction_desc
            (contactpersonfunction_id, language_id, description, systemuser_id, timestamp)
          values
            (seq_contactpersonfunction.currval, pack_import.lvnlanguageid, '-',
             pack_import.lvnsystemuserid, sysdate);
        exception
          when dup_val_on_index then
            null;
          when others then
            errormsg := 'CFbImportCustomer: Fail to import default contactpersonfunction ';
            pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
        end;
    end;
    commit;
    --sales employee
    lcountrows := 0;
    for x in (select c.salesemployeenumber, max(c.salesemployeename) salesemployeename,
                     max(b.plant_id) plant_id
              from   i_customer c, businessunit b
              where  b.code = to_char(c.businessunit)
              and    c.salesemployeenumber is not null
              and    not exists (select e.employee_id
                      from   employee e
                      where  e.employeenumber = c.salesemployeenumber)
              group  by c.salesemployeenumber) loop
      begin
        pack_import.cfbgetcreate_employee(x.plant_id, lvnemployee_id, x.salesemployeenumber,
                                          x.salesemployeename,
                                          nvl(substr(x.salesemployeename, 1, 10), '-'),
                                          to_date('1-1-2002', 'DD-MM-YYYY'), null, null, null, null,
                                          null);
        lcountrows := lcountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomer: Fail to import salesemployee ' || x.salesemployeenumber;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' salesemployee(s) row(s) imported.');
      end;
    end if;
    --sales employee1
    lcountrows := 0;
    for x in (select c.salesemployeenumber1, max(c.salesemployeename1) salesemployeename1,
                     max(b.plant_id) plant_id
              from   i_customer c, businessunit b
              where  b.code = c.businessunit
              and    c.salesemployeenumber1 is not null
              and    not exists (select e.employee_id
                      from   employee e
                      where  e.employeenumber = c.salesemployeenumber1)
              group  by c.salesemployeenumber1
              union
              select c.salesemployeenumber1, max(c.salesemployeename1) salesemployeename1,
                     max(b.plant_id) plant_id
              from   i_customeractivities c, businessunit b
              where  b.code = c.invoicebusinessunitcode
              and    c.salesemployeenumber1 is not null
              and    not exists (select e.employee_id
                      from   employee e
                      where  e.employeenumber = c.salesemployeenumber1)
              group  by c.salesemployeenumber1) loop
      begin
        pack_import.cfbgetcreate_employee(x.plant_id, lvnemployee_id, x.salesemployeenumber1,
                                          x.salesemployeename1,
                                          nvl(substr(x.salesemployeename1, 1, 10), '-'),
                                          to_date('1-1-2002', 'DD-MM-YYYY'), null, null, null, null,
                                          null);
        lcountrows := lcountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomer: Fail to import salesemployee1 ' || x.salesemployeenumber1;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' salesemployee1(s) row(s) imported.');
      end;
    end if;
    --sales employee2
    lcountrows := 0;
    for x in (select c.salesemployeenumber2, max(c.salesemployeename2) salesemployeename2,
                     max(b.plant_id) plant_id
              from   i_customer c, businessunit b
              where  b.code = to_char(c.businessunit)
              and    c.salesemployeenumber2 is not null
              and    not exists (select e.employee_id
                      from   employee e
                      where  e.employeenumber = c.salesemployeenumber2)
              group  by c.salesemployeenumber2
              union
              select c.salesemployeenumber2, max(c.salesemployeename2) salesemployeename2,
                     max(b.plant_id) plant_id
              from   i_customeractivities c, businessunit b
              where  b.code = c.invoicebusinessunitcode
              and    c.salesemployeenumber2 is not null
              and    not exists (select e.employee_id
                      from   employee e
                      where  e.employeenumber = c.salesemployeenumber2)
              group  by c.salesemployeenumber2) loop
      begin
        pack_import.cfbgetcreate_employee(x.plant_id, lvnemployee_id, x.salesemployeenumber2,
                                          x.salesemployeename2,
                                          nvl(substr(x.salesemployeename2, 1, 10), '-'),
                                          to_date('1-1-2002', 'DD-MM-YYYY'), null, null, null, null,
                                          null);
        lcountrows := lcountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomer: Fail to import salesemployee2 ' || x.salesemployeenumber2;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' salesemployee2(s) row(s) imported.');
      end;
    end if;
    --service employee
    lcountrows := 0;
    for x in (select c.serviceemployeenumber, max(c.serviceemployeename) serviceemployeename,
                     max(b.plant_id) plant_id
              from   i_customer c, businessunit b
              where  b.code = to_char(c.businessunit)
              and    c.serviceemployeenumber is not null
              and    not exists (select e.employee_id
                      from   employee e
                      where  e.employeenumber = c.serviceemployeenumber)
              group  by c.serviceemployeenumber) loop
      begin
        pack_import.cfbgetcreate_employee(x.plant_id, lvnemployee_id, x.serviceemployeenumber,
                                          x.serviceemployeename,
                                          nvl(substr(x.serviceemployeename, 1, 10), '-'),
                                          to_date('1-1-2002', 'DD-MM-YYYY'), null, null, null, null,
                                          null);
        lcountrows := lcountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomer: Fail to import serviceployee ' || x.serviceemployeenumber;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' serviceployee(s) row(s) imported.');
      end;
    end if;
    begin
      -- transport article
      select min(ta.transportarticle_id) into transportarticleid from transportarticle ta;
      if transportarticleid is null then
        begin
          pack_import.cfbcreate_transportarticle(transportarticleid, '1', 'Y');
          commit;
        end;
      end if;
    exception
      when others then
        transportarticleid := null;
        errormsg           := 'CFbImportCustomer: Fail to create a default transportarticle 1 ';
        pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
    end;
    -- insert customer clusters
    lcountrows := 0;
    for x in (select a.invoiceclusteringcode, f.invoicefrequency_id
              from   i_customer a, invoicefrequency f
              where  a.invoicefrequency = f.invoicefrequencynumber
              and    a.invoiceclusteringcode is not null
              group  by a.invoiceclusteringcode, f.invoicefrequency_id) loop
      begin
        insert into customercluster
          (cluster_id, code, description, invoicefrequency_id, active, systemuser_id, timestamp)
        values
          (seq_customercluster.nextval, x.invoiceclusteringcode, x.invoiceclusteringcode,
           x.invoicefrequency_id, 'Y', pack_import.lvnsystemuserid, sysdate);
        lcountrows := lcountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomer: Fail to import (invoiceclusteringcode) customer clusters ' ||
                      x.invoiceclusteringcode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' customer clusters rows imported.');
      end;
    end if;
    begin
      select division_id into divisionid from division where code = '-';
    exception
      when no_data_found then
        begin
          select min(division_id) into divisionid from division;
        exception
          when dup_val_on_index then
            null;
          when others then
            errormsg := 'CFbImportCustomer: Fail to select default division ';
            pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
        end;
    end;
    -- marketsegment
    lcountrows := 0;
    for vcursor in (select i.marketsegmentcode, max(i.marketsegmentdesc) marketsegmentdesc
                    from   i_customer i
                    where  not exists
                     (select 1 from marketsegment ms where ms.code = i.marketsegmentcode)
                    group  by i.marketsegmentcode
                    order  by i.marketsegmentcode) loop
      begin
        insert into marketsegment
          (marketsegment_id, code, systemuser_id, timestamp)
        values
          (seq_marketsegment.nextval, vcursor.marketsegmentcode, pack_import.lvnsystemuserid,
           sysdate);
        insert into marketsegment_desc
          (marketsegment_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_marketsegment.currval, pack_import.lvnlanguageid, vcursor.marketsegmentdesc,
           pack_import.lvnsystemuserid, sysdate);
        lcountrows := lcountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomer: Fail to import marketsegment code/description ' ||
                      vcursor.marketsegmentcode || '/' || vcursor.marketsegmentdesc;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' marketsegment rows imported.');
      end;
    end if;
    -- salesarea
    lcountrows := 0;
    for vcursor in (select max(bu.plant_id) plant_id, i.salesareacode,
                           max(i.salesareadesc) salesareadesc,
                           max(nvl(i.salesemployeenumber, 1)) salesemployeenumber,
                           max(nvl(i.salesemployeename, '-')) salesemployeename
                    from   i_customer i, businessunit bu
                    where  i.businessunit = bu.code
                    and    not exists
                     (select code from salesarea where code = i.salesareacode)
                    group  by i.salesareacode
                    order  by i.salesareacode) loop
      begin
        pack_import.cfbgetcreate_employee(vcursor.plant_id, lvnemployee_id,
                                          vcursor.salesemployeenumber, vcursor.salesemployeename,
                                          null, null, null, null, null, null, null);
        insert into salesarea
          (salesarea_id, code, responsibleemployee_id, systemuser_id, timestamp)
        values
          (seq_salesarea.nextval, vcursor.salesareacode, lvnemployee_id,
           pack_import.lvnsystemuserid, sysdate);
        insert into salesarea_desc
          (salesarea_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_salesarea.currval, pack_import.lvnlanguageid, vcursor.salesareadesc,
           pack_import.lvnsystemuserid, sysdate);
        lcountrows := lcountrows + 1;
      exception
        when others then
          errormsg := 'CFbImportCustomer: Fail to import salesarea code/description ' ||
                      vcursor.salesareacode || '/' || vcursor.salesareadesc;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' salesarea rows imported.');
      end;
    end if;
    -- firstdaysgradecode
    lcountrows := 0;
    for vcursor in (select firstdaysgradecode
                    from   i_customer
                    where  firstdaysgradecode is not null
                    and    not exists
                     (select code from qualitygrade where code = firstdaysgradecode)
                    group  by firstdaysgradecode
                    order  by firstdaysgradecode) loop
      begin
        qualitygradeid := pack_import.getqualitygradeid(vcursor.firstdaysgradecode);
        lcountrows     := lcountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomer: Fail to import firstdaysgradecode ' ||
                      vcursor.firstdaysgradecode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' firstdaysgradecode rows imported.');
      end;
    end if;
    -- qualitygradecode => firstissuegradecode
    lcountrows := 0;
    for vcursor in (select firstissuegradecode
                    from   i_customer
                    where  firstissuegradecode is not null
                    and    not exists
                     (select code from qualitygrade where code = firstissuegradecode)
                    group  by firstissuegradecode
                    order  by firstissuegradecode) loop
      begin
        qualitygradeid := pack_import.getqualitygradeid(vcursor.firstissuegradecode);
        lcountrows     := lcountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomer: Fail to import firstissuegradecode ' ||
                      vcursor.firstissuegradecode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    -- qualitygradecode II
    for vcursor in (select qualitygradecode
                    from   i_customer
                    where  qualitygradecode is not null
                    and    not exists
                     (select code from qualitygrade where code = qualitygradecode)
                    group  by qualitygradecode
                    order  by qualitygradecode) loop
      begin
        qualitygradeid := pack_import.getqualitygradeid(vcursor.qualitygradecode);
        lcountrows     := lcountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomer: Fail to import qualitygradecode ' ||
                      vcursor.qualitygradecode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' qualitygradecode rows imported.');
      end;
    end if;
    -- gainreason
    lcountrows := 0;
    for vcursor in (select gainreasoncode, max(gainreasondesc) gainreasondesc
                    from   i_customer
                    where  gainreasoncode is not null
                    and    not exists
                     (select 1 from gainlostreason where code = gainreasoncode)
                    group  by gainreasoncode
                    order  by gainreasoncode) loop
      begin
        insert into gainlostreason
          (gainlostreason_id, code, systemuser_id, gainreason, timestamp, lostreason)
        values
          (seq_gainlostreason.nextval, vcursor.gainreasoncode, pack_import.lvnsystemuserid, 'Y',
           sysdate, 'N');
        insert into gainlostreason_desc
          (gainlostreason_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_gainlostreason.currval, pack_import.lvnlanguageid,
           nvl(vcursor.gainreasondesc, vcursor.gainreasoncode), pack_import.lvnsystemuserid, sysdate);
        lcountrows := lcountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomer: Fail to import gainreasoncode/gainreasondesc ' ||
                      vcursor.gainreasoncode || '/' || vcursor.gainreasondesc;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' gainreason rows imported.');
      end;
    end if;
    -- lostreason
    lcountrows := 0;
    for vcursor in (select lostreasoncode, max(lostreasondesc) lostreasondesc
                    from   i_customer
                    where  lostreasoncode is not null
                    and    not exists
                     (select code from gainlostreason where code = lostreasoncode)
                    group  by lostreasoncode
                    order  by lostreasoncode) loop
      begin
        insert into gainlostreason
          (gainlostreason_id, code, systemuser_id, gainreason, timestamp, lostreason)
        values
          (seq_gainlostreason.nextval, vcursor.lostreasoncode, pack_import.lvnsystemuserid, 'N',
           sysdate, 'Y');
        insert into gainlostreason_desc
          (gainlostreason_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_gainlostreason.currval, pack_import.lvnlanguageid,
           nvl(vcursor.lostreasondesc, vcursor.lostreasoncode), pack_import.lvnsystemuserid, sysdate);
        lcountrows := lcountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomer: Fail to import lostreasoncode/lostreasondesc ' ||
                      vcursor.lostreasoncode || '/' || vcursor.lostreasondesc;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' lostreason rows imported.');
      end;
    end if;
    -- gaincompetitor
    lcountrows := 0;
    for vcursor in (select gaincompetitorcode, max(gaincompetitorname) gaincompetitorname
                    from   i_customer
                    where  gaincompetitorcode is not null
                    and    not exists
                     (select code from competitor where code = gaincompetitorcode)
                    group  by gaincompetitorcode
                    order  by gaincompetitorcode) loop
      begin
        insert into competitor
          (competitor_id, code, name, systemuser_id, timestamp)
        values
          (seq_competitor.nextval, vcursor.gaincompetitorcode,
           nvl(vcursor.gaincompetitorname, vcursor.gaincompetitorcode), pack_import.lvnsystemuserid,
           sysdate);
        lcountrows := lcountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomer: Fail to import gaincompetitorcode/gaincompetitorname ' ||
                      vcursor.gaincompetitorcode || '/' || vcursor.gaincompetitorname;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' gaincompetitor rows imported.');
      end;
    end if;
    -- lostcompetitor
    lcountrows := 0;
    for vcursor in (select lostcompetitorcode, max(lostcompetitorname) lostcompetitorname
                    from   i_customer
                    where  lostcompetitorcode is not null
                    and    not exists
                     (select code from competitor where code = lostcompetitorcode)
                    group  by lostcompetitorcode
                    order  by lostcompetitorcode) loop
      begin
        insert into competitor
          (competitor_id, code, name, systemuser_id, timestamp)
        values
          (seq_competitor.nextval, vcursor.lostcompetitorcode,
           nvl(vcursor.lostcompetitorname, vcursor.lostcompetitorcode), pack_import.lvnsystemuserid,
           sysdate);
        lcountrows := lcountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomer: Fail to import lostcompetitorcode/lostcompetitorname ' ||
                      vcursor.lostcompetitorcode || '/' || vcursor.lostcompetitorname;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' lostcompetitor rows imported.');
      end;
    end if;
    --communicationmethod
    lcountrows := 0;
    for vcursor in (select communicationmethodcode,
                           max(communicationmethoddesc) communicationmethoddesc
                    from   i_customer
                    where  not exists
                     (select code from communicationmethod where code = communicationmethodcode)
                    group  by communicationmethodcode
                    order  by communicationmethodcode) loop
      begin
        insert into communicationmethod
          (communicationmethod_id, code, systemuser_id, timestamp, defaultcommunicationmethod)
        values
          (seq_communicationmethod.nextval, vcursor.communicationmethodcode,
           pack_import.lvnsystemuserid, sysdate, 'N');
        insert into communicationmethod_desc
          (communicationmethod_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_communicationmethod.currval, pack_import.lvnlanguageid,
           vcursor.communicationmethoddesc, pack_import.lvnsystemuserid, sysdate);
        lcountrows := lcountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomer: Fail to import communicationmethodcode/description ' ||
                      vcursor.communicationmethodcode || '/' || vcursor.communicationmethoddesc;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' communicationmethod(s) imported.');
      end;
    end if;
    --check default communicationmethod, 1 must be default
    begin
      select count(c.communicationmethod_id)
      into   lcountrows
      from   communicationmethod c
      where  c.defaultcommunicationmethod = 'Y';
      if lcountrows <= 0 then
        begin
          update communicationmethod c
          set    c.defaultcommunicationmethod = 'Y'
          where  c.communicationmethod_id =
                 (select min(x.communicationmethod_id) from communicationmethod x);
          commit;
        end;
      end if;
    exception
      when others then
        begin
          errormsg := ' Warning CFbImportCustomer; it was not possible to check/make 1 communication method default. ';
          pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 2);
        end;
    end;
    -- invoice layout
    lcountrows := 0;
    for vcursor in (select invoicelayoutcode
                    from   i_customer
                    where  invoicelayoutcode is not null
                    and    not exists (select code
                            from   formlayout
                            where  formtype = 'IN'
                            and    code = invoicelayoutcode)
                    group  by invoicelayoutcode
                    order  by invoicelayoutcode) loop
      begin
        insert into formlayout
          (formlayout_id, formtype, code, systemuser_id, timestamp, defaultlayout)
        values
          (seq_formlayout.nextval, 'IN', vcursor.invoicelayoutcode, pack_import.lvnsystemuserid,
           sysdate, 'N');
        insert into formlayout_desc
          (formlayout_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_formlayout.currval, pack_import.lvnlanguageid, vcursor.invoicelayoutcode,
           pack_import.lvnsystemuserid, sysdate);
        lcountrows := lcountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomer: Fail to import invoicelayoutcode ' ||
                      vcursor.invoicelayoutcode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' invoice layout(s) imported.');
      end;
    end if;
    -- chain
    lcountrows := 0;
    for vcursor in (select chaincode, max(chainname) chainname
                    from   i_customer
                    where  chaincode is not null
                    and    not exists
                     (select code from chain where code = i_customer.chaincode)
                    group  by chaincode
                    order  by chaincode) loop
      begin
        insert into chain
          (chain_id, code, name, systemuser_id, timestamp)
        values
          (seq_chain.nextval, vcursor.chaincode, nvl(vcursor.chainname, vcursor.chaincode),
           pack_import.lvnsystemuserid, sysdate);
        lcountrows := lcountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomer: Fail to import chaincode ' || vcursor.chaincode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' chain(s)  imported.');
      end;
    end if;
    --national account
    lcountrows := 0;
    for x in (select trim(c.nationalaccountcode) nationalaccountcode,
                     max(c.nationalaccountname) nationalaccountname
              from   i_customer c
              where  trim(c.nationalaccountcode) is not null
              and    not exists (select a.nationalaccount_id
                      from   nationalaccount a
                      where  a.code = c.nationalaccountcode)
              group  by trim(c.nationalaccountcode)
              order  by trim(c.nationalaccountcode)) loop
      begin
        insert into nationalaccount
          (nationalaccount_id, code, name, systemuser_id, timestamp)
        values
          (seq_nationalaccount.nextval, x.nationalaccountcode,
           nvl(x.nationalaccountname, x.nationalaccountcode), pack_import.lvnsystemuserid, sysdate);
        lcountrows := lcountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomer: Fail to import nationalaccountcode ' ||
                      x.nationalaccountcode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' nationalaccountcode(s) imported.');
      end;
    end if;
    --customerranking
    lcountrows := 0;
    for x in (select z.ranking, max(z.priority) priority
              from   i_customer z
              where  z.ranking is not null
              and    not exists
               (select y.priority from customerranking y where y.ranking = z.ranking)
              group  by z.ranking
              order  by z.ranking) loop
      begin
        select max(nvl(r.priority, 0)) + 1 into lpriority from customerranking r;
        if x.priority > lpriority then
          lpriority := x.priority;
        end if;
        insert into customerranking
          (customerranking_id, priority, ranking, systemuser_id, timestamp)
        values
          (seq_customerranking.nextval, lpriority, x.ranking, pack_import.lvnsystemuserid, sysdate);
        lcountrows := lcountrows + 1;
      exception
        when others then
          errormsg := 'CFbImportCustomer: Fail to import customerranking/priority ' || x.ranking || '/' ||
                      x.priority;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' customerranking(s) imported.');
      end;
    end if;
    --acquisitioncodes
    lcountrows := 0;
    for x in (select z.acquistioncode, max(z.acquistiondescription) acquistiondescription
              from   i_paybycustomer z
              where  z.acquistioncode is not null
              and    not exists
               (select y.code from acquisitioncode y where y.code = z.acquistioncode)
              group  by z.acquistioncode) loop
      begin
        insert into acquisitioncode
          (acquisitioncode_id, code, description, systemuser_id, timestamp)
        values
          (seq_acquisitioncode.nextval, x.acquistioncode,
           nvl(x.acquistiondescription, x.acquistioncode), pack_import.lvnsystemuserid, sysdate);
        lcountrows := lcountrows + 1;
      exception
        when others then
          errormsg := 'CFbImportCustomer: Fail to import acquistioncode ' || x.acquistioncode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' acquistioncode(s) imported.');
      end;
    end if;
    -- cleanroomcustomertype
    lcountrows := 0;
    for vcursor in (select x.cleanroomcustomertype
                    from   i_customer x
                    where  x.cleanroomcustomertype is not null
                    and    not exists (select y.code
                            from   cleanroomcustomertype y
                            where  code = x.cleanroomcustomertype)
                    group  by x.cleanroomcustomertype
                    order  by x.cleanroomcustomertype) loop
      begin
        cleanroomcustomertype_id := pack_import.getcleanroomcustomertype_id(vcursor.cleanroomcustomertype);
        lcountrows               := lcountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomer: Fail to import cleanroomcustomertype ' ||
                      vcursor.cleanroomcustomertype;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' cleanroomcustomertype rows imported.');
      end;
    end if;
    --code label layouts
    lcountrows := 0;
    for x in (select i.codelabellayoutcode, max(i.codelabellayoutdesc) codelabellayoutdesc
              from   i_customer i
              where  i.codelabellayoutcode is not null
              and    not exists (select 1
                      from   labellayout l
                      where  l.code = i.codelabellayoutcode
                      and    l.labeltype = 1)
              group  by i.codelabellayoutcode) loop
      begin
        insert into labellayout
          (labellayout_id, code, description, labeltype, defaultlayout, systemuser_id, timestamp,
           layoutreceiveonstock, sterile)
        values
          (seq_labellayout.nextval, x.codelabellayoutcode,
           nvl(x.codelabellayoutdesc, x.codelabellayoutcode), 1, 'N', pack_import.lvnsystemuserid,
           sysdate, 'N', 'N');
        lcountrows := lcountrows + 1;
      exception
        when others then
          errormsg := 'CFbImportCustomer: code label layouts ' || x.codelabellayoutcode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' code label layout(s) imported.');
      end;
    end if;
    --name label layouts
    lcountrows := 0;
    for x in (select i.namelabellayoutcode, max(i.namelabellayoutdesc) namelabellayoutdesc
              from   i_customer i
              where  i.namelabellayoutcode is not null
              and    not exists (select 1
                      from   labellayout l
                      where  l.code = i.namelabellayoutcode
                      and    l.labeltype = 2)
              group  by i.namelabellayoutcode) loop
      begin
        insert into labellayout
          (labellayout_id, code, description, labeltype, defaultlayout, systemuser_id, timestamp,
           layoutreceiveonstock, sterile)
        values
          (seq_labellayout.nextval, x.namelabellayoutcode,
           nvl(x.namelabellayoutdesc, x.namelabellayoutcode), 2, 'N', pack_import.lvnsystemuserid,
           sysdate, 'N', 'N');
        lcountrows := lcountrows + 1;
      exception
        when others then
          errormsg := 'CFbImportCustomer: name label layouts ' || x.namelabellayoutcode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    commit; --commit all for this procedure.
    if lcountrows > 0 then
      begin
        pack_import.write_log(lcountrows || ' code label layout rows imported.');
      end;
    end if;
  exception
    when others then
      begin
        --rollback all
        rollback;
        errormsg := 'cfbimportcustomerfixedinfo: Failed to import.';
        pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimportcustomerfixedinfo;
  ---customerbillinginfo
  procedure cfbimportcustomerbillinginfo is
    frequencyid              invoicefrequency.invoicefrequency_id%type;
    ispaybycustomer          customerbillinginfo.paybycustomer%type;
    paybycustomernumberid    customerbillinginfo.paybycustomer_link_id%type;
    lvprintinvoice           customerbillinginfo.printinvoice%type;
    lcollectionresponsibleid customerbillinginfo.collectionresponsible_id%type;
    lcountrows               integer;
  begin
    lcountrows := 0;
    for vcursor in (select i.paymenttermcode, max(i.paymenttermdesc) paymenttermdesc
                    from   i_billtoaccount i
                    where  not exists
                     (select 1 from paymentterms pt where pt.code = i.paymenttermcode)
                    group  by i.paymenttermcode) loop
      begin
        insert into paymentterms
          (defaultpaymentterm, active, code, paymentterms_id, timestamp, systemuser_id,
           netpaymentdays, discountdays, discountdays2, paymentdiscount, paymentdiscount2)
        values
          ('N', 'Y', vcursor.paymenttermcode, seq_paymentterms.nextval, sysdate,
           pack_import.lvnsystemuserid, 0, 0, 0, 0, 0);
        insert into paymentterms_desc
          (paymentterms_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_paymentterms.currval, pack_import.lvnlanguageid, vcursor.paymenttermdesc,
           pack_import.lvnsystemuserid, sysdate);
        lcountrows := lcountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          begin
            errormsg := 'CFbImportCustomerBillingInfo: Fail to import paymentterms code/description ' ||
                        vcursor.paymenttermcode || '/' || vcursor.paymenttermdesc;
            pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
          end;
      end;
    end loop;
    if lcountrows > 0 then
      begin
        commit;
        pack_import.write_log(lcountrows || ' paymentterm(s) imported.');
      end;
    end if;
    -- insert new billtorecords
    lcountrows := 0;
    for vcursor in (select a.*, d.customer_id, t.paymentterms_id,
                           (select fl.formlayout_id
                             from   formlayout fl
                             where  fl.code = a.statementlayout
                             and    fl.formtype = 'ST') statementlayout_id,
                           (select fli.formlayout_id
                             from   formlayout fli
                             where  fli.code = a.consolidatedinvoicelayout
                             and    fli.formtype = 'CI') consolidatedinvoicelayout_id,
                           (select u.plant_id
                             from   businessunit u
                             where  u.businessunit_id = d.defaultbusinessunit_id) plant_id
                    from   i_billtoaccount a, customer d, paymentterms t
                    where  a.customernumber = d.customernumber
                    and    t.code(+) = a.paymenttermcode
                    and    not exists (select i.customer_id
                            from   customerbillinginfo i
                            where  i.customer_id = d.customer_id)) loop
      begin
        begin
          if vcursor.statementfrequency = 1 then
            frequencyid := 110; -- from 100 to 110 monthly
          end if;
          if vcursor.statementfrequency = 2 then
            frequencyid := 45; --week schedule
          end if;
          if vcursor.statementfrequency = 3 then
            frequencyid := 10; --weekly
          end if;
          --i_paybycustomer processing
          begin
            select i.ispaybycustomer,
                   (select c.customer_id
                     from   customer c
                     where  c.customernumber = i.paybycustomernumber)
            into   ispaybycustomer, paybycustomernumberid
            from   i_paybycustomer i
            where  i.customernumber = vcursor.customernumber;
          exception
            when no_data_found then
              begin
                ispaybycustomer       := 0;
                paybycustomernumberid := null;
              end;
          end;
          begin
            --get printinvoice from i_customer
            select i.printinvoice
            into   lvprintinvoice
            from   i_customer i
            where  i.customernumber = vcursor.customernumber;
          exception
            when no_data_found then
              begin
                lvprintinvoice := 1;
              end;
          end;
          --collectresponsible
          begin
            if vcursor.collectionresponsible_number is null then
              lcollectionresponsibleid := null;
            else
              pack_import.cfbgetcreate_employee(vcursor.plant_id, lcollectionresponsibleid,
                                                vcursor.collectionresponsible_number,
                                                vcursor.collectionresponsible_name,
                                                nvl(substr(vcursor.collectionresponsible_name, 1, 10),
                                                     '-'), to_date('1-1-2002', 'DD-MM-YYYY'), null,
                                                null, null, null, null);
            end if;
          exception
            when others then
              begin
                errormsg := 'CFbImportCustomerBillingInfo error retrieve collectionresponsible: ';
                pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
                lcollectionresponsibleid := null;
              end;
          end;
          pack_import.cfbcreate_customerbillinginfo(vcursor.customer_id,
                                                    vcursor.delinquentmarkafter, vcursor.creditlimit,
                                                    vcursor.financechargeputon,
                                                    vcursor.financechargedays,
                                                    vcursor.statementcopies,
                                                    vcursor.statementpercustomer,
                                                    vcursor.attachinvoicecopies, frequencyid,
                                                    vcursor.sendstatement,
                                                    vcursor.sendstatementbyemail,
                                                    lcollectionresponsibleid,
                                                    vcursor.paymentterms_id,
                                                    nvl(vcursor.statementlayout_id, formlayoutst), 0,
                                                    sysdate, nvl(vcursor.consolidatedinvoice, 'N'),
                                                    vcursor.bankaccount, vcursor.creditsqueezeper,
                                                    null, nvl(vcursor.consolidatedinvreport, 'N'),
                                                    null, null, ispaybycustomer,
                                                    paybycustomernumberid, lvprintinvoice,
                                                    vcursor.sendinvoiceby,
                                                    vcursor.consolidatedinvoicelayout_id,
                                                    vcursor.generatepayment,
													vcursor.senddirectinvoicebyemail);
          commit;
          lcountrows := lcountrows + 1;
        exception
          when dup_val_on_index then
            null;
          when others then
            begin
              rollback;
              errormsg := 'CFbImportCustomerBillingInfo: Fail to import customerbillinginfo ' ||
                          vcursor.customernumber;
              pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
            end;
        end;
        if vcursor.remarkonstatement is not null then
          begin
            update customerbillingcomment
            set    description = vcursor.remarkonstatement, type = 2,
                   systemuser_id = pack_import.lvnsystemuserid
            where  customer_id = vcursor.customer_id;
          exception
            when no_data_found then
              begin
                insert into customerbillingcomment
                  (customer_id, timestamp, systemuser_id, enddate, startdate, description, type)
                values
                  (vcursor.customer_id, sysdate, pack_import.lvnsystemuserid,
                   to_date('31/12/2099', 'DD/MM/YYYY'), to_date('01/01/2002', 'DD/MM/YYYY'),
                   vcursor.remarkonstatement, 2);
              end;
          end;
        end if;
        commit;
      exception
        when dup_val_on_index then
          null;
        when others then
          rollback;
          errormsg := 'CFbImportCustomerBillingInfo error: ';
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    -- add invoice address to debtors without an invoice address.
    for x in (select c.customer_id, c.customernumber
              from   customer c, i_customer i
              where  c.customer_id = c.debtor_id
              and    i.customernumber = c.customernumber
              and    c.invoiceaddress_id is null) loop
      begin
        insert into address
          (address_id, street, street2, zipcode, city, state, systemuser_id, county, timestamp)
          select seq_address.nextval, b.street, b.street2, b.zipcode, b.city, b.state,
                 b.systemuser_id, b.county, sysdate
          from   customer a, address b
          where  a.mailaddress_id = b.address_id
          and    a.customer_id = x.customer_id;
        update customer
        set    invoiceaddress_id = seq_address.currval
        where  customer_id = x.customer_id;
      exception
        when others then
          pack_import.write_log('Warning: failed adding invoice address debtor of customer ' ||
                                to_char(x.customernumber) || ' ' || substr(sqlerrm, 1, 512), 2);
      end;
    end loop;
    commit;
    -- log file messages
    pack_import.write_log(lcountrows || ' customer billing info rows imported.');
    -- import creditcards
    cfbimport_creditcards;
    -- import additional customer tables
    import_visitmonths;
    import_customerenvinfo;
  end cfbimportcustomerbillinginfo;
  --import customerbudgetdefinition
  procedure cfbimport_customerbudget is
    lvcounter                     number := 0;
    lvcustomerid                  customer.customer_id%type;
    lvbudgetunitid                budgetunit.budgetunit_id%type;
    lv_customerbudgetdefinitionid customerbudgetdefinition.customerbudgetdefinition_id%type;
  begin
    --cfbimport_customerbudget
    errormsg := 'cfbimport_customerbudget';
    for x in (select ifb.* from i_customerbudgetdefinition ifb) loop
      begin
        --get customer number
        errormsg := 'customer number ' || x.customernumber;
        select c.customer_id
        into   lvcustomerid
        from   customer c
        where  c.customernumber = x.customernumber;
        --get budgetunitcode
        errormsg := 'get budgetunitcode ' || x.budgetunitcode;
        pack_import.cfbget_create_budgetunit(lvbudgetunitid, x.budgetunitcode,
                                             x.budgetunitdescription);
        --insert into customerbudgetdefinition
        errormsg := ' insert into customerbudgetdefinition budgetcode ' || x.budgetcode;
        insert into customerbudgetdefinition
          (customerbudgetdefinition_id, customer_id, code, description, budgetunit_id, startdate,
           enddate, budgettype, usedforinvoicing, usedforreporting, systemuser_id, timestamp)
        values
          (seq_customerbudgetdefinition.nextval, lvcustomerid, x.budgetcode,
           coalesce(x.budgetdescription, x.budgetcode, '-'), lvbudgetunitid,
           nvl(x.startdate, trunc(sysdate - 1)), nvl(x.enddate, to_date('31-12-2099', 'dd-mm-yyyy')),
           case when lvbudgetunitid is null then 1 else 0 end, nvl(x.usedforinvoicing, 'Y'),
           nvl(x.usedforreporting, 'Y'), pack_import.lvnsystemuserid, sysdate)
        returning customerbudgetdefinition_id into lv_customerbudgetdefinitionid;
        if x.price is not null then
          begin
            insert into customerbudgetprice
              (customerbudgetprice_id, customerbudgetdefinition_id, startdate, price, systemuser_id,
               timestamp)
            values
              (seq_customerbudgetprice.nextval, lv_customerbudgetdefinitionid,
               nvl(x.startdate, trunc(sysdate - 1)), x.price, pack_import.lvnsystemuserid, sysdate);
          end;
        end if;
        --count rows inserted
        lvcounter := lvcounter + 1;
      exception
        when no_data_found then
          pack_import.write_log('Error during import customerbudget, no data found ' || errormsg, 3);
        when dup_val_on_index then
          null; --no problem if it is already there
      end;
    end loop; --x
    commit;
    if lvcounter > 0 then
      pack_import.write_log(lvcounter || ' customer budget definition rows imported.');
    end if;
  exception
    when others then
      begin
        rollback;
        errormsg := 'cfbimport_customerbudget: Failed to import.';
        pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_customerbudget;
  procedure imp_customer_budgetprotection is
    lvcounter number := 0;
  begin
    --imp_customer_budgetprotection
    errormsg := 'imp_customer_budgetprotection';
    for pp in (select c.customer_id, i.customernumber, i.businessunit,
                      i.materialmaintenancepercentage, i.garmentsetup, i.garmentmaintenance,
                      i.garmentloss, i.garmentrepair, i.mbyoppercentage, i.garmentlosspercentage,
                      i.garmentemblem
               from   i_customer i
               join   customer c
               on     c.customernumber = i.customernumber) loop
      begin
        --insert customerbudgetprotection
        insert into customerbudgetprotection
          (customer_id, materialmaintenancepercentage, garmentsetup, garmentmaintenance,
           garmentloss, garmentrepair, systemuser_id, timestamp, mbyoppercentage,
           garmentlosspercentage, garmentemblem)
        values
          (pp.customer_id, nvl(pp.materialmaintenancepercentage, 0), nvl(pp.garmentsetup, 'N'),
           nvl(pp.garmentmaintenance, 'N'), nvl(pp.garmentloss, 'N'), nvl(pp.garmentrepair, 'N'),
           pack_import.lvnsystemuserid, sysdate, nvl(pp.mbyoppercentage, 0),
           nvl(pp.garmentlosspercentage, 100), nvl(pp.garmentemblem, 'N'));
        --count rows inserted
        lvcounter := lvcounter + 1;
      exception
        when dup_val_on_index then
          null; --no problem if it is already there
      end;
    end loop;
    commit;
    if lvcounter > 0 then
      pack_import.write_log(lvcounter || ' Customer Budget Protection rows imported.');
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('imp_customer_budgetprotection: Failed to import ' ||
                              substr(sqlerrm, 1, 512), 3);
      end;
  end imp_customer_budgetprotection;
  procedure cfbprocess_sortcustomer is
    lv_counter number := 0;
  begin
    --process_sortcustomer
    for y in (select c.customer_id, s.customer_id sortcustomer_id,
                     i.maincustomertype convcustomertype, s.maincustomertype, i.customernumber,
                     i.sortcustomernumber
              from   i_customer i
              join   customer c
              on     c.customernumber = i.customernumber
              join   customer s
              on     s.customernumber = i.sortcustomernumber
              where  c.sortcustomer_id is null
              and    i.maincustomertype = 3) loop
      begin
        --REMARK UPDATE ALSO EXISTING CUSTOMERS!!
        --main customer has type 3, sort customer has type 2, so its ok to link them
        if y.maincustomertype = 3 then
          --if may never be a main customer type 3!
          raise no_data_found;
        else
          if y.maincustomertype = 1 then
            begin
              --this is the sort customer that will be linked, we can fix customers with 1 not with 3
              update customer c
              set    c.maincustomertype = 2, c.timestamp = sysdate,
                     c.systemuser_id = pack_import.lvnsystemuserid
              where  c.customer_id = y.sortcustomer_id;
              lv_counter := lv_counter + 1;
            end;
          end if;
        end if;
        --this is the main customer
        update customer c
        set    c.maincustomertype = 3, c.sortcustomer_id = y.sortcustomer_id, c.timestamp = sysdate,
               c.systemuser_id = pack_import.lvnsystemuserid
        where  c.customer_id = y.customer_id;
        lv_counter := lv_counter + 1;
      exception
        when no_data_found then
          begin
            pack_import.write_log(' Main customer ' || to_char(y.customernumber) ||
                                  ' cannot be linked to a valid sort customer ' ||
                                  to_char(y.sortcustomernumber) ||
                                  ' because it has maincustomertype ' ||
                                  to_char(y.maincustomertype), 3);
          end;
      end;
    end loop;
    if lv_counter > 0 then
      begin
        pack_import.write_log(to_char(lv_counter) || ' sort-customer(s) maincustomertype updated');
      end;
    end if;
    commit;
  end cfbprocess_sortcustomer;
  procedure cfbprocess_maindeliverypoint is
    lv_sortdeliverypointid deliverypoint.deliverypoint_id%type;
    lv_convdeliverypointid deliverypoint.deliverypoint_id%type;
    lv_counter             number := 0;
  begin
    --cfbprocess_maindeliverypoint
    for t in (select idp.customernumber convcustomernumber, idp.maincustomerdeliverypoint,
                     s.customernumber sortcustomernumber, s.maincustomertype sortmaincustomertype,
                     c.maincustomertype convmaincustomertype, s.customer_id sortcustomer_id,
                     c.customer_id convcustomer_id, idp.deliveryaddress_street,
                     idp.deliverypointcode convdeliverypointcode
              from   i_deliverypoint idp
              join   customer c
              on     c.customernumber = idp.customernumber
              left   outer join customer s
              on     s.customer_id = c.sortcustomer_id
              where  idp.maincustomerdeliverypoint is not null) loop
      begin
        --1=not applicable,  2=main customer,  3=belongs to a parent (main)customer
        if nvl(t.convmaincustomertype, 0) = 3 and nvl(t.sortmaincustomertype, 0) = 2 then
          begin
            lv_counter := lv_counter + cfbimport_deliverypoint(t.sortcustomer_id);
            --select main customer deliverypoint
            errormsg := 'main customer deliverypoint ' || t.maincustomerdeliverypoint ||
                        ' for customer ' || to_char(t.sortcustomernumber);
            select p.deliverypoint_id
            into   lv_sortdeliverypointid
            from   deliverypoint p
            where  p.code = t.maincustomerdeliverypoint
            and    p.customer_id = t.sortcustomer_id;
            --select original delivery point
            lv_counter := lv_counter + cfbimport_deliverypoint(t.convcustomer_id);
            errormsg   := 'customer deliverypoint ' || t.convdeliverypointcode || ' for customer ' ||
                          to_char(t.convcustomernumber);
            select p.deliverypoint_id
            into   lv_convdeliverypointid
            from   deliverypoint p
            where  p.code = t.convdeliverypointcode
            and    p.customer_id = t.convcustomer_id;
            --update deliverypoint
            errormsg := 'update deliverypoint id ' || lv_convdeliverypointid ||
                        ' with main delpoint id ' || lv_sortdeliverypointid;
            update deliverypoint dp
            set    dp.maincustomerdeliverypoint_id = lv_sortdeliverypointid
            where  dp.deliverypoint_id = lv_convdeliverypointid;
          exception
            when no_data_found then
              begin
                pack_import.write_log(errormsg || ' does not exist!', 3);
              end;
          end;
        else
          begin
            pack_import.write_log('Error linking main customer deliverypoint ' ||
                                  t.maincustomerdeliverypoint || ' from customer ' ||
                                  to_char(t.sortcustomernumber) || ' type ' ||
                                  nvl(to_char(t.sortmaincustomertype), 'NULL') || ' to customer ' ||
                                  to_char(t.convcustomernumber) || ' type ' ||
                                  nvl(to_char(t.convmaincustomertype), 'NULL') ||
                                  ' because the maincustomertypes are not ok', 3);
          end;
        end if;
      end;
    end loop; --t
    commit;
    if lv_counter > 0 then
      begin
        pack_import.write_log('Extra ' || to_char(lv_counter) || ' deliverypoints converted');
      end;
    end if;
  end cfbprocess_maindeliverypoint;
  --import customerprepcharge
  procedure cfbimport_customerprepcharge is
    lv_counter      number := 0;
    lv_customerid   customer.customer_id%type;
    lv_reasoncodeid reasoncode.reasoncode_id%type;
  begin
    --cfbimport_customerprepcharge
    errormsg := 'cfbimport_customerprepcharge';
    for x in (select icpc.* from i_customerprepcharge icpc) loop
      begin
        --get customer number
        errormsg := 'customer number ' || x.customernumber;
        select c.customer_id
        into   lv_customerid
        from   customer c
        where  c.customernumber = x.customernumber;
        if x.reasoncode is null then
          begin
            lv_reasoncodeid := null;
          end;
        else
          begin
            --get reasoncode
            select rs.reasoncode_id
            into   lv_reasoncodeid
            from   reasoncode rs
            where  rs.code = trim(upper(x.reasoncode));
          exception
            when no_data_found then
              begin
                --get reasoncode
                pack_import.cfbcreate_reasoncode(lv_reasoncodeid, trim(upper(x.reasoncode)));
                pack_import.cfbcreate_reasoncode_desc(lv_reasoncodeid, x.reasoncode);
              end;
          end;
        end if;
        --insert into customerprepcharge
        errormsg := ' insert into customerprepcharge';
        insert into customerprepcharge
          (customerprepcharge_id, customer_id, price, startdate, systemuser_id, timestamp,
           reasoncode_id)
        values
          (seq_customerprepcharge.nextval, lv_customerid, x.price, x.startdate,
           pack_import.lvnsystemuserid, sysdate, lv_reasoncodeid);
        --check customer to use chargeprecharges
        update customer c
        set    c.chargeprecharges = 'Y'
        where  c.customer_id = lv_customerid
        and    c.chargeprecharges <> 'Y';
        --count rows inserted
        lv_counter := lv_counter + 1;
      exception
        when no_data_found then
          pack_import.write_log('Error during import customerprepcharge, no data found ' ||
                                errormsg, 3);
        when dup_val_on_index then
          null; --no problem if it is already there
      end;
    end loop; --x
    if lv_counter > 0 then
      begin
        commit;
        pack_import.write_log(lv_counter || ' customer prep charge rows imported.');
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        errormsg := 'cfbimport_customerprepcharge: Failed to import.';
        pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_customerprepcharge;
  procedure link_common_customer is
    lv_rowcount number := 0;
  begin
    --link_common_customer
    update customer c
    set    c.commoncustomer_id =
            (select com.customer_id
             from   customer com
             join   i_customer i
             on     i.commoncustomer = com.customernumber
             where  i.customerrelated = 4
             and    i.customernumber = c.customernumber), c.timestamp = sysdate,
           c.systemuser_id = pack_import.lvnsystemuserid
    where  c.customerrelated = 4
    and    c.commoncustomer_id is null
    and    exists (select 1
            from   customer com
            join   i_customer i
            on     i.commoncustomer = com.customernumber
            where  i.customerrelated = 4
            and    i.customernumber = c.customernumber);
    lv_rowcount := sql%rowcount;
    if lv_rowcount > 0 then
      begin
        pack_import.write_log(to_char(lv_rowcount) || ' customers linked to a common customer.');
      end;
    end if;
    commit;
  exception
    when others then
      begin
        pack_import.write_log('link_common_customer: Failed to link common customer(s) ' ||
                              substr(sqlerrm, 1, 512), 3);
      end;
  end link_common_customer;
  procedure link_other_customer is
    lv_rowcount number := 0;
  begin
    --link_other_customer
    update customer c
    set    c.othercustomer_id =
            (select oth.customer_id
             from   customer oth
             join   i_customer i
             on     i.othercustomer = oth.customernumber
             where  i.customerrelated = 5
             and    i.customernumber = c.customernumber), c.timestamp = sysdate,
           c.systemuser_id = pack_import.lvnsystemuserid
    where  c.customerrelated = 5
    and    c.othercustomer_id is null
    and    exists (select 1
            from   customer oth
            join   i_customer i
            on     i.othercustomer = oth.customernumber
            where  i.customerrelated = 5
            and    i.customernumber = c.customernumber);
    lv_rowcount := sql%rowcount;
    if lv_rowcount > 0 then
      begin
        pack_import.write_log(to_char(lv_rowcount) || ' customers linked to a other customer.');
      end;
    end if;
    commit;
  exception
    when others then
      begin
        pack_import.write_log('link_other_customer: Failed to link other customer(s) ' ||
                              substr(sqlerrm, 1, 512), 3);
      end;
  end link_other_customer;
  procedure import_customerach is
    lv_count number := 0;
  begin
    --import_customerach
    errormsg := 'import_customerach';
    for x in (select ic.*, c.customer_id, c.dateactive
              from   i_customerach ic
              join   customer c
              on     c.customernumber = ic.customernumber
              where  not exists (select 1 from customerach ac where ac.customer_id = c.customer_id)) loop
      begin
        insert into customerach
          (customer_id, token, accountnumber, routingnumber, createddate, systemuser_id, timestamp)
        values
          (x.customer_id, x.token, x.accountnumber, x.routingnumber,
           coalesce(x.createddate, x.dateactive), pack_import.lvnsystemuserid, sysdate);
        --count rows processed
        lv_count := lv_count + 1;
      end;
    end loop; --x
    commit;
    if lv_count > 0 then
      begin
        pack_import.write_log(to_char(lv_count) || ' customers ach rows imported.');
      end;
    end if;
  exception
    when others then
      begin
        pack_import.write_log('Error import customerach  ' || substr(sqlerrm, 1, 512), 3);
      end;
  end import_customerach;
  --customer
  procedure cfbimportcustomer is
    ---import Customer
    missing_bussinessunits  exception;
    countrowsd              integer;
    countrowsm              integer;
    countexisting           integer;
    mail_address            address.street%type;
    mail_address2           address.street2%type;
    mail_state              address.state%type;
    mail_county             address.county%type;
    mail_city               address.city%type;
    mail_zipcode            address.zipcode%type;
    deliveryaddressid       address.address_id%type;
    invoiceaddressid        address.address_id%type;
    billingaddress          varchar2(256);
    billingzipcode          varchar2(256);
    billingcity             varchar2(256);
    billingstate            varchar2(256);
    billingcounty           varchar2(256);
    billingaddress2         varchar2(256);
    billingtaxareaid        addresstaxareaid.taxareaid%type;
    billconfindicator       addresstaxareaid.confidenceindicator%type;
    nationalaccountid       nationalaccount.nationalaccount_id%type;
    ndepartmentcounter      number := 0;
    ndeliverypointcounter   number := 0;
    fpnserviceemployee_id   customer.serviceemployee_id%type;
    fpbbonusagreement       customer.bonusagreement%type;
    fpnacquisioncode_id     customer.acquisioncode_id%type;
    fpncustomerranking_id   customer.customerranking_id%type;
    fpntdccode              customer.tdccode%type;
    ledicontactperson       contactperson.contactperson_id%type;
    lmissingbusinessunits   integer;
    lvncountdays            integer;
    lvnsalesemployee1id     customer.salesemployee1_id%type;
    lvnsalesemployee2id     customer.salesemployee2_id%type;
    lvninvoicefrequency     i_customer.invoicefrequency%type;
    lvncheck_billto         number;
    lvninternalbu           businessunit.businessunit_id%type;
    lvndefaultinvbu         businessunit.businessunit_id%type;
    lvncountrows            integer;
    lvncleanroomcusttype_id cleanroomcustomertype.cleanroomcustomertype_id%type;
    procedure add_customerrestockingfeeprice(fp_price          in customerrestockingfeeprice.price%type,
                                             fp_startdate      in customerrestockingfeeprice.startdate%type,
                                             fp_customernumber in number) is
    begin
      --add_customerrestockingfeeprice
      if fp_price is not null then
        begin
          insert into customerrestockingfeeprice
            (customerrestockingfeeprice_id, customer_id, price, startdate, systemuser_id, timestamp)
          values
            (seq_customerrestockingfeeprice.nextval, customerid, fp_price,
             nvl(fp_startdate, trunc(sysdate) - 1), pack_import.lvnsystemuserid, sysdate);
        end;
      end if;
    exception
      when others then
        begin
          pack_import.write_log('Error add customerrestockingfeeprice for customer ' ||
                                to_char(fp_customernumber) || ' error: ' ||
                                substr(sqlerrm, 1, 512), 3);
        end;
    end add_customerrestockingfeeprice;
    procedure add_customerlockermanagement is
    begin
      --add_customerlockermanagement, all customer in i_customer
      insert into customerlockermanagement
        (customer_id, uselockerobligated, chargerent, chargeservice, fixednumberbank, systemuser_id,
         timestamp, showlockeronroutelist)
        select c.customer_id, 'Y', 0, 0, 0, pack_import.lvnsystemuserid, sysdate, 'N'
        from   i_customer i
        join   customer c
        on     c.customernumber = i.customernumber
        where  i.uselockerobligated = 'Y'
        and    not exists
         (select 1 from customerlockermanagement clm where clm.customer_id = c.customer_id);
      commit;
    exception
      when others then
        begin
          pack_import.write_log('Error add customerlockermanagement: ' || substr(sqlerrm, 1, 512),
                                3);
        end;
    end add_customerlockermanagement;
  begin
    select count(*)
    into   lmissingbusinessunits
    from   i_customer i
    where  not exists
     (select u.businessunit_id from businessunit u where u.code = to_char(i.businessunit));
    if lmissingbusinessunits > 0 then
      raise missing_bussinessunits;
    end if;
    cfbimportcustomerfixedinfo;
    select count(c.customer_id) into countexisting from customer c;
    begin
      execute immediate 'alter table CUSTOMER disable constraint CHECK_MASTERACCOUNT3';
    exception
      when others then
        null;
    end;
    -- customer - debtor - masteraccount
    lvncountrows := 0; --insert customer
    for vcursor in (select a.*, b.businessunit_id, c.marketsegment_id, d.salesarea_id,
                           e.qualitygrade_id firstdaysgradeid, f.qualitygrade_id firstissuegradeid,
                           g.qualitygrade_id, h.formlayout_id, i.states_id,
                           (select min(j.citycounty_id)
                             from   citycounty j
                             where  a.citytaxauthoritycode = j.taxauthoritycode
                             and    j.type = 1
                             and    j.states_id = i.states_id) city_id,
                           (select min(jj.citycounty_id)
                             from   citycounty jj
                             where  a.countytaxauthoritycode = jj.taxauthoritycode
                             and    jj.type = 2
                             and    jj.states_id = i.states_id) county_id, x.communicationmethod_id,
                           z.chain_id, cc.cluster_id, o.country_id, u.currency_id,
                           (select l.labellayout_id
                             from   labellayout l
                             where  l.code = a.codelabellayoutcode
                             and    l.labeltype = 1) codelabellayout_id,
                           (select l.labellayout_id
                             from   labellayout l
                             where  l.code = a.namelabellayoutcode
                             and    l.labeltype = 2) namelabellayout_id, b.plant_id,
                           (select lg.language_id from languages lg where lg.code = a.languagecode) language_id,
                           (select cc.currency_id from currency cc where cc.code = a.invoicecurrency) invoicecurrencyid,
                           case
                             when a.restockingprice is not null then
                              'Y'
                             else
                              'N'
                           end chargerestockingfee,
                           (select m.maatemplateheader_id
                             from   maatemplateheader m
                             where  m.code = a.raatemplateheader) maatemplateheader_id
                    from   i_customer a, businessunit b, marketsegment c, salesarea d, qualitygrade e,
                           qualitygrade f, qualitygrade g, formlayout h, states i,
                           communicationmethod x, chain z, customercluster cc, country o, currency u
                    where  to_char(a.businessunit) = b.code
                    and    a.marketsegmentcode = c.code
                    and    a.salesareacode = d.code
                    and    a.firstdaysgradecode = e.code(+)
                    and    a.firstissuegradecode = f.code(+)
                    and    a.qualitygradecode = g.code(+)
                    and    (a.invoicelayoutcode = h.code and h.formtype = 'IN')
                    and    a.statetaxauthoritycode = i.taxauthoritycode(+)
                    and    a.communicationmethodcode = x.code
                    and    a.chaincode = z.code(+)
                    and    a.invoiceclusteringcode = cc.code(+)
                    and    a.country = o.code
                    and    a.currency = u.code
                    and    not exists (select customer.customernumber
                            from   customer
                            where  a.customernumber = customernumber)) loop
      begin
        --mailaddress
        if vcursor.mailstate is null then
          mail_state := vcursor.deliverystate;
        else
          mail_state := vcursor.mailstate;
        end if;
        if vcursor.mailcounty is null then
          mail_county := vcursor.deliverycounty;
        else
          mail_county := vcursor.mailcounty;
        end if;
        if vcursor.mailcity is null then
          mail_city := vcursor.deliverycity;
        else
          mail_city := vcursor.mailcity;
        end if;
        if vcursor.mailzipcode is null then
          mail_zipcode := vcursor.deliveryzipcode;
        else
          mail_zipcode := vcursor.mailzipcode;
        end if;
        if vcursor.mailaddress is null then
          mail_address := vcursor.deliveryaddress;
        else
          mail_address := vcursor.mailaddress;
        end if;
        if vcursor.mailaddress2 is null then
          mail_address2 := vcursor.deliveryaddress2;
        else
          mail_address2 := vcursor.mailaddress2;
        end if;
        --lvninternalbu
        if vcursor.internalbusinessunitcode is null then
          lvninternalbu := vcursor.businessunit_id;
        else
          errormsg := 'internal businessunit code ' || vcursor.internalbusinessunitcode;
          select bu.businessunit_id
          into   lvninternalbu
          from   businessunit bu
          where  bu.code = vcursor.internalbusinessunitcode;
        end if;
        --lvndefaultinvbu
        if vcursor.invoicebusinessunitcode is null then
          lvndefaultinvbu := vcursor.businessunit_id;
        else
          errormsg := 'default invoice businessunit code ' || vcursor.invoicebusinessunitcode;
          select bu.businessunit_id
          into   lvndefaultinvbu
          from   businessunit bu
          where  bu.code = vcursor.invoicebusinessunitcode;
        end if;
        if trim(vcursor.nationalaccountcode) is not null then
          begin
            select n.nationalaccount_id
            into   nationalaccountid
            from   nationalaccount n
            where  n.code = vcursor.nationalaccountcode;
          exception
            when others then
              begin
                errormsg := 'Warning with nationalaccountcode ' || vcursor.nationalaccountcode;
                pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 2);
                nationalaccountid := null;
              end;
          end;
        else
          nationalaccountid := null;
        end if;
        -- deliveryaddressid
        deliveryaddressid := getaddressid(vcursor.deliveryaddress, vcursor.deliveryzipcode,
                                          vcursor.deliverycity, vcursor.deliverystate,
                                          vcursor.deliverycounty, vcursor.deliveryaddress2,
                                          vcursor.deliverytaxareaid,
                                          vcursor.deliveryconfidenceindicator,
                                          vcursor.deliveryaddress3);
        begin
          -- invoice address.
          select billingaddress, billingzipcode, billingcity, billingstate, billingcounty,
                 billingaddress2, nvl(b.invoicefrequency, 0), b.billingtaxareaid,
                 b.billingconfidenceindicator
          into   billingaddress, billingzipcode, billingcity, billingstate, billingcounty,
                 billingaddress2, lvninvoicefrequency, billingtaxareaid, billconfindicator
          from   i_billtoaccount b
          where  b.customernumber = vcursor.accountnumber;
          invoiceaddressid := getaddressid(billingaddress, billingzipcode, billingcity, billingstate,
                                           billingcounty, billingaddress2, billingtaxareaid,
                                           billconfindicator, null);
        exception
          when others then
            begin
              if lvninvoicefrequency is null then
                lvninvoicefrequency := 0; --default is 0
              end if;
              if vcursor.masteraccount <> 2 then
                begin
                  -- debtor information did not exists in for i_billtoaccount this customers
                  errormsg := 'CFbImportCustomer: Warning no invoice address/customer billing info for customernumber ' ||
                              vcursor.customernumber || ' from its bill to customer ' ||
                              vcursor.accountnumber;
                  pack_import.write_log(errormsg, 2);
                end;
              end if;
              --check if bill to exists, if not create bill to for customer
              select count(1)
              into   lvncheck_billto
              from   i_customer i
              where  i.customernumber = vcursor.accountnumber;
              if lvncheck_billto <> 1 then
                begin
                  insert into i_billtoaccount
                    (customernumber, billingcity, billingzipcode, statementfrequency, sendstatement)
                  values
                    (vcursor.customernumber, mail_city, mail_zipcode, 3, 3);
                exception
                  when dup_val_on_index then
                    null;
                end;
              else
                insert into i_billtoaccount
                  (customernumber, billingcity, billingzipcode, statementfrequency, sendstatement)
                values
                  (vcursor.accountnumber, mail_city, mail_zipcode, 3, 3);
              end if;
              invoiceaddressid := getaddressid(vcursor.mailaddress, vcursor.mailzipcode,
                                               vcursor.mailcity, vcursor.mailstate,
                                               vcursor.mailcounty, vcursor.mailaddress2,
                                               vcursor.mailtaxareaid, vcursor.mailconfidenceindicator,
                                               vcursor.mailaddress3);
            exception
              when others then
                begin
                  invoiceaddressid := null;
                  if vcursor.masteraccount <> 2 then
                    begin
                      errormsg := 'CFbImportCustomer: Error adding missing customer billing info for i_customers# /  account# ' ||
                                  vcursor.customernumber || ' / ' || vcursor.accountnumber;
                      pack_import.write_log(errormsg, 3);
                      pack_import.write_log(substr(sqlerrm, 1, 512), 5);
                    end;
                  end if;
                end;
            end;
        end;
        customerid := -1;
        --sales employee 1
        if vcursor.salesemployeenumber1 is null then
          lvnsalesemployee1id := null;
        else
          begin
            pack_import.cfbgetcreate_employee(vcursor.plant_id, lvnsalesemployee1id,
                                              vcursor.salesemployeenumber1,
                                              vcursor.salesemployeename1,
                                              nvl(substr(vcursor.salesemployeename1, 1, 10), '-'),
                                              to_date('1-1-2002', 'DD-MM-YYYY'), null, null, null,
                                              null, null);
          exception
            when others then
              begin
                lvnsalesemployee1id := null;
                errormsg            := 'Warning sales1 employee ' || vcursor.salesemployeenumber1 ||
                                       ' is not linked to customer ' || vcursor.customernumber;
                pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 2);
              end;
          end;
        end if;
        --sales employee 2
        if vcursor.salesemployeenumber2 is null then
          lvnsalesemployee2id := null;
        else
          begin
            pack_import.cfbgetcreate_employee(vcursor.plant_id, lvnsalesemployee2id,
                                              vcursor.salesemployeenumber2,
                                              vcursor.salesemployeename2,
                                              nvl(substr(vcursor.salesemployeename2, 1, 10), '-'),
                                              to_date('1-1-2002', 'DD-MM-YYYY'), null, null, null,
                                              null, null);
          exception
            when others then
              begin
                lvnsalesemployee2id := null;
                errormsg            := 'Warning sales2 employee ' || vcursor.salesemployeenumber2 ||
                                       ' is not linked to customer ' || vcursor.customernumber;
                pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 2);
              end;
          end;
        end if;
        --service employee
        if vcursor.serviceemployeenumber is null then
          fpnserviceemployee_id := null;
        else
          begin
            pack_import.cfbgetcreate_employee(vcursor.plant_id, fpnserviceemployee_id,
                                              vcursor.serviceemployeenumber,
                                              vcursor.serviceemployeename,
                                              nvl(substr(vcursor.serviceemployeename, 1, 10), '-'),
                                              to_date('1-1-2002', 'DD-MM-YYYY'), null, null, null,
                                              null, null);
          exception
            when others then
              begin
                fpnserviceemployee_id := null;
                errormsg              := 'Warning service employee ' ||
                                         vcursor.serviceemployeenumber ||
                                         ' is not linked to customer ' || vcursor.customernumber;
                pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 2);
              end;
          end;
        end if;
        --customer ranking
        if vcursor.ranking is null then
          begin
            fpncustomerranking_id := null;
          end;
        else
          begin
            select r.customerranking_id
            into   fpncustomerranking_id
            from   customerranking r
            where  r.ranking = vcursor.ranking;
          exception
            when others then
              begin
                fpncustomerranking_id := null;
                errormsg              := 'Warning no customerranking ' || vcursor.ranking ||
                                         ' linked to customer ' || vcursor.customernumber;
                pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 2);
              end;
          end;
        end if;
        --cleanroom customertype ID
        if vcursor.cleanroomcustomertype is null then
          begin
            lvncleanroomcusttype_id := null;
          end;
        else
          begin
            errormsg := 'Cleanroomcustomertype ' || vcursor.cleanroomcustomertype ||
                        ' linked to customer ' || vcursor.customernumber;
            select ct.cleanroomcustomertype_id
            into   lvncleanroomcusttype_id
            from   cleanroomcustomertype ct
            where  ct.code = vcursor.cleanroomcustomertype;
          end;
        end if;
        --paybycustomer processing
        begin
          select i.bonusagreement,
                 (select a.acquisitioncode_id from acquisitioncode a where a.code = i.acquistioncode),
                 i.tdccode
          into   fpbbonusagreement, fpnacquisioncode_id, fpntdccode
          from   i_paybycustomer i
          where  i.customernumber = vcursor.customernumber;
        exception
          when no_data_found then
            begin
              fpbbonusagreement   := null;
              fpnacquisioncode_id := null;
              fpntdccode          := null;
            end;
        end;
        select formlayout_id
        into   formlayoutdn
        from   formlayout
        where  code = vcursor.deliverynotelayout
        and    formtype = 'DN';
        begin
          pack_import.cfbcreate_customer(customerid, vcursor.customernumber, vcursor.name,
                                         nvl(vcursor.phoneno, '-'),
                                         nvl(vcursor.legalname, vcursor.name), vcursor.faxno,
                                         vcursor.email, vcursor.dateactive, vcursor.dateinactive,
                                         vcursor.active, vcursor.remark, vcursor.siccode,
                                         vcursor.searchname, vcursor.legacycustomernumber, 'Y',
                                         customerid, vcursor.businessunit_id, customerid,
                                         vcursor.masteraccount, vcursor.marketsegment_id,
                                         vcursor.salesarea_id, vcursor.currency_id,
                                         vcursor.country_id, deliveryaddressid,
                                         getaddressid(vcursor.mailaddress, vcursor.mailzipcode,
                                                       vcursor.mailcity, vcursor.mailstate,
                                                       vcursor.mailcounty, vcursor.mailaddress2,
                                                       vcursor.mailtaxareaid,
                                                       vcursor.mailconfidenceindicator, vcursor.mailaddress3),
                                         vcursor.communicationmethod_id, vcursor.soilcount,
                                         formlayoutdn, formlayoutcn, vcursor.internetordering, 'N',
                                         --IMPORTOCCUPANCYHHT
                                         vcursor.returnlinen, vcursor.returngarments,
                                         vcursor.codegarmentsuniquely, vcursor.daysnoprepcharge,
                                         vcursor.chargerepairs, vcursor.garmentrentspecification,
                                         vcursor.swingsuitdelivery, vcursor.usegarmentdispenser,
                                         vcursor.lockermanagement,
                                         nvl(vcursor.firstdaysgradeid,
                                              pack_import.lvndefaultqualitygradeid),
                                         vcursor.daysspecialgrade,
                                         nvl(vcursor.firstissuegradeid,
                                              pack_import.lvndefaultqualitygradeid),
                                         nvl(vcursor.qualitygrade_id,
                                              pack_import.lvndefaultqualitygradeid), null,
                                         --serviceteam_id
                                         vcursor.standardqtydefinition, vcursor.correctshortages,
                                         vcursor.correctoverdeliveries, vcursor.formlayout_id,
                                         vcursor.invoicecopies, vcursor.minimuminvoiceamount,
                                         vcursor.taxable, vcursor.paymentmethod, vcursor.paymenttype,
                                         vcursor.states_id, vcursor.county_id, vcursor.city_id, 'Y',
                                         --is own master account
                                         'Y',
                                         --is own debtor
                                         vcursor.customermakinggarment,
                                         nvl(vcursor.invoicefrequency, lvninvoicefrequency),
                                         --invoicefrequency
                                         vcursor.codelabellayout_id, vcursor.namelabellayout_id,
                                         --namelabellayoutID
                                         'N',
                                         --allowprepchargepertemplate,
                                         3,
                                         --emblemspecification,
                                         'N',
                                         --allownegativestockcount,
                                         0,
                                         --outscansort,
                                         nvl(vcursor.chargewashfirstissue, 'N'),
                                         --chargewashfirstissue,
                                         vcursor.allowautomaticsales,
                                         --allowautomaticsales,
                                         vcursor.customerrelated, vcursor.chargeresidualvalue,
                                         vcursor.rentperiod, vcursor.splitinvoices,
                                         vcursor.vatnumber, vcursor.chain_id,
                                         vcursor.garmentinsurance,
                                         --, vCursor.garmentinsuranceprice
                                         invoiceaddressid,
                                         --fpninvoiceaddress_id
                                         vcursor.ilnnumber, nvl(vcursor.usesbundles, 'N'),
                                         vcursor.extraname1, vcursor.extraname2,
                                         vcursor.scansondeliverynote, vcursor.associationtype,
                                         vcursor.directinvdeliveries, vcursor.directinvcleanweights,
                                         vcursor.directinvsoilweights,
                                         vcursor.directinvminimumamount, 'N',
                                         --usecoverpage
                                         vcursor.signaturerequired,
                                         --fpnsignaturerequired
                                         nationalaccountid, vcursor.cocnumber, vcursor.pnumber,
                                         fpnserviceemployee_id, null, fpbbonusagreement,
                                         fpnacquisioncode_id, fpncustomerranking_id, fpntdccode,
                                         vcursor.chargelosscharge, vcursor.edimethod,
                                         vcursor.taxexemptcode, vcursor.inheritmapricelist,
                                         vcursor.restrictonmaproducts, lvnsalesemployee1id,
                                         lvnsalesemployee2id, vcursor.splitinvoicesperactivity,
                                         vcursor.chargerepaircog, lvninternalbu, lvndefaultinvbu,
                                         vcursor.informpriceupdate, vcursor.directinvallservices,
                                         vcursor.directinvsalesnotes, vcursor.depositstockallowed,
                                         vcursor.alternatesorting, vcursor.internalcalcpercentagelog,
                                         vcursor.internalcalcpercentagecog, vcursor.maincustomertype,
                                         vcursor.language_id, vcursor.linenreducefactor,
                                         vcursor.usecontractcoefficient, vcursor.contractcoefficient,
                                         vcursor.returnsamecontainer, vcursor.ownbatch,
                                         vcursor.invoicecurrencyid, vcursor.customgarmentcharge,
                                         vcursor.useprodsizesurchargepricing,
                                         nvl(vcursor.autosoilpercentage, 0),
                                         vcursor.taxexemptcertificatedocument,
                                         vcursor.chargerestockingfee, vcursor.masteraccountrelation,
                                         vcursor.seasonautoflagallowed, vcursor.passerbycustomer,
                                         vcursor.firstservicedate);
        end;
        begin
          --insert into customerextrainfo
          insert into customerextrainfo
            (customer_id, storenumber, systemuser_id, timestamp, myuniformassistallow,
             specialsizecharge, merchandisebuyoutcharge, raatemplateheader_id,
             cleanroomcustomertype_id, sterilizationexpirationperiod)
          values
            (customerid, null, pack_import.lvnsystemuserid, sysdate, 'N',
             nvl(vcursor.specialsizecharge, 'N'), nvl(vcursor.merchandisebuyoutcharge, 'N'),
             vcursor.maatemplateheader_id, lvncleanroomcusttype_id,
             nvl(vcursor.sterilizationexpirationperiod, 0));
        exception
          when others then
            begin
              pack_import.write_log('Error insert customerextrainfo customernumber ' ||
                                    vcursor.customernumber || ' ' || substr(sqlerrm, 1, 512), 3);
            end;
        end;
        --insert customerrouteinfo
        if vcursor.routedescription is not null then
          begin
            insert into customerrouteinfo
              (customer_id, routedescription, systemuser_id, timestamp)
            values
              (customerid, vcursor.routedescription, pack_import.lvnsystemuserid, sysdate);
          exception
            when others then
              errormsg := 'CFbImportCustomer: Fail to insert customerrouteinfo for customernumber ' ||
                          vcursor.customernumber;
              pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
          end;
        end if;
        begin
          --added garmentinsuranceprice
          insert into customerinsuranceprice
            (customerinsuranceprice_id, startdate, price, systemuser_id, timestamp, customer_id)
          values
            (seq_customerinsuranceprice.nextval, vcursor.dateactive, vcursor.garmentinsuranceprice,
             pack_import.lvnsystemuserid, sysdate, customerid);
        exception
          when dup_val_on_index then
            null;
          when others then
            errormsg := 'CFbImportCustomer: Fail to insert garment insurance price for customernumber ' ||
                        vcursor.customernumber;
            pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
        end;
        begin
          --insert costcenter if needed
          select count(1)
          into   countrowsd
          from   i_costcenter i
          where  i.customernumber = vcursor.customernumber;
          if countrowsd = 0 then
            begin
              pack_import.cfbcreate_costcenter(countrowsd, '-', '-', customerid, null, null);
            end;
          end if;
          countrowsd := 0;
        exception
          when dup_val_on_index then
            null;
          when others then
            errormsg := 'CFbImportCustomer: Fail to insert costcenter for customernumber ' ||
                        vcursor.customernumber;
            pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
        end;
        --add_customerrestockingfeeprice
        add_customerrestockingfeeprice(vcursor.restockingprice,
                                       nvl(vcursor.restockingstartdate, vcursor.dateactive),
                                       vcursor.customernumber);
        --create contact persons for the customer
        cfbimportcontactpersons(customerid);
        --insert deliverypoint
        ndeliverypointcounter := cfbimport_deliverypoint(customerid) + ndeliverypointcounter;
        --insert department
        ndepartmentcounter := ndepartmentcounter +
                              pack_import_department.cfbimport_departments(vcursor.customernumber);
        --insert customeractivities
        pack_import_customer.import_customeractivities(customerid, vcursor.customernumber,
                                                       vcursor.businessunit_id, vcursor.cutoffdate,
                                                       vcursor.invoicefrequency);
        --insert customeredi
        if vcursor.edicontactpersonnumber is not null and vcursor.requisitionnumber is not null and
           vcursor.accountingstring is not null then
          begin
            importcontactperson(customerid, ledicontactperson, vcursor.edicontactpersonnumber, null,
                                null, null, null, null, null, 'N', null, null);
            insert into customerediinfo
              (customer_id, edicontactperson_id, requisitionnumber, accountingstring, systemuser_id,
               timestamp)
            values
              (customerid, ledicontactperson, vcursor.requisitionnumber, vcursor.accountingstring,
               pack_import.lvnsystemuserid, sysdate);
          exception
            when others then
              errormsg := 'Error inserting customerediinfo for customernumber/customername ' ||
                          vcursor.customernumber || '/' || vcursor.name;
              pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
          end;
        end if;
        begin
          if vcursor.prepcharge is not null then
            --insert customerprepcharge
            insert into customerprepcharge
              (customerprepcharge_id, customer_id, price, startdate, systemuser_id, timestamp)
            values
              (seq_customerprepcharge.nextval, customerid, vcursor.prepcharge, vcursor.dateactive,
               pack_import.lvnsystemuserid, sysdate);
            update customer c set c.chargeprecharges = 'Y' where c.customer_id = customerid;
          end if;
        exception
          when dup_val_on_index then
            null;
          when others then
            errormsg := 'CFbImportCustomer: Fail to import customerprepcharge for customernumber/customername ' ||
                        vcursor.customernumber || '/' || vcursor.name;
            pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
        end;
        begin
          --customer nonbusinessdays
          lvncountdays := vcursor.enddateholiday - vcursor.startdateholiday;
          case
            when lvncountdays > 365 then
              begin
                errormsg := 'Warning too many non businessdays for customernumber/customername ' ||
                            vcursor.customernumber || '/' || vcursor.name;
                pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 2);
              end;
            when lvncountdays <= 365 then
              begin
                while lvncountdays >= 0 loop
                  begin
                    insert into nonbusinessday
                      (nonbusinessday_id, nonbusinessday, department_id, customer_id, systemuser_id,
                       timestamp, plant_id, closestatus, movedays)
                    values
                      (seq_nonbusinessday.nextval, vcursor.enddateholiday - lvncountdays, null,
                       customerid, pack_import.lvnsystemuserid, sysdate, null, 2, 0);
                    lvncountdays := lvncountdays - 1;
                  end;
                end loop;
              end;
            else
              null;
          end case;
        exception
          when dup_val_on_index then
            null;
          when others then
            errormsg := 'CFbImportCustomer: Fail to import nombusinessdays for customernumber/customername ' ||
                        vcursor.customernumber || '/' || vcursor.name;
            pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
        end;
        --ABS-93615 Exchange fee conversion
        if vcursor.exchangecharge is not null then
          begin
            insert into customerexchangecharge
              (customerexchangecharge_id, customer_id, startdate, price, systemuser_id, timestamp)
            values
              (seq_customerexchangecharge.nextval, customerid,
               coalesce(vcursor.exchangecharge_startdate, vcursor.dateactive),
               vcursor.exchangecharge, pack_import.lvnsystemuserid, sysdate);
          exception
            when others then
              begin
                pack_import.write_log('CFbImportCustomer: Fail to import exchangecharge for customernumber/customername ' ||
                                      vcursor.customernumber || '/' || vcursor.name || ' ' ||
                                      substr(sqlerrm, 1, 512), 3);
              end;
          end;
        end if;
        begin
          --customerinternetoptions
          errormsg := 'check if we need to add customerinternetoptions';
          if vcursor.autoapprovewebworkorder in (0, 1) then
            begin
              insert into customerinternetoptions
                (customer_id, ordersalesitems, ordergarments, orderlinen, maintainstocklevels,
                 maintainstddel, systemuser_id, timestamp, garmentsusefunctions, garmentswebportal,
                 residentialwebportal, stockcountwebportal, orderbydatewebportal,
                 autoapprovewebworkorder)
              values
                (customerid, 'N', 'N', 'N', 'N', 'N', pack_import.lvnsystemuserid, sysdate, 'N',
                 vcursor.garmentswebportal, 'N', 'N', 'N', vcursor.autoapprovewebworkorder);
            end;
          end if;
        exception
          when others then
            errormsg := 'CFbImportCustomer: Fail to import customerinternetoptions for customernumber/customername ' ||
                        vcursor.customernumber || '/' || vcursor.name;
            pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
        end;
        --insert into customergeneral
        begin
          insert into customergeneral
            (customer_id, nongarmentchargeresidualvalue, nongarmentchargelosscharge, systemuser_id,
             timestamp)
          values
            (customerid, nvl(vcursor.nongarmentchargeresidualvalue, 'N'),
             nvl(vcursor.nongarmentchargelosscharge, 'N'), pack_import.lvnsystemuserid, sysdate);
        exception
          when others then
            begin
              errormsg := 'CFbImportCustomer: Fail to import customergeneral for customernumber/customername ' ||
                          vcursor.customernumber || '/' || vcursor.name;
              pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
            end;
        end;
        commit;
        lvncountrows := lvncountrows + 1; --count inserted rows in customer table
      exception
        when dup_val_on_index then
          null;
        when no_data_found then
          pack_import.write_log('No data found ' || errormsg, 3);
        when others then
          rollback;
          errormsg := 'CFbImportCustomer: Fail to import customernumber/customername ' ||
                      vcursor.customernumber || '/' || vcursor.name;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop; --end insert customer
    --fill customer billing info records
    cfbimportcustomerbillinginfo;
    pack_import.write_log('Imported Billing info.');
    --debtor
    countrowsd := 0;
    for vcursor in (select c.customer_id, d.customer_id debtorid
                    from   i_customer i, customer c, customer d
                    where  i.customernumber = c.customernumber
                    and    i.customernumber <> i.accountnumber
                    and    d.customernumber = i.accountnumber
                    and    c.debtor_id <> d.debtor_id
                    and    c.timestamp > (sysdate - 2 / 24)) loop
      begin
        delete from customerbillinginfo cbi where cbi.customer_id = vcursor.customer_id;
        update customer set debtor_id = vcursor.debtorid where customer_id = vcursor.customer_id;
        countrowsd := countrowsd + 1;
      end;
    end loop;
    --check billto rule
    errormsg := 'check billto rule';
    delete from customerbillinginfo cbi
    where  exists (select 1
            from   customer c
            where  c.customer_id <> c.debtor_id
            and    c.customer_id = cbi.customer_id);
    --masteraccount
    errormsg   := 'masteraccount';
    countrowsm := 0;
    for vcursor in (select c.customer_id, m.customer_id masteraccountid
                    from   i_customer i, customer c, customer m
                    where  i.customernumber = c.customernumber
                    and    i.masteraccount = 3
                    and    i.masteraccountnumber = m.customernumber
                    and    c.masteraccount_id <> m.masteraccount_id
                    and    c.timestamp > (sysdate - 2 / 24)) loop
      begin
        update customer
        set    masteraccount_id = vcursor.masteraccountid
        where  customer_id = vcursor.customer_id;
        countrowsm := countrowsm + 1;
      end;
    end loop;
    --customerbillingcomment
    begin
      insert into customerbillingcomment
        (customer_id, timestamp, systemuser_id, enddate, startdate, description, type)
        select c.customer_id, sysdate, c.systemuser_id, to_date('31/12/2099', 'DD/MM/YYYY'),
               to_date('01/01/2002', 'DD/MM/YYYY'), i.remarkoninvoice, 1
        from   i_customer i, customer c
        where  i.customernumber = c.customernumber
        and    c.timestamp > (sysdate - 2 / 24)
        and    i.remarkoninvoice is not null
        and    not exists (select z.customer_id
                from   customerbillingcomment z
                where  z.customer_id = c.customer_id);
    exception
      when dup_val_on_index then
        null;
      when others then
        errormsg := 'CFbImportCustomer: Fail to insert customerbillingcomment ';
        pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
    end;
    commit;
    begin
      update customer c
      set    c.insurancepricetype = 0
      where  exists (select i.garmentinsuranceprice, i.garmentinsurance, c.insurancepricetype
              from   customerinsuranceprice t, i_customer i
              where  t.price <> 0
              and    t.customer_id = c.customer_id
              and    c.customernumber = i.customernumber
              and    c.timestamp > (sysdate - 2 / 24)
              and    i.garmentinsuranceprice <> 0);
      commit;
    exception
      when others then
        begin
          rollback;
          errormsg := 'CFbImportCustomer: fail to update customer.insurancepricetype ';
          pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
        end;
    end;
    begin
      insert into customerspercluster
        (customerspercluster_id, cluster_id, customer_id, systemuser_id, timestamp)
        select seq_customerspercluster.nextval, cc.cluster_id, c.customer_id, c.systemuser_id,
               sysdate
        from   customer c, customercluster cc, i_customer i
        where  c.customernumber = i.customernumber
        and    i.invoiceclusteringcode = cc.code
        and    c.invoicefrequency_id = cc.invoicefrequency_id
        and    c.timestamp > (sysdate - 2 / 24)
        and    not exists (select x.customerspercluster_id
                from   customerspercluster x
                where  x.cluster_id = cc.cluster_id
                and    x.customer_id = c.customer_id);
      commit;
    exception
      when others then
        begin
          rollback;
          errormsg := 'CFbImportCustomer: fail to import customerspercluster ';
          pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
        end;
    end;
    --customer activities
    for x in (select c.customer_id, c.customernumber
              from   i_customeractivities ca, customer c
              where  ca.customernumber = c.customernumber) loop
      begin
        pack_import_customer.import_customeractivities(x.customer_id, x.customernumber);
      end;
    end loop; --x
    begin
      for cc in (select i.customernumber, i.invoiceclusteringcode
                 from   customer c, customercluster cc, i_customer i
                 where  c.customernumber = i.customernumber
                 and    i.invoiceclusteringcode = cc.code
                 and    c.invoicefrequency_id <> cc.invoicefrequency_id) loop
        begin
          pack_import.write_log('For customer ' || cc.customernumber ||
                                ' the invoice cluster code ' || cc.invoiceclusteringcode ||
                                ' invoicefrequency does not match that of the customer!', 2);
        end;
      end loop;
    exception
      when others then
        begin
          errormsg := 'CFbImportCustomer: fail to check customerspercluster ';
          pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
        end;
    end;
    if countrowsd > 0 then
      pack_import.write_log(countrowsd || ' debtor(s) updated.');
    end if;
    if countrowsm > 0 then
      pack_import.write_log(countrowsm || ' masteraccount(s) updated.');
    end if;
    pack_import.write_log(countexisting || ' customer were already in the database.');
    select count(i.customernumber) into countexisting from i_customer i;
    pack_import.write_log(countexisting || ' customer in the i-table.');
    pack_import.write_log(lvncountrows || ' customer rows imported.');
    select count(c.customer_id) into countexisting from customer c;
    pack_import.write_log(countexisting || ' customer now in the database.');
    select count(i.departmentnumber) into countexisting from i_department i;
    pack_import.write_log(countexisting || ' department in the i-table.');
    pack_import.write_log(ndepartmentcounter || ' department imported.');
    if ndeliverypointcounter > 0 then
      pack_import.write_log(ndeliverypointcounter || ' deliverypoint(s) imported.');
    end if;
    begin
      execute immediate 'alter table CUSTOMER enable constraint CHECK_MASTERACCOUNT3';
    exception
      when others then
        null;
    end;
    commit;
    --process sortcustomer
    cfbprocess_sortcustomer;
    --convert_i_deliverypoint
    convert_i_deliverypoint;
    --process maindeliverypoint
    cfbprocess_maindeliverypoint;
    --cfbimport_customerbudget
    cfbimport_customerbudget;
    --imp_customer_budgetprotection
    imp_customer_budgetprotection;
    --cfbimport_customerprepcharge
    cfbimport_customerprepcharge;
    --link_common_customer
    link_common_customer;
    --link_other_customer
    link_other_customer;
    --add_customerlockermanagement
    add_customerlockermanagement;
    --import_customercreditcard
    import_customercreditcard;
    --import customerach
    import_customerach;
    -- import_customergarmentcharges
    import_customergarmentcharges;
  exception
    when missing_bussinessunits then
      pack_import.write_log('THERE are missing BUSINESSUNITES no customer imported!');
  end cfbimportcustomer;
  --customerdeliveryday
  procedure cfbimportcustomerdeliverydays is
    v_typeofmerchandise  customerdeliveryday.typeofmerchadise%type;
    fpndeliveryscheme_id deliveryscheme.deliveryscheme_id%type;
    countrowss           integer;
    countrowsd           integer;
    lvnemployeeid        employee.employee_id%type;
    lvndriverid          route.driver_id%type;
    lvnroutemanagerid    route.routemanager_id%type;
    lvndistrict          route.district_id%type;
    lvndepotid           depot.depot_id%type;
    lvndepotaddressid    address.address_id%type;
    lvnreturnrouteid     route.route_id%type;
    countrows            integer;
    lvsortbatchdefid     sortbatchdefinition.sortbatchdefinition_id%type;
  begin
    -- Replace ~ with carriage return
    update i_deliverydays d
    set    d.routelistinstructions = replace(d.routelistinstructions, '~', chr(10))
    where  d.routelistinstructions <> replace(d.routelistinstructions, '~', chr(10));
    commit;
    --import drivers to employee
    countrows := 0;
    for x in (select nvl(d.drivernumber, 1) drivernumber, max(d.drivername) drivername,
                     max(b.plant_id) plant_id
              from   i_deliverydays d, customer c, businessunit b
              where  d.customernumber = c.customernumber
              and    c.defaultbusinessunit_id = b.businessunit_id
              and    d.plantcode_route is null
              and    not exists (select e.employee_id
                      from   employee e
                      where  e.employeenumber = nvl(d.drivernumber, 1))
              group  by d.drivernumber
              union
              select nvl(d.drivernumber, 1) drivernumber, max(d.drivername) drivername,
                     max(pt.plant_id) plant_id
              from   i_deliverydays d, plant pt
              where  d.plantcode_route = pt.code
              and    not exists (select e.employee_id
                      from   employee e
                      where  e.employeenumber = nvl(d.drivernumber, 1))
              group  by d.drivernumber) loop
      begin
        pack_import.cfbgetcreate_employee(x.plant_id, lvnemployeeid, x.drivernumber, x.drivername,
                                          nvl(substr(x.drivername, 1, 10), '-'), null, null, null,
                                          null, null, null);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'cfbimportcustomerdeliverydays: Fail to import drivers ' || x.drivernumber;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(countrows || ' driver(s) row(s) imported.');
    end if;
    --import managers
    countrows := 0;
    for x in (select d.routemanager, max(d.routemanagername) routemanagername,
                     max(bu.plant_id) plant_id
              from   i_deliverydays d, customer c, businessunit bu
              where  d.customernumber = c.customernumber
              and    c.defaultbusinessunit_id = bu.businessunit_id
              and    d.routemanager is not null
              and    d.plantcode_route is null
              and    not exists
               (select e.employee_id from employee e where e.employeenumber = d.routemanager)
              group  by d.routemanager
              union
              select d.routemanager, max(d.routemanagername) routemanagername,
                     max(pt.plant_id) plant_id
              from   i_deliverydays d, plant pt
              where  d.plantcode_route = pt.code
              and    d.routemanager is not null
              and    not exists
               (select e.employee_id from employee e where e.employeenumber = d.routemanager)
              group  by d.routemanager) loop
      begin
        pack_import.cfbgetcreate_employee(x.plant_id, lvnemployeeid, x.routemanager,
                                          x.routemanagername,
                                          nvl(substr(x.routemanagername, 1, 10), '-'), null, null,
                                          null, null, null, null);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'cfbimportcustomerdeliverydays: Fail to import route managers ' ||
                      x.routemanager;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(countrows || ' routemanager row(s) imported.');
    end if;
    --import contact persons
    countrows := 0;
    for x in (select d.contactpersonnumber,
                     nvl(max(d.contactpersonname), to_char(d.contactpersonnumber)) contactpersonname,
                     c.customer_id
              from   i_deliverydays d, customer c
              where  d.contactpersonnumber is not null
              and    d.customernumber = c.customernumber
              and    not exists (select 1
                      from   contactperson cp
                      where  cp.contactpersonnumber = d.contactpersonnumber
                      and    cp.customer_id = c.customer_id)
              group  by d.contactpersonnumber, c.customer_id) loop
      begin
        insert into contactperson
          (customer_id, contactperson_id, contactpersonnumber, contactpersonfunction_id, name,
           invoicecontactperson, systemuser_id, timestamp)
        values
          (x.customer_id, seq_contactperson.nextval, x.contactpersonnumber,
           contactpersonfunctionminusid, x.contactpersonname, 'N', pack_import.lvnsystemuserid,
           sysdate);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'cfbimportcustomerdeliverydays: Fail to import contact persons ' ||
                      x.contactpersonname;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(countrows || ' contact person row(s) imported.');
    end if;
    --import districts
    countrows := 0;
    for x in (select nvl(d.district, '-') district, max(d.districtdescription) description
              from   i_deliverydays d
              where  d.district is not null
              and    not exists
               (select 1 from district dt where dt.code = nvl(d.district, '-'))
              group  by nvl(d.district, '-')) loop
      begin
        insert into district
          (district_id, code, description, systemuser_id, timestamp)
        values
          (seq_district.nextval, x.district, nvl(x.description, x.district),
           pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'cfbimportcustomerdeliverydays: Fail to import district(s) ' || x.district;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(countrows || ' district row(s) imported.');
    end if;
    --import plant districts if possible
    countrows := 0;
    for x in (select dt.district_id, bu.plant_id, max(e.employee_id) employee_id
              from   i_deliverydays d, district dt, i_customer i, businessunit bu, employee e
              where  d.district = dt.code
              and    d.customernumber = i.customernumber
              and    d.routemanager = e.employeenumber
              and    bu.plant_id = e.plant_id
              and    i.businessunit = bu.code
              and    d.plantcode_route is null
              and    not exists (select 0
                      from   districtplant dp
                      where  dp.district_id = dt.district_id
                      and    dp.plant_id = bu.plant_id)
              group  by dt.district_id, bu.plant_id
              union
              select dt.district_id, pt.plant_id, max(e.employee_id) employee_id
              from   i_deliverydays d, district dt, plant pt, employee e
              where  d.district = dt.code
              and    d.routemanager = e.employeenumber
              and    d.plantcode_route = pt.code
              and    pt.plant_id = e.plant_id
              and    not exists (select 0
                      from   districtplant dp
                      where  dp.district_id = dt.district_id
                      and    dp.plant_id = pt.plant_id)
              group  by dt.district_id, pt.plant_id) loop
      begin
        insert into districtplant
          (district_id, plant_id, employee_id, systemuser_id, timestamp)
        values
          (x.district_id, x.plant_id, x.employee_id, pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'cfbimportcustomerdeliverydays: Fail to import  district-plant(s)';
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(countrows || ' district-plant row(s) imported.');
    end if;
    --deliveryscheme
    countrows := 0;
    for vcursor in (select a.deliveryschemecode
                    from   i_deliverydays a
                    where  a.deliveryschemecode is not null
                    and    not exists
                     (select code from deliveryscheme b where b.code = a.deliveryschemecode)
                    group  by a.deliveryschemecode) loop
      begin
        pack_import.cfbcreate_deliveryscheme(fpndeliveryscheme_id, vcursor.deliveryschemecode, 'N',
                                             null, null);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomerDeliveryDays: Fail to insert deliveryschemecode' ||
                      vcursor.deliveryschemecode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(countrows || ' deliveryscheme rows imported.');
    end if;
    --import route
    countrows := 0;
    for vcursor in (select routenumber, d.day_id, u.plant_id,
                           nvl(max(a.drivernumber), 1) drivernumber,
                           nvl(min((select ds.deliveryscheme_id
                                    from   deliveryscheme ds
                                    where  ds.code = a.deliveryschemecode)),
                                (select min(ds.deliveryscheme_id)
                                  from   deliveryscheme ds
                                  where  ds.offsetweek = 0
                                  and    ds.frequency = 1)) defaultdeliveryschemeid,
                           max(a.routemanager) routemanager, nvl(max(a.district), '-') district,
                           max(a.depotcode) depotcode, max(a.depotdescription) depotdescription,
                           max(a.drivername) drivername, max(a.routemanagername) routemanagername,
                           max(a.route_description) route_description, max(a.routecode) routecode,
                           max(a.sortbatchroute) sortbatchroute
                    from   i_deliverydays a, customer c, businessunit u, day d
                    where  a.customernumber = c.customernumber
                    and    a.routenumber is not null
                    and    a.daynumber = d.daynumber
                    and    u.businessunit_id = c.defaultbusinessunit_id
                    and    a.plantcode_route is null
                    and    not exists (select routenumber
                            from   route b
                            where  b.routenumber = a.routenumber
                            and    b.plant_id = u.plant_id
                            and    b.drivingday_id = d.day_id)
                    group  by routenumber, d.day_id, u.plant_id
                    union
                    select routenumber, d.day_id, pt.plant_id,
                           nvl(max(a.drivernumber), 1) drivernumber,
                           nvl(min((select ds.deliveryscheme_id
                                    from   deliveryscheme ds
                                    where  ds.code = a.deliveryschemecode)),
                                (select min(ds.deliveryscheme_id)
                                  from   deliveryscheme ds
                                  where  ds.offsetweek = 0
                                  and    ds.frequency = 1)) defaultdeliveryschemeid,
                           max(a.routemanager) routemanager, nvl(max(a.district), '-') district,
                           max(a.depotcode) depotcode, max(a.depotdescription) depotdescription,
                           max(a.drivername) drivername, max(a.routemanagername) routemanagername,
                           max(a.route_description) route_description, max(a.routecode) routecode,
                           max(a.sortbatchroute) sortbatchroute
                    from   i_deliverydays a, plant pt, day d
                    where  a.routenumber is not null
                    and    a.daynumber = d.daynumber
                    and    a.plantcode_route = pt.code
                    and    not exists (select routenumber
                            from   route b
                            where  b.routenumber = a.routenumber
                            and    b.plant_id = pt.plant_id
                            and    b.drivingday_id = d.day_id)
                    group  by routenumber, d.day_id, pt.plant_id) loop
      begin
        --get driver
        pack_import.cfbgetcreate_employee(vcursor.plant_id, lvndriverid, vcursor.drivernumber,
                                          vcursor.drivername,
                                          nvl(substr(vcursor.drivername, 1, 10), '-'), null, null,
                                          null, null, null, null);
        --get routemanager
        pack_import.cfbgetcreate_employee(vcursor.plant_id, lvnroutemanagerid, vcursor.routemanager,
                                          vcursor.routemanagername,
                                          nvl(substr(vcursor.routemanagername, 1, 10), '-'), null,
                                          null, null, null, null, null);
        begin
          --get district
          select ds.district_id
          into   lvndistrict
          from   districtplant ds
          where  ds.district_id =
                 (select dt.district_id from district dt where dt.code = vcursor.district)
          and    ds.plant_id = vcursor.plant_id;
        exception
          when no_data_found then
            begin
              --insert into districtplant
              insert into districtplant
                (district_id, plant_id, employee_id, systemuser_id, timestamp)
                select t.district_id, vcursor.plant_id, nvl(lvnroutemanagerid, lvndriverid),
                       pack_import.lvnsystemuserid, sysdate
                from   district t
                where  t.code = vcursor.district;
              --select district
              select ds.district_id
              into   lvndistrict
              from   districtplant ds
              where  ds.district_id =
                     (select dt.district_id from district dt where dt.code = vcursor.district)
              and    ds.plant_id = vcursor.plant_id;
            end;
        end;
        begin
          --get depot
          if vcursor.depotcode is null then
            lvndepotid := null;
          else
            begin
              select dp.depot_id
              into   lvndepotid
              from   depot dp
              where  dp.code = vcursor.depotcode
              and    dp.plant_id = vcursor.plant_id;
            exception
              when no_data_found then
                begin
                  --create depot
                  lvndepotaddressid := getaddressid('-', '-', '-', '-', '-', '-',null,null,'-');
                  insert into depot
                    (depot_id, plant_id, code, description, systemuser_id, address_id, timestamp)
                  values
                    (seq_depot.nextval, vcursor.plant_id, vcursor.depotcode,
                     nvl(vcursor.depotdescription, vcursor.depotcode), pack_import.lvnsystemuserid,
                     lvndepotaddressid, sysdate)
                  returning depot_id into lvndepotid;
                end;
            end;
          end if;
        end;
        begin
          select max(sb.sortbatchdefinition_id)
          into   lvsortbatchdefid
          from   sortbatchdefinition sb
          where  sb.plant_id = vcursor.plant_id
          and    sb.day_id = vcursor.day_id
          and    sb.batchnumber = vcursor.sortbatchroute;
        end;
        --insert route
        insert into route
          (route_id, plant_id, drivingday_id, routenumber, description, depot_id, systemuser_id,
           codeonlabel, timestamp, driver_id, truck_id, starttime, endtime, packingday_id,
           packingdeadline, loadingdock, putupreportpercustomer, putupreportperroute,
           putupreportperdepot, putupreportroutestop, printsoilticket, printorderform,
           bundletagsflatw, bundletagsgarm, deliveryscheme_id, district_id, routemanager_id,
           routecode, sortbatchdefinition_id)
        values
          (seq_route.nextval, vcursor.plant_id, vcursor.day_id, vcursor.routenumber,
           coalesce(vcursor.route_description, to_char(vcursor.routenumber)), lvndepotid,
           pack_import.lvnsystemuserid, null, sysdate, lvndriverid, null, null, null, null, null,
           null, 0, 'N', 'N', 0, 'N', 1, 0, 0, vcursor.defaultdeliveryschemeid, lvndistrict,
           lvnroutemanagerid, vcursor.routecode, lvsortbatchdefid);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomerDeliveryDays: Fail to insert routenumber/daynumber' ||
                      vcursor.routenumber || '/' || vcursor.day_id;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(countrows || ' route rows inserted.');
    end if;
    --update routestop
    countrows := 0;
    for vcursor in (select a.stopnumber, a.soiltickets, a.stoptype, a.routenumber, c.route_id,
                           b.customer_id, b.customernumber, a.daynumber, a.routelistinstructions,
                           a.chargedeliveryfee, a.contactpersonnumber, u.plant_id,
                           (select dp.deliverypoint_id
                             from   deliverypoint dp
                             where  dp.code = a.deliverypointcode
                             and    dp.customer_id = b.customer_id) deliverypoint_id, a.sortsequence
                    from   i_deliverydays a, customer b, businessunit u, route c
                    where  a.customernumber = b.customernumber
                    and    b.defaultbusinessunit_id = u.businessunit_id
                    and    u.plant_id = c.plant_id
                    and    a.plantcode_route is null
                    and    a.routenumber = c.routenumber
                    and    a.daynumber = c.drivingday_id
                    and    exists (select routestop_id
                            from   routestop x
                            where  x.stopnumber = a.stopnumber
                            and    x.route_id = c.route_id
                            and    x.customer_id = b.customer_id
                            and    sysdate between x.dateactive and x.dateinactive
                            and    x.deliverypoint_id =
                                   (select dp.deliverypoint_id
                                     from   deliverypoint dp
                                     where  dp.code = a.deliverypointcode
                                     and    dp.customer_id = b.customer_id))
                    union all
                    select a.stopnumber, a.soiltickets, a.stoptype, a.routenumber, c.route_id,
                           b.customer_id, b.customernumber, a.daynumber, a.routelistinstructions,
                           a.chargedeliveryfee, a.contactpersonnumber, pt.plant_id,
                           (select dp.deliverypoint_id
                             from   deliverypoint dp
                             where  dp.code = a.deliverypointcode
                             and    dp.customer_id = b.customer_id) deliverypoint_id, a.sortsequence
                    from   i_deliverydays a, customer b, plant pt, route c
                    where  a.customernumber = b.customernumber
                    and    a.plantcode_route = pt.code
                    and    pt.plant_id = c.plant_id
                    and    a.routenumber = c.routenumber
                    and    a.daynumber = c.drivingday_id
                    and    exists
                     (select routestop_id
                            from   routestop x
                            where  x.stopnumber = a.stopnumber
                            and    x.route_id = c.route_id
                            and    x.customer_id = b.customer_id
                            and    x.deliverypoint_id =
                                   (select dp.deliverypoint_id
                                     from   deliverypoint dp
                                     where  dp.code = a.deliverypointcode
                                     and    dp.customer_id = b.customer_id)
                            and    sysdate between x.dateactive and x.dateinactive)) loop
      begin
        begin
          --get contact person
          if vcursor.contactpersonnumber is null then
            lvnemployeeid := null;
          else
            select e.contactperson_id
            into   lvnemployeeid
            from   contactperson e
            where  e.contactpersonnumber = vcursor.contactpersonnumber
            and    e.customer_id = vcursor.customer_id;
          end if;
        end;
        update routestop
        set    soiltickets = vcursor.soiltickets, systemuser_id = pack_import.lvnsystemuserid,
               timestamp = sysdate, stoptype = vcursor.stoptype,
               routelistinstructions = vcursor.routelistinstructions,
               chargedeliveryfee = vcursor.chargedeliveryfee, contactperson_id = lvnemployeeid,
               sortsequence = vcursor.sortsequence
        where  stopnumber = vcursor.stopnumber
        and    deliverypoint_id = vcursor.deliverypoint_id
        and    route_id = vcursor.route_id
        and    customer_id = vcursor.customer_id
        and    sysdate between dateactive and dateinactive;
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomerDeliveryDays: Fail to update routestopnumber for customernumber/daynumber/route ' ||
                      vcursor.stopnumber || 'for' || vcursor.customernumber || '/' ||
                      vcursor.daynumber || '/' || vcursor.routenumber;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(countrows || ' routestopnumber rows updated.');
    end if;
    --insert routestop
    countrows := 0;
    for vcursor in (select a.stopnumber, a.soiltickets, a.stoptype, a.routenumber, c.route_id,
                           b.customer_id, b.customernumber, a.daynumber, a.routelistinstructions,
                           a.chargedeliveryfee, a.contactpersonnumber, u.plant_id,
                           (select dp.deliverypoint_id
                             from   deliverypoint dp
                             where  dp.code = a.deliverypointcode
                             and    dp.customer_id = b.customer_id) deliverypoint_id, a.sortsequence,
                           a.sortbatchroute, a.sortbatchroutestop
                    from   i_deliverydays a, customer b, route c, businessunit u
                    where  a.customernumber = b.customernumber
                    and    b.defaultbusinessunit_id = u.businessunit_id
                    and    c.plant_id = u.plant_id
                    and    a.routenumber = c.routenumber
                    and    a.daynumber = c.drivingday_id
                    and    a.plantcode_route is null
                    and    not exists (select routestop_id
                            from   routestop x
                            where  x.stopnumber = a.stopnumber
                            and    x.route_id = c.route_id
                            and    x.customer_id = b.customer_id)
                    union all
                    select a.stopnumber, a.soiltickets, a.stoptype, a.routenumber, c.route_id,
                           b.customer_id, b.customernumber, a.daynumber, a.routelistinstructions,
                           a.chargedeliveryfee, a.contactpersonnumber, pt.plant_id,
                           (select dp.deliverypoint_id
                             from   deliverypoint dp
                             where  dp.code = a.deliverypointcode
                             and    dp.customer_id = b.customer_id) deliverypoint_id, a.sortsequence,
                           a.sortbatchroute, a.sortbatchroutestop
                    from   i_deliverydays a, customer b, route c, plant pt
                    where  a.customernumber = b.customernumber
                    and    pt.code = a.plantcode_route
                    and    c.plant_id = pt.plant_id
                    and    a.routenumber = c.routenumber
                    and    a.daynumber = c.drivingday_id
                    and    not exists (select routestop_id
                            from   routestop x
                            where  x.stopnumber = a.stopnumber
                            and    x.route_id = c.route_id
                            and    x.customer_id = b.customer_id)) loop
      begin
        begin
          --get contact person
          if vcursor.contactpersonnumber is null then
            lvnemployeeid := null;
          else
            select e.contactperson_id
            into   lvnemployeeid
            from   contactperson e
            where  e.contactpersonnumber = vcursor.contactpersonnumber
            and    e.customer_id = vcursor.customer_id;
          end if;
        end;
        begin
          select max(sb.sortbatchdefinition_id)
          into   lvsortbatchdefid
          from   sortbatchdefinition sb
          where  sb.plant_id = vcursor.plant_id
          and    sb.day_id = vcursor.daynumber
          and    sb.batchnumber = vcursor.sortbatchroutestop;
        end;
        insert into routestop
          (routestop_id, route_id, stopnumber, customer_id, contactperson_id, deliverypoint_id,
           systemuser_id, soiltickets, timestamp, routelistinstructions, returnroute_id, stoptype,
           chargedeliveryfee, sortsequence, specificsortbatchdefinition_id)
        values
          (seq_routestop.nextval, vcursor.route_id, nvl(vcursor.stopnumber, 0), vcursor.customer_id,
           lvnemployeeid, vcursor.deliverypoint_id, pack_import.lvnsystemuserid, vcursor.soiltickets,
           sysdate, vcursor.routelistinstructions, vcursor.route_id, vcursor.stoptype,
           vcursor.chargedeliveryfee, vcursor.sortsequence, lvsortbatchdefid);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomerDeliveryDays: Fail to import routestopnumber for customernumber/daynumber/route ' ||
                      vcursor.stopnumber || 'for' || vcursor.customernumber || '/' ||
                      vcursor.daynumber || '/' || vcursor.routenumber;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(countrows || ' routestop rows imported.');
    end if;
    countrows  := 0;
    countrowss := 0;
    --update customer delivery days
    for vcursor in (select a.*, b.customer_id, c.day_id, s.deliveryscheme_id
                    from   i_deliverydays a, customer b, day c, customerdeliveryday f,
                           deliveryscheme s
                    where  a.customernumber = b.customernumber
                    and    a.daynumber = c.daynumber
                    and    f.customer_id = b.customer_id
                    and    f.day_id = c.day_id
                    and    a.deliveryschemecode = s.code) loop
      begin
        if vcursor.delgarments not in ('N', 'C') then
          v_typeofmerchandise := 2;
          update customerdeliveryday --for garments
          set    timestamp = sysdate, systemuser_id = pack_import.lvnsystemuserid,
                 deliverytype = vcursor.delgarments
          where  customer_id = vcursor.customer_id
          and    day_id = vcursor.day_id
          and    typeofmerchadise = v_typeofmerchandise;
          countrows := countrows + sql%rowcount;
        end if;
      exception
        when others then
          errormsg := 'CFbImportCustomerDeliveryDays: Fail to update customer delivery day for customernumber/daynumber/typeofmerchandise ' ||
                      vcursor.customernumber || '/' || vcursor.daynumber || '/' ||
                      v_typeofmerchandise;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
      begin
        if vcursor.delnogarments != 'N' then
          v_typeofmerchandise := 1;
          update customerdeliveryday --for nongarments
          set    timestamp = sysdate, systemuser_id = pack_import.lvnsystemuserid,
                 deliverytype = vcursor.delnogarments
          where  customer_id = vcursor.customer_id
          and    day_id = vcursor.day_id
          and    typeofmerchadise = v_typeofmerchandise;
          countrows := countrows + sql%rowcount;
        end if;
      exception
        when others then
          errormsg := 'CFbImportCustomerDeliveryDays: Fail to update customer delivery day for customernumber/daynumber/typeofmerchandise ' ||
                      vcursor.customernumber || '/' || vcursor.daynumber || '/' ||
                      v_typeofmerchandise;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
      begin
        pack_import.cfbcreate_customerdelscheme(vcursor.customer_id, vcursor.deliveryscheme_id,
                                                vcursor.day_id);
        countrowss := countrowss + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomerDeliveryDays: Fail to import customer delivery scheme for customernumber/deliveryschemecode ' ||
                      vcursor.customernumber || '/' || vcursor.deliveryschemecode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if countrows > 0 then
      pack_import.write_log(countrows || ' customer delivery days rows updated.');
    end if;
    if countrowss > 0 then
      pack_import.write_log(countrowss || ' customer delivery schemes rows inserted on update.');
    end if;
    if countrowsd > 0 then
      pack_import.write_log(countrowsd || ' department delivery days rows inserted on update.');
    end if;
    --insert customer delivery days
    countrows  := 0;
    countrowss := 0;
    for vcursor in (select a.*, b.customer_id, c.day_id, e.description, s.deliveryscheme_id,
                           u.plant_id
                    from   i_deliverydays a, customer b, day c, day_desc e, deliveryscheme s,
                           businessunit u
                    where  a.customernumber = b.customernumber
                    and    a.daynumber = c.daynumber
                    and    c.day_id = e.day_id
                    and    a.deliveryschemecode = s.code
                    and    b.defaultbusinessunit_id = u.businessunit_id
                    and    not exists (select customer_id, day_id, typeofmerchadise
                            from   customerdeliveryday
                            where  customerdeliveryday.customer_id = b.customer_id
                            and    customerdeliveryday.day_id = c.day_id
                            and    (customerdeliveryday.typeofmerchadise = 1 or
                                  customerdeliveryday.typeofmerchadise = 2))) loop
      begin
        begin
          pack_import.cfbcreate_customerdelscheme(vcursor.customer_id, vcursor.deliveryscheme_id,
                                                  vcursor.day_id);
          countrowss := countrowss + 1;
        exception
          when dup_val_on_index then
            null;
          when others then
            errormsg := 'CFbImportCustomerDeliveryDays: Fail to import customer delivery scheme for customernumber/deliveryschemecode ' ||
                        vcursor.customernumber || '/' || vcursor.deliveryschemecode;
            pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
        end;
        if vcursor.delgarments not in ('N', 'C') then
          v_typeofmerchandise := 2;
          begin
            --insert for garments
            pack_import.add_check_customerdeliveryday(vcursor.customer_id, vcursor.day_id,
                                                      vcursor.delgarments, v_typeofmerchandise);
            countrows := countrows + 1;
          exception
            when dup_val_on_index then
              null;
            when others then
              errormsg := 'CFbImportCustomerDeliveryDays: Fail to import customer delivery day for customernumber/daynumber/typeofmerchandise ' ||
                          vcursor.customernumber || '/' || vcursor.daynumber || '/' ||
                          v_typeofmerchandise;
              pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
          end;
        end if;
        if vcursor.delnogarments != 'N' then
          v_typeofmerchandise := 1;
          begin
            --insert for nongarments
            pack_import.add_check_customerdeliveryday(vcursor.customer_id, vcursor.day_id,
                                                      vcursor.delnogarments, v_typeofmerchandise);
            countrows := countrows + 1;
          exception
            when dup_val_on_index then
              null;
            when others then
              errormsg := 'CFbImportCustomerDeliveryDays: Fail to import customer delivery day for customernumber/daynumber/typeofmerchandise ' ||
                          vcursor.customernumber || '/' || vcursor.daynumber || '/' ||
                          v_typeofmerchandise;
              pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
          end;
        end if;
      end;
    end loop;
    if countrowss > 0 then
      pack_import.write_log(countrowss || ' customer delivery schemes rows imported.');
    end if;
    -- PVD HVH added.
    insert into customerdeliveryday
      (customer_id, day_id, timestamp, systemuser_id, deliverytype, typeofmerchadise)
      select c.customer_id, c.day_id, sysdate, c.systemuser_id, c.deliverytype, 1
      from   customerdeliveryday c, customer z, i_customer i
      where  c.typeofmerchadise = 2
      and    c.customer_id = z.customer_id
      and    z.customernumber = i.customernumber
      and    not exists (select 1
              from   customerdeliveryday d
              where  d.customer_id = c.customer_id
              and    d.day_id = c.day_id
              and    d.typeofmerchadise = 1);
    countrows := countrows + sql%rowcount;
    begin
      -- adding missing records..
      insert into customerdeliveryday
        (customer_id, day_id, timestamp, systemuser_id, deliverytype, typeofmerchadise)
        select d.customer_id, d.day_id, sysdate, pack_import.lvnsystemuserid, 'D', 1
        from   customerdeliveryscheme d, customer c, i_customer i
        where  d.customer_id = c.customer_id
        and    c.customernumber = i.customernumber
        and    not exists (select 1
                from   customerdeliveryday x
                where  x.customer_id = d.customer_id
                and    x.day_id = d.day_id
                and    x.typeofmerchadise = 1)
        group  by d.customer_id, d.day_id;
      countrows := countrows + sql%rowcount;
    exception
      when others then
        errormsg := 'CFbImportCustomerDeliveryDays: Warning during customerdeliveryday correction.';
        pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 2);
    end;
    commit;
    if countrows > 0 then
      pack_import.write_log(countrows || ' customer delivery days added/checked.');
    end if;
    --- deliveryschemeperstop
    countrows := 0;
    -- PVD new cursor that only adds deliveryschemesperstop required from i_deliverydays
    for vcursor in (select c.customer_id, d.day_id, x.deliveryscheme_id, z.routestop_id, z.stopnumber,
                           z.route_id, r.routenumber
                    from   i_deliverydays i, customer c, day d, deliveryscheme x, route r,
                           routestop z, businessunit u
                    where  i.customernumber = c.customernumber
                    and    i.daynumber = d.daynumber
                    and    c.defaultbusinessunit_id = u.businessunit_id
                    and    u.plant_id = r.plant_id
                    and    d.day_id = r.drivingday_id
                    and    i.deliveryschemecode = x.code
                    and    i.plantcode_route is null
                    and    i.routenumber = r.routenumber
                    and    nvl(i.stopnumber, 0) = z.stopnumber
                    and    z.customer_id = c.customer_id
                    and    sysdate between z.dateactive and z.dateinactive
                    and    r.route_id = z.route_id
                    and    not exists (select s.customer_id
                            from   deliveryschemesperstop s
                            where  s.customer_id = c.customer_id
                            and    s.day_id = d.day_id
                            and    s.deliveryscheme_id = x.deliveryscheme_id
                            and    s.routestop_id = z.routestop_id)
                    union all
                    select c.customer_id, d.day_id, x.deliveryscheme_id, z.routestop_id, z.stopnumber,
                           z.route_id, r.routenumber
                    from   i_deliverydays i, customer c, day d, deliveryscheme x, route r,
                           routestop z, plant pt
                    where  i.customernumber = c.customernumber
                    and    i.daynumber = d.daynumber
                    and    i.plantcode_route = pt.code
                    and    pt.plant_id = r.plant_id
                    and    d.day_id = r.drivingday_id
                    and    i.deliveryschemecode = x.code
                    and    i.routenumber = r.routenumber
                    and    nvl(i.stopnumber, 0) = z.stopnumber
                    and    z.customer_id = c.customer_id
                    and    sysdate between z.dateactive and z.dateinactive
                    and    r.route_id = z.route_id
                    and    not exists (select s.customer_id
                            from   deliveryschemesperstop s
                            where  s.customer_id = c.customer_id
                            and    s.day_id = d.day_id
                            and    s.deliveryscheme_id = x.deliveryscheme_id
                            and    s.routestop_id = z.routestop_id)) loop
      begin
        insert into deliveryschemesperstop
          (routestop_id, customer_id, deliveryscheme_id, day_id, systemuser_id, timestamp)
        values
          (vcursor.routestop_id, vcursor.customer_id, vcursor.deliveryscheme_id, vcursor.day_id,
           pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportCustomerDeliveryDays: Fail to import delivery scheme per stop for customer_id/deliveryscheme_id/stopnumber ' ||
                      vcursor.customer_id || '/' || vcursor.deliveryscheme_id || '/' ||
                      vcursor.stopnumber;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(countrows || ' delivery schemes per route stop rows imported.');
    end if;
    --return routes
    countrows := 0;
    for rr in (select i.returnroute, i.returndaynumber, c.customer_id, rs.routestop_id,
                      i.customernumber, r.plant_id
               from   i_deliverydays i, customer c, businessunit bu, route r, routestop rs
               where  i.customernumber = c.customernumber
               and    c.defaultbusinessunit_id = bu.businessunit_id
               and    bu.plant_id = r.plant_id
               and    i.routenumber = r.routenumber
               and    i.daynumber = r.drivingday_id
               and    rs.route_id = r.route_id
               and    rs.customer_id = c.customer_id
               and    i.plantcode_route is null
               and    rs.stopnumber = i.stopnumber
               and    sysdate between rs.dateactive and rs.dateinactive
               and    i.returnroute is not null
               and    i.returndaynumber is not null
               union all
               select i.returnroute, i.returndaynumber, c.customer_id, rs.routestop_id,
                      i.customernumber, pt.plant_id
               from   i_deliverydays i, customer c, plant pt, route r, routestop rs
               where  i.customernumber = c.customernumber
               and    i.plantcode_route = pt.code
               and    pt.plant_id = r.plant_id
               and    i.routenumber = r.routenumber
               and    i.daynumber = r.drivingday_id
               and    rs.route_id = r.route_id
               and    rs.customer_id = c.customer_id
               and    rs.stopnumber = i.stopnumber
               and    sysdate between rs.dateactive and rs.dateinactive
               and    i.returnroute is not null
               and    i.returndaynumber is not null
               group  by i.returnroute, i.returndaynumber, c.customer_id, rs.routestop_id,
                         i.customernumber, r.plant_id, pt.plant_id) loop
      begin
        --get return route
        errormsg := 'return route number ' || to_char(rr.returnroute) || ' for day ' ||
                    to_char(rr.returndaynumber) || ' for customer ' || to_char(rr.customernumber);
        select r.route_id
        into   lvnreturnrouteid
        from   route r
        where  r.routenumber = rr.returnroute
        and    r.drivingday_id = rr.returndaynumber
        and    r.plant_id = rr.plant_id;
        --check customer in route!
        select max(rs.route_id)
        into   lvnreturnrouteid
        from   routestop rs
        where  rs.route_id = lvnreturnrouteid
        and    rs.customer_id = rr.customer_id
        and    sysdate between rs.dateactive and rs.dateinactive;
        if lvnreturnrouteid is null then
          begin
            pack_import.write_log('Customer ' || to_char(rr.customernumber) ||
                                  ' does not have a route stop in return route ' ||
                                  to_char(rr.returnroute) || ' for day ' ||
                                  to_char(rr.returndaynumber) ||
                                  ' return route cannot be updated!', 2);
          end;
        else
          begin
            --update return route for the routestop
            errormsg := 'update routestop id ' || to_char(rr.routestop_id) ||
                        ' with return route id ' || to_char(lvnreturnrouteid);
            update routestop rs
            set    rs.returnroute_id = lvnreturnrouteid
            where  rs.routestop_id = rr.routestop_id;
            countrows := countrows + 1;
          end;
        end if;
      exception
        when no_data_found then
          pack_import.write_log(errormsg || ' was not found, cannot update return route!', 2);
        when others then
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 2);
      end;
    end loop; --rr  return route
    commit;
    if countrows > 0 then
      pack_import.write_log(countrows || ' routestop records updated with a return route.');
    end if;
  exception
    when others then
      errormsg := 'Error during CFbImportCustomerDeliveryDays .. ';
      pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
  end cfbimportcustomerdeliverydays;
  -----import contracts per customer
  procedure cfbimportcontractspercustomer is
    contactpersonid contactperson.contactperson_id%type;
    employeeid      employee.employee_id%type;
    countrows       integer;
    priceindex_id   priceindex.priceindex_id%type;
  begin
    --insert contractspercustomer
    countrows := 0;
    for vcursor in (select a.*, b.customer_id, gainr.gainlostreason_id gainreason_id,
                           gainc.competitor_id gaincompetitor_id,
                           lostr.gainlostreason_id lostreason_id,
                           lostc.competitor_id lostcompetitor_id, bus.plant_id
                    from   i_customer a, customer b, gainlostreason gainr, gainlostreason lostr,
                           competitor lostc, competitor gainc, businessunit bus
                    where  a.customernumber = b.customernumber
                    and    b.defaultbusinessunit_id = bus.businessunit_id
                    and    a.contractcode is not null
                    and    a.gainreasoncode = gainr.code(+)
                    and    a.lostreasoncode = lostr.code(+)
                    and    a.gaincompetitorcode = gainc.code(+)
                    and    a.lostcompetitorcode = lostc.code(+)
                    and    not exists
                     (select z.customer_id
                            from   contractspercustomer z
                            where  b.customer_id = z.customer_id
                            and    nvl(a.contractcode, to_char(a.customernumber)) = z.code
                            and    a.contractdateactive = z.dateactive)) loop
      begin
        -- get contact person
        select min(contactperson_id)
        into   contactpersonid
        from   contactperson x
        where  x.customer_id = vcursor.customer_id
        and    x.contactpersonnumber = vcursor.contactpersonnumber;
        -- get sales employee
        if vcursor.salesemployeenumber is null then
          employeeid := null;
        else
          pack_import.cfbgetcreate_employee(vcursor.plant_id, employeeid,
                                            vcursor.salesemployeenumber, vcursor.salesemployeename,
                                            nvl(substr(vcursor.salesemployeename, 1, 10), '-'),
                                            to_date('1-1-2002', 'DD-MM-YYYY'), null, null, null,
                                            null, null);
        end if;
        -- get priceindex_id
        select min(priceindex_id)
        into   priceindex_id
        from   priceindex
        where  code = vcursor.priceindexcode;
        -- insert data
        insert into contractspercustomer
          (contractspercustomer_id, code, dateactive, dateinactive, signdate, continueservice,
           signalingweeks, contractdocument, purchaseorder, purchaseorderexpirationdate,
           purchaseordervalue, customer_id, contactperson_id, systemuser_id, gainreason_id,
           timestamp, gaincompetitor_id, lostcompetitor_id, lostreason_id, estimatedweeklysales,
           fixedweightperc, fixedsalesperc, fixedreplaceperc, fixedrentperc, fixedwashperc, cpibased,
           anniversarypriceadj, nextanniversarydate, salesemployee_id, noticeweeks,
           fixedimagecareperc, priceupdatemethod, priceindex_id)
        values
          (seq_contractspercustomer.nextval,
           nvl(vcursor.contractcode, to_char(vcursor.customernumber)),
           nvl(vcursor.contractdateactive, sysdate),
           nvl(vcursor.contractdateinactive, to_date('31-12-2099', 'DD-MM-YYYY')),
           nvl(vcursor.contractsigndate, sysdate), nvl(vcursor.contractcontinueservice, 'Y'),
           vcursor.contractsignalingweeks, vcursor.contractdocument, vcursor.purchaseorder,
           vcursor.purchaseorderexpirationdate, vcursor.purchaseordervalue, vcursor.customer_id,
           contactpersonid, pack_import.lvnsystemuserid, vcursor.gainreason_id, sysdate,
           vcursor.gaincompetitor_id, vcursor.lostcompetitor_id, vcursor.lostreason_id,
           vcursor.estimatedweeklysales, vcursor.fixedweightperc, vcursor.fixedsalesperc,
           vcursor.fixedreplaceperc, vcursor.fixedrentperc, vcursor.fixedwashperc, vcursor.cpibased,
           vcursor.anniversarypriceadj,
           nvl(vcursor.nextanniversarydate, to_date('31-12-2099', 'DD-MM-YYYY')), employeeid,
           nvl(vcursor.contract_noticeweeks, 0), nvl(vcursor.fixedimagecareperc, 0),
           vcursor.priceupdatemethod, priceindex_id);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportContractsPerCustomer: Fail to insert contract ' ||
                      vcursor.contractcode || ' for customernumber ' || vcursor.customernumber;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    commit;
    pack_import.write_log(countrows || ' contractspercustomer rows imported.');
  end cfbimportcontractspercustomer;
  procedure cfbimporttaxauthorities is
    fpnstates_id states.states_id%type;
    countrows    integer;
  begin
    -- add itable taxauthorities
    countrows := 0;
    for x in (select itx.*, ct.country_id
              from   i_taxauthorities itx
              left   outer join country ct
              on     ct.code = itx.country) loop
      begin
        begin
          select s.states_id
          into   fpnstates_id
          from   states s
          where  s.code = x.statecode
          and    s.country_id = nvl(x.country_id, pack_import.lvncountrydefaultid);
        exception
          when no_data_found then
            begin
              select seq_states.nextval into fpnstates_id from dual;
              insert into states
                (states_id, name, code, timestamp, systemuser_id, taxauthoritycode, country_id,
                 splittaxoninvoice)
              values
                (fpnstates_id, x.statename, x.statecode, sysdate, pack_import.lvnsystemuserid,
                 x.taxauthoritycode, nvl(x.country_id, pack_import.lvncountrydefaultid), 'Y');
              -- 3 times for each type,misc,rent and another
              insert into statestaxrate
                (states_id, oldtaxrate, taxtype, newtaxrate, systemuser_id, timestamp,
                 startdatetaxrate)
              values
                (fpnstates_id, 0, 1, x.taxrate, pack_import.lvnsystemuserid, sysdate,
                 to_date('01/01/2002', 'DD/MM/YYYY'));
              insert into statestaxrate
                (states_id, oldtaxrate, taxtype, newtaxrate, systemuser_id, timestamp,
                 startdatetaxrate)
              values
                (fpnstates_id, 0, 2, x.taxrate, pack_import.lvnsystemuserid, sysdate,
                 to_date('01/01/2002', 'DD/MM/YYYY'));
              insert into statestaxrate
                (states_id, oldtaxrate, taxtype, newtaxrate, systemuser_id, timestamp,
                 startdatetaxrate)
              values
                (fpnstates_id, 0, 3, x.taxrate, pack_import.lvnsystemuserid, sysdate,
                 to_date('01/01/2002', 'DD/MM/YYYY'));
            end;
        end;
        if x.linetype = 1 -- State
         then
          update states s
          set    s.taxauthoritycode = x.taxauthoritycode
          where  s.states_id = fpnstates_id
          and    s.country_id = nvl(x.country_id, pack_import.lvncountrydefaultid)
          and    s.taxauthoritycode is null;
        else
          begin
            if x.linetype = 3 -- County
             then
              insert into citycounty
                (citycounty_id, timestamp, systemuser_id, taxauthoritycode, name, type, states_id)
              values
                (seq_citycounty.nextval, sysdate, pack_import.lvnsystemuserid, x.taxauthoritycode,
                 x.citycountyname, 2, fpnstates_id);
            else
              -- City
              insert into citycounty
                (citycounty_id, timestamp, systemuser_id, taxauthoritycode, name, type, states_id)
              values
                (seq_citycounty.nextval, sysdate, pack_import.lvnsystemuserid, x.taxauthoritycode,
                 x.citycountyname, 1, fpnstates_id);
            end if;
            insert into citycountytaxrate
              (citycounty_id, taxtype, startdatetaxrate, systemuser_id, oldtaxrate, timestamp,
               newtaxrate)
            values
              (seq_citycounty.currval, 1, to_date('01/01/2002', 'DD/MM/YYYY'),
               pack_import.lvnsystemuserid, 0, sysdate, x.taxrate);
            insert into citycountytaxrate
              (citycounty_id, taxtype, startdatetaxrate, systemuser_id, oldtaxrate, timestamp,
               newtaxrate)
            values
              (seq_citycounty.currval, 2, to_date('01/01/2002', 'DD/MM/YYYY'),
               pack_import.lvnsystemuserid, 0, sysdate, x.taxrate);
            insert into citycountytaxrate
              (citycounty_id, taxtype, startdatetaxrate, systemuser_id, oldtaxrate, timestamp,
               newtaxrate)
            values
              (seq_citycounty.currval, 3, to_date('01/01/2002', 'DD/MM/YYYY'),
               pack_import.lvnsystemuserid, 0, sysdate, x.taxrate);
          end;
        end if;
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null; -- No problem if it already exists
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log('import_taxauthorities succeeded.');
      end;
    end if;
    countrows := 0;
    for vcursor in (select c.country_id, i.statetaxauthoritycode
                    from   i_customer i
                    join   country c
                    on     c.code = i.country
                    where  i.statetaxauthoritycode is not null
                    and    not exists (select s.states_id
                            from   states s
                            where  s.taxauthoritycode = i.statetaxauthoritycode
                            and    s.country_id = c.country_id)
                    group  by c.country_id, i.statetaxauthoritycode) loop
      begin
        insert into states
          (states_id, name, code, timestamp, systemuser_id, taxauthoritycode, country_id,
           turnovergroup_id, splittaxoninvoice)
        values
          (seq_states.nextval, vcursor.statetaxauthoritycode, vcursor.statetaxauthoritycode,
           sysdate, pack_import.lvnsystemuserid, vcursor.statetaxauthoritycode, vcursor.country_id,
           null, 'Y');
        insert into statestaxrate
          (states_id, oldtaxrate, taxtype, newtaxrate, systemuser_id, timestamp, startdatetaxrate)
        values
          (seq_states.currval, 0, 1, 0, pack_import.lvnsystemuserid, sysdate,
           to_date('01/01/2002', 'DD/MM/YYYY'));
        insert into statestaxrate
          (states_id, oldtaxrate, taxtype, newtaxrate, systemuser_id, timestamp, startdatetaxrate)
        values
          (seq_states.currval, 0, 2, 0, pack_import.lvnsystemuserid, sysdate,
           to_date('01/01/2002', 'DD/MM/YYYY'));
        insert into statestaxrate
          (states_id, oldtaxrate, taxtype, newtaxrate, systemuser_id, timestamp, startdatetaxrate)
        values
          (seq_states.currval, 0, 3, 0, pack_import.lvnsystemuserid, sysdate,
           to_date('01/01/2002', 'DD/MM/YYYY'));
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportTaxauthorities: Fail to insert statestaxauthoritycode ' ||
                      vcursor.statetaxauthoritycode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' statestaxauthoritycode rows inserted.');
      end;
    end if;
    countrows := 0;
    for vcursor in (select ic.countytaxauthoritycode, st.states_id
                    from   i_customer ic
                    join   country c
                    on     c.code = ic.country
                    join   states st
                    on     st.taxauthoritycode = ic.statetaxauthoritycode
                    and    st.country_id = c.country_id
                    where  ic.countytaxauthoritycode is not null
                    and    not exists
                     (select 1
                            from   citycounty ct
                            where  ct.type = 2
                            and    ct.taxauthoritycode = ic.countytaxauthoritycode)
                    group  by ic.countytaxauthoritycode, st.states_id) loop
      begin
        insert into citycounty
          (citycounty_id, timestamp, systemuser_id, taxauthoritycode, name, type, states_id)
        values
          (seq_citycounty.nextval, sysdate, pack_import.lvnsystemuserid,
           vcursor.countytaxauthoritycode, vcursor.countytaxauthoritycode, 2, vcursor.states_id);
        insert into citycountytaxrate
          (citycounty_id, taxtype, startdatetaxrate, systemuser_id, oldtaxrate, timestamp,
           newtaxrate)
        values
          (seq_citycounty.currval, 1, to_date('01/01/2002', 'DD/MM/YYYY'),
           pack_import.lvnsystemuserid, 0, sysdate, 0);
        insert into citycountytaxrate
          (citycounty_id, taxtype, startdatetaxrate, systemuser_id, oldtaxrate, timestamp,
           newtaxrate)
        values
          (seq_citycounty.currval, 2, to_date('01/01/2002', 'DD/MM/YYYY'),
           pack_import.lvnsystemuserid, 0, sysdate, 0);
        insert into citycountytaxrate
          (citycounty_id, taxtype, startdatetaxrate, systemuser_id, oldtaxrate, timestamp,
           newtaxrate)
        values
          (seq_citycounty.currval, 3, to_date('01/01/2002', 'DD/MM/YYYY'),
           pack_import.lvnsystemuserid, 0, sysdate, 0);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportTaxauthorities: Fail to insert statestaxauthoritycode ' ||
                      vcursor.countytaxauthoritycode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' countytaxauthoritycode rows inserted.');
      end;
    end if;
    countrows := 0;
    for vcursor in (select i.citytaxauthoritycode, st.states_id
                    from   i_customer i
                    join   country c
                    on     c.code = i.country
                    join   states st
                    on     st.taxauthoritycode = i.statetaxauthoritycode
                    and    st.country_id = c.country_id
                    where  i.citytaxauthoritycode is not null
                    and    not exists
                     (select 1
                            from   citycounty ct
                            where  ct.type = 1
                            and    ct.taxauthoritycode = i.citytaxauthoritycode)
                    group  by i.citytaxauthoritycode, st.states_id) loop
      begin
        insert into citycounty
          (citycounty_id, timestamp, systemuser_id, taxauthoritycode, name, type, states_id)
        values
          (seq_citycounty.nextval, sysdate, pack_import.lvnsystemuserid,
           vcursor.citytaxauthoritycode, vcursor.citytaxauthoritycode, 1, vcursor.states_id);
        insert into citycountytaxrate
          (citycounty_id, taxtype, startdatetaxrate, systemuser_id, oldtaxrate, timestamp,
           newtaxrate)
        values
          (seq_citycounty.currval, 1, to_date('01/01/2002', 'DD/MM/YYYY'),
           pack_import.lvnsystemuserid, 0, sysdate, 0);
        insert into citycountytaxrate
          (citycounty_id, taxtype, startdatetaxrate, systemuser_id, oldtaxrate, timestamp,
           newtaxrate)
        values
          (seq_citycounty.currval, 2, to_date('01/01/2002', 'DD/MM/YYYY'),
           pack_import.lvnsystemuserid, 0, sysdate, 0);
        insert into citycountytaxrate
          (citycounty_id, taxtype, startdatetaxrate, systemuser_id, oldtaxrate, timestamp,
           newtaxrate)
        values
          (seq_citycounty.currval, 3, to_date('01/01/2002', 'DD/MM/YYYY'),
           pack_import.lvnsystemuserid, 0, sysdate, 0);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportTaxauthorities: Fail to insert statestaxauthoritycode/citytaxauthoritycode ' ||
                      vcursor.citytaxauthoritycode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' citytaxauthoritycode rows inserted.');
      end;
    end if;
    countrows := 0;
    --Import taxdefinition.
    for x in (select g.taxgroup_id, s.states_id, l.invoicelinetype_id
              from   i_taxdefinition i
              join   taxgroup g
              on     g.code = i.taxgroupcode
              join   states s
              on     (s.country_id = g.country_id and s.code = i.statecode)
              cross  join invoicelinetype l) loop
      begin
        insert into taxdefinition
          (taxgroup_id, states_id, timestamp, systemuser_id, invoicelinetype_id)
        values
          (x.taxgroup_id, x.states_id, sysdate, pack_import.lvnsystemuserid, x.invoicelinetype_id);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null; --no problem.
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log('import_taxdefinition succeeded. ' || countrows ||
                              ' taxdefinition rows inserted');
      end;
    end if;
  exception
    when others then
      rollback;
      pack_import.write_log('import_taxauthorities/taxdefinition failed: ' ||
                            substr(sqlerrm, 1, 512), 3);
  end cfbimporttaxauthorities;
  function add_systemuser(fp_username  in varchar2,
                          fp_groupname in varchar2,
                          fp_fullname  in varchar2) return number is
    lv_usergroup_id usergroup.usergroup_id%type;
    lv_systemuserid number;
  begin
    if trim(fp_username) is null then
      begin
        lv_systemuserid := null;
      end;
    else
      begin
        -- determine and create if needed followed by user.
        select s.systemuser_id
        into   lv_systemuserid
        from   systemuser s
        where  s.username = upper(trim(fp_username));
      exception
        when no_data_found then
          begin
            -- determine usergroup. This is the group to which they will all belong
            errormsg := 'get usergroup ' || upper(trim(fp_groupname));
            select g.usergroup_id
            into   lv_usergroup_id
            from   usergroup g
            where  g.groupname = upper(trim(fp_groupname));
            pack_import.cfbcreate_systemuser(lv_systemuserid,
                                             --fpnsystemuser_id,
                                             lv_usergroup_id,
                                             --fpnusergroup_id,
                                             upper(trim(fp_username)),
                                             --fpsusername,
                                             'PFpP3zMAjbw=',
                                             --fpspassword,
                                             nvl(fp_fullname, fp_username),
                                             --fpsfullname,
                                             'Y',
                                             --fpsactive,
                                             'N',
                                             --fpssysadmin,
                                             null,
                                             --fpsremark,
                                             'Y'); --fpscontactmanagerfullrights);
          end;
      end;
    end if;
    return lv_systemuserid;
  end add_systemuser;
  procedure import_contactcalls_followup is
    lv_counter          number := 0;
    fpncreatedbyuser_id systemuser.systemuser_id%type;
  begin
    --ABS-83974 RFCA conversion
    update i_contactcalls_followup c set c.followupnotes = replace(c.followupnotes, '~', chr(10));
    --import_contactcalls_followup
    for y in (select ccf.*, ct.contact_id, cc.groupname
              from   i_contactcalls_followup ccf
              join   contact ct
              on     ct.callnumber = ccf.callnumber
              join   i_contactcalls cc
              on     cc.callnumber = ccf.callnumber) loop
      begin
        --add_systemuser
        fpncreatedbyuser_id := add_systemuser(y.createdby, y.groupname, y.createdbyfullname);
        insert into contactfollowupnote
          (contactfollowupnote_id, contact_id, creationtimestamp, createdbyusername,
           createdbyuserfullname, createdbyuser_id, note, systemusername, systemuser_id, timestamp)
        values
          (seq_contactfollowupnote.nextval, y.contact_id, y.createdate, y.createdby,
           y.createdbyfullname, fpncreatedbyuser_id, y.followupnotes, y.createdbyfullname,
           pack_import.lvnsystemuserid, sysdate);
        lv_counter := lv_counter + 1;
      exception
        when dup_val_on_index then
          null; --no problem already exists
      end;
    end loop; --y
    if lv_counter > 0 then
      begin
        commit;
        pack_import.write_log(to_char(lv_counter) || ' contactcall followup rows inserted.');
      end;
    end if;
  end import_contactcalls_followup;
  procedure cfbimportcontactcalls is
    fpncontact_id          contact.contact_id%type;
    fpncreatedbyuser_id    systemuser.systemuser_id%type;
    fpnfollowupbyuser_id   systemuser.systemuser_id%type;
    fpninprogressbyuser_id systemuser.systemuser_id%type;
    fpnclosedbyuser_id     systemuser.systemuser_id%type;
    fpnreviewedbyuser_id   systemuser.systemuser_id%type;
    fpncompletedbyuser_id  systemuser.systemuser_id%type;
    fpncustomer_link_id    customer_link.customer_link_id%type;
    fpndepartment_link_id  department_link.department_link_id%type;
    fpnbusinessunit_id     businessunit.businessunit_id%type;
    fpncontactcategory_id  contactcategory.contactcategory_id%type;
    fpncontactperson_id    contactperson.contactperson_id%type;
    fpscontactpersonname   contactperson.name%type;
    fpncountercalls        number := 0;
  begin
    -- update table with enter characters for ~
    update i_contactcalls c
    set    c.contactnotes = replace(c.contactnotes, '~', chr(10)),
           c.followupnotes = replace(c.followupnotes, '~', chr(10));
    -- loop the records.
    for x in (select *
              from   i_contactcalls i
              where  not exists (select 1 from contact c where c.callnumber = i.callnumber)
              order  by i.originalcallnumber asc, i.callnumber asc) loop
      begin
        -- get the different users
        fpncreatedbyuser_id    := add_systemuser(x.createdby, x.groupname, x.createdbyfullname);
        fpnfollowupbyuser_id   := add_systemuser(x.followupneededby, x.groupname,
                                                 x.followupneededbyfullname);
        fpninprogressbyuser_id := add_systemuser(x.inprogressbyuser, x.groupname, null);
        fpnclosedbyuser_id     := add_systemuser(x.closedbyuser, x.groupname, null);
        fpnreviewedbyuser_id   := add_systemuser(x.reviewedbyuser, x.groupname, null);
        fpncompletedbyuser_id  := add_systemuser(x.completedbyuser, x.groupname, null);
        begin
          -- determine / creat contact catagory.
          select c.contactcategory_id
          into   fpncontactcategory_id
          from   contactcategory c
          where  c.code = x.contactcategorycode;
        exception
          when no_data_found then
            begin
              pack_import.cfbcreate_contactcategory(fpncontactcategory_id,
                                                    --fpncontactcategory_id,
                                                    x.contactcategorycode,
                                                    --fpscode,
                                                    'N'); --fpdttimestamp);
              pack_import.cfbcreate_contactcategory_desc(fpncontactcategory_id,
                                                         --fpncontactcategory_id,
                                                         x.contactcategorydescription);
            end;
        end;
        -- determine customer
        errormsg := 'Customer ' || x.customer;
        select c.customer_id
        into   fpncustomer_link_id
        from   customer c
        where  c.customernumber = x.customer;
        -- and department if needed (optional).
        if x.department is null then
          begin
            fpndepartment_link_id := null;
          end;
        else
          begin
            select d.department_id
            into   fpndepartment_link_id
            from   department d
            where  d.departmentnumber = x.department
            and    d.customer_id = fpncustomer_link_id;
          exception
            when others then
              fpndepartment_link_id := null;
          end;
        end if;
        -- determine business unit.
        errormsg := 'Businessunit ' || x.businessunit;
        select u.businessunit_id
        into   fpnbusinessunit_id
        from   businessunit u
        where  u.code = x.businessunit;
        begin
          -- determine contactperson (optional)
          select c.contactperson_id, c.name
          into   fpncontactperson_id, fpscontactpersonname
          from   contactperson c
          where  c.contactpersonnumber = x.customercontactperson
          and    c.customer_id = fpncustomer_link_id;
        exception
          when no_data_found then
            begin
              fpncontactperson_id  := null;
              fpscontactpersonname := null;
            end;
        end;
        -- create the contactcall record.
        pack_import.cfbcreate_contact(fpncontact_id,
                                      --fpncontact_id,
                                      fpncustomer_link_id,
                                      --fpncustomer_link_id,
                                      fpndepartment_link_id,
                                      --fpndepartment_link_id,
                                      fpnbusinessunit_id,
                                      --fpnbusinessunit_id,
                                      fpncontactcategory_id,
                                      --fpncontactcategory_id,
                                      fpncreatedbyuser_id,
                                      --fpncreatedbyuser_id,
                                      fpnfollowupbyuser_id,
                                      --fpnfollowupbyuser_id,
                                      x.createdate,
                                      --fpdtnewdate,
                                      x.callnumber,
                                      --fpncallnumber,
                                      nvl(x.followupdate, to_date('31-12-2099', 'dd-mm-yyyy')),
                                      --fpdtfollowupdate,
                                      nvl(x.inprogressdate, to_date('31-12-2099', 'dd-mm-yyyy')),
                                      --fpdtinprogressdate,
                                      nvl(x.closedate, to_date('31-12-2099', 'dd-mm-yyyy')),
                                      --fpdtclosedate,
                                      x.status,
                                      --fpnstatus,
                                      fpscontactpersonname,
                                      --fpscontactpersonname,
                                      fpncontactperson_id,
                                      --fpncontactperson_id,
                                      x.followupneededbyfullname,
                                      --fpsfollowupbyusername,
                                      x.createdbyfullname,
                                      --fpscreatedbyusername,
                                      x.contactnotes,
                                      --fpscontactnotes,
                                      x.followupnotes,
                                      --fpsfollowupnotes,
                                      null,
                                      --fpsattachment,
                                      x.showonroutelist,
                                      --fpsshowonroutelist
                                      fpninprogressbyuser_id, x.inprogressbyuser, fpnclosedbyuser_id,
                                      x.closedbyuser, x.priority, x.contactcause_code,
                                      x.completeddate, fpncompletedbyuser_id, x.completedbyuser,
                                      x.reviewdate, fpnreviewedbyuser_id, x.reviewedbyuser,
                                      x.blockdepartureonstop, x.followupbyroute,
                                      x.originalcallnumber, x.checkbeforeroutestart);
        fpncountercalls := fpncountercalls + 1;
      exception
        when dup_val_on_index then
          null; --no problem already exists
        when others then
          pack_import.write_log('Error import contactcalls call#:' || to_char(x.callnumber) || ' ' ||
                                errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    commit;
    if fpncountercalls > 0 then
      pack_import.write_log(to_char(fpncountercalls) || ' contactcalls rows inserted.');
    end if;
    --import_contactcalls_followup
    import_contactcalls_followup;
  exception
    when others then
      rollback;
      pack_import.write_log('import cfbimportcontactcalls failed: ' || substr(sqlerrm, 1, 512), 3);
  end cfbimportcontactcalls;
  --- INTERNAL import weighingcategories
  procedure cfbimport_weighingcategory is
    lvcounter         number := 0;
    lvactivityid      activity.activity_id%type;
    lvturnovergroupid turnovergroup.turnovergroup_id%type;
  begin
    ---determine activity
    --- start loop weighingcatory
    for x in (select i.weighingcategorycode, i.weighingcategorydescription, i.weighingcategoryrewash,
                     i.weighingcategorylegacycode, i.weighingcategoryeannumber,
                     max(i.weighingcatturnovergroup) weighingcatturnovergroup,
                     max(i.internalcalcpercentage) internalcalcpercentage,
                     max(i.weighingcat_activitycode) weighingcat_activitycode
              from   i_weighingcategpercustomer i
              where  not exists (select w.weighingcategory_id
                      from   weighingcategory w
                      where  w.code = i.weighingcategorycode)
              group  by i.weighingcategorycode, i.weighingcategorydescription,
                        i.weighingcategoryrewash, i.weighingcategorylegacycode,
                        i.weighingcategoryeannumber) loop
      begin
        if x.weighingcat_activitycode is null then
          select min(a.activity_id) into lvactivityid from activity a where a.active = 'Y';
        else
          --select activity id
          select a.activity_id
          into   lvactivityid
          from   activity a
          where  a.code = x.weighingcat_activitycode;
        end if;
        if x.weighingcatturnovergroup is null then
          begin
            lvturnovergroupid := null;
          end;
        else
          begin
            --- get turnovergroup
            select g.turnovergroup_id
            into   lvturnovergroupid
            from   turnovergroup g
            where  g.code = x.weighingcatturnovergroup;
          exception
            when others then
              begin
                insert into turnovergroup
                  (turnovergroup_id, salesjournalgroup_id, code, legacycode, active, systemuser_id,
                   timestamp)
                values
                  (seq_turnovergroup.nextval, pack_import.lvnsalesjournalgroupminusid,
                   x.weighingcatturnovergroup, null, 'Y', pack_import.lvnsystemuserid, sysdate)
                returning turnovergroup_id into lvturnovergroupid;
                insert into turnovergroup_desc
                  (turnovergroup_id, language_id, description, systemuser_id, timestamp)
                values
                  (lvturnovergroupid, pack_import.lvnlanguageid, x.weighingcatturnovergroup,
                   pack_import.lvnsystemuserid, sysdate);
              exception
                when others then
                  lvturnovergroupid := null;
              end;
          end;
        end if;
        --- weighingcategory
        insert into weighingcategory
          (weighingcategory_id, code, active, rewash, systemuser_id, legacyweighingcategorycode,
           timestamp, turnovergroup_id, activity_id, eannumber, internalcalcpercentage)
        values
          (seq_weighingcategory.nextval, x.weighingcategorycode, 'Y', x.weighingcategoryrewash,
           pack_import.lvnsystemuserid, x.weighingcategorylegacycode, sysdate, lvturnovergroupid,
           lvactivityid, x.weighingcategoryeannumber, x.internalcalcpercentage);
        insert into weighingcategory_desc
          (weighingcategory_id, language_id, systemuser_id, description, timestamp)
        values
          (seq_weighingcategory.currval, pack_import.lvnlanguageid, pack_import.lvnsystemuserid,
           x.weighingcategorydescription, sysdate);
        insert into weighingcategory_link
          (weighingcategory_link_id, weighingcategory_id, code, legacyweighingcategorycode,
           systemuser_id, timestamp)
        values
          (seq_weighingcategory.currval, seq_weighingcategory.currval, x.weighingcategorycode,
           x.weighingcategorylegacycode, pack_import.lvnsystemuserid, sysdate);
        insert into weighingcategory_link_desc
          (weighingcategory_link_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_weighingcategory.currval, pack_import.lvnlanguageid, x.weighingcategorydescription,
           pack_import.lvnsystemuserid, sysdate);
        lvcounter := lvcounter + 1;
      exception
        when dup_val_on_index then
          null;
      end;
    end loop;
    commit;
    if lvcounter > 0 then
      pack_import.write_log(lvcounter || ' weighingcategory rows imported.');
    end if;
  exception
    when others then
      begin
        rollback;
        errormsg := 'cfbimport_weighingcategory: Failed to import.';
        pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_weighingcategory;
  --- import weighingcategories + customer weighingcategories
  procedure cfbimport_weighingcategpercust is
    lvcounter                number := 0;
    lvcustomerid             customer.customer_id%type;
    lvweighingcategoryid     weighingcategory.weighingcategory_id%type;
    lvtaxgroupid             taxgroup.taxgroup_id%type;
    lvsoil                   customerweightprice.soil%type;
    lvpricelistpercustomerid pricelistpercustomer.pricelistpercustomer_id%type;
    procedure import_missing_custactivities is
    begin
      --insert missing businessunitactivities for i_weighingcategpercustomer
      errormsg := 'insert missing businessunitactivities for i_weighingcategpercustomer';
      insert into businessunitactivities
        (businessunit_id, activity_id, systemuser_id, timestamp, invoicedbybusinessunit_id)
        select c.defaultbusinessunit_id, g.activity_id, pack_import.lvnsystemuserid, sysdate,
               max(c.defaultinvoicebusinessunit_id)
        from   customer c, weighingcategory g, weighingcategpercustomer y
        where  g.weighingcategory_id = y.weighingcategory_id
        and    y.customer_id = c.customer_id
        and    not exists (select 1
                from   businessunitactivities x
                where  x.businessunit_id = c.defaultbusinessunit_id
                and    x.activity_id = g.activity_id)
        and    exists (select i.customernumber
                from   i_weighingcategpercustomer i
                where  i.customernumber = c.customernumber)
        group  by c.defaultbusinessunit_id, g.activity_id;
      lvcounter := sql%rowcount;
      if lvcounter > 0 then
        begin
          commit;
          pack_import.write_log(to_char(lvcounter) ||
                                ' missing businessunitactivities added (based on weighingcategpercustomer)');
        end;
      end if;
      errormsg := 'insert into customeractivities for i_weighingcategpercustomer';
      insert into customeractivities
        (customer_id, processbusinessunit_id, activity_id, invoicebusinessunit_id, systemuser_id,
         timestamp, cutoffdate, finalinvoicecreated, invoicefrequency_id)
        select c.customer_id, max(c.defaultbusinessunit_id), g.activity_id,
               max(c.defaultinvoicebusinessunit_id), pack_import.lvnsystemuserid, sysdate, null, 'N',
               max(c.invoicefrequency_id)
        from   customer c, weighingcategory g, weighingcategpercustomer y
        where  g.weighingcategory_id = y.weighingcategory_id
        and    y.customer_id = c.customer_id
        and    not exists (select x.customer_id, x.activity_id
                from   customeractivities x
                where  x.customer_id = c.customer_id
                and    x.activity_id = g.activity_id)
        and    exists (select i.customernumber
                from   i_weighingcategpercustomer i
                where  i.customernumber = c.customernumber)
        group  by c.customer_id, g.activity_id;
      lvcounter := sql%rowcount;
      if lvcounter > 0 then
        begin
          commit;
          pack_import.write_log(to_char(lvcounter) ||
                                ' missing customeractivities added (based on weighingcategpercustomer)');
        end;
      end if;
    exception
      when others then
        begin
          rollback;
          pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
        end;
    end import_missing_custactivities;
  begin
    --import the weighingcategory
    cfbimport_weighingcategory;
    --in loop add customer weighingcatergories
    for x in (select w.weighingcategorycode, w.customernumber, nvl(w.weightclean, 'N') weightclean,
                     nvl(w.weightsoiled, 'Y') weightsoiled, nvl(w.invoicemethod, 1) invoicemethod,
                     nvl(w.soilpercentage, 0) soilpercentage,
                     nvl(w.dateactive, trunc(sysdate - 1)) dateactive,
                     nvl(w.dateinactive, to_date('31/12/2099', 'dd/mm/yyyy')) dateinactive,
                     w.invoicegroupingcode, w.eannumber, w.taxgroupcode, w.price, w.pricestartdate,
                     w.weighingcatturnovergroup, w.discount, w.discountstartdate
              from   i_weighingcategpercustomer w
              where  not exists (select a.weighingcategpercustomer_id
                      from   weighingcategpercustomer a, weighingcategory b, customer c
                      where  a.weighingcategory_id = b.weighingcategory_id
                      and    b.code = w.weighingcategorycode
                      and    c.customernumber = w.customernumber
                      and    c.customer_id = a.customer_id)) loop
      begin
        --- get customer id
        errormsg := ' customer ' || x.customernumber;
        select c.customer_id
        into   lvcustomerid
        from   customer c
        where  c.customernumber = x.customernumber;
        --- get weighingcategory id
        errormsg := ' weighingcategory ' || x.weighingcategorycode;
        select w.weighingcategory_id
        into   lvweighingcategoryid
        from   weighingcategory w
        where  w.code = x.weighingcategorycode;
        if x.weighingcatturnovergroup is not null then
          begin
            ---check if taxgroup in turnovergroup is for right country
            ---if so then use it
            select g.taxgroup_id
            into   lvtaxgroupid
            from   turnovergroup g, taxgroup x, customer c
            where  g.code = x.weighingcatturnovergroup
            and    c.customer_id = lvcustomerid
            and    c.country_id = x.country_id
            and    x.taxgroup_id = g.taxgroup_id;
          exception
            when others then
              lvtaxgroupid := null;
          end;
        end if;
        if lvtaxgroupid is null then
          begin
            --- get taxgroup id if exists for the right country
            errormsg := ' taxgroup ' || x.taxgroupcode;
            select g.taxgroup_id
            into   lvtaxgroupid
            from   taxgroup g, customer c
            where  g.code = x.taxgroupcode
            and    c.customer_id = lvcustomerid
            and    c.country_id = g.country_id;
          exception
            when others then
              lvtaxgroupid := null;
          end;
        end if;
        -- insert weighingcategory per customer
        insert into weighingcategpercustomer
          (weighingcategpercustomer_id, weighingcategory_id, weightsoiled, weightclean, dateactive,
           totalweightsoil, dateinactive, totalweightclean, invoicemethod, customer_id,
           systemuser_id, soilpercentage, timestamp, totalamountinvoicedsoil,
           totalamountinvoicedclean, invoicegroupingcode, eannumber, taxgroup_id)
        values
          (seq_weighingcategpercustomer.nextval, lvweighingcategoryid, x.weightsoiled,
           x.weightclean, x.dateactive, 0, x.dateinactive, 0, x.invoicemethod, lvcustomerid,
           pack_import.lvnsystemuserid, x.soilpercentage, sysdate, 0, 0, x.invoicegroupingcode,
           x.eannumber, lvtaxgroupid);
        --- add customerweightprice when price is used
        if x.price >= 0 then
          begin
            if x.invoicemethod = 3 then
              begin
                lvsoil := 'N';
              end;
            else
              begin
                lvsoil := 'Y';
              end;
            end if;
            insert into customerweightprice
              (customerweightprice_id, weighingcategpercustomer_id, timestamp, systemuser_id, price,
               startdate, soil)
            values
              (seq_customerweightprice.nextval, seq_weighingcategpercustomer.currval, sysdate,
               pack_import.lvnsystemuserid, x.price, nvl(x.pricestartdate, x.dateactive), lvsoil);
            pack_import.cfbcreate_pricelistpercustomer(lvpricelistpercustomerid, lvcustomerid, 5,
                                                       null, null, x.dateactive, x.dateinactive,
                                                       null, null, null);
          exception
            when dup_val_on_index then
              null;
          end;
        end if; --if x.price >= 0
        --add customer weight discount
        if x.discount >= 0 then
          begin
            if x.invoicemethod = 3 then
              begin
                lvsoil := 'N';
              end;
            else
              begin
                lvsoil := 'Y';
              end;
            end if;
            insert into customerweightdiscount
              (customerweightdiscount_id, weighingcategpercustomer_id, timestamp, systemuser_id,
               discount, startdate, soil)
            values
              (seq_customerweightdiscount.nextval, seq_weighingcategpercustomer.currval, sysdate,
               pack_import.lvnsystemuserid, x.discount, nvl(x.discountstartdate, x.dateactive),
               lvsoil);
            pack_import.cfbcreate_pricelistpercustomer(lvpricelistpercustomerid, lvcustomerid, 5,
                                                       null, null, x.dateactive, x.dateinactive,
                                                       null, null, null);
          end;
        end if; --if x.discount >= 0
        lvcounter := lvcounter + 1;
      exception
        when no_data_found then
          begin
            errormsg := errormsg || ' not found.';
            pack_import.write_log('cfbimport_weighingcategpercust ' || errormsg, 3);
          end;
      end;
    end loop;
    if lvcounter > 0 then
      begin
        commit;
        pack_import.write_log(lvcounter || ' weighingcategpercustomer rows imported.');
      end;
    end if;
    --import_missing_custactivities
    import_missing_custactivities;
  exception
    when others then
      begin
        rollback;
        errormsg := 'cfbimport_weighingcategpercust: Failed to import.';
        pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_weighingcategpercust;
  procedure cfbimport_generaluserinstruction is
    lvcounter            number := 0;
    lvgeneraluserinstrid generaluserinstruction.generaluserinstruction_id%type;
    lvcustomerid         customer.customer_id%type;
    lv_code              generaluserinstruction.code%type := '*';
    lv_instr             customeruserinstruction_desc.instruction%type := '*';
    lv_custno            customer.customernumber%type := -1;
    lv_dateactive0       date := to_date('31/12/2099', 'dd/mm/yyyy');
    lv_dateactive        date := to_date('31/12/2099', 'dd/mm/yyyy');
    lv_langid            languages.language_id%type := -1;
    lv_generalid         generaluserinstruction.generaluserinstruction_id%type := -1;
    errormsg             varchar2(1000);
    procedure upd_userinstructionperscreen(fp_dialogid           in dialogs.dialog_id%type,
                                           fp_generaluserinstrid in generaluserinstruction.generaluserinstruction_id%type) is
    begin
      if fp_dialogid is not null then
        begin
          --insert into userinstructionperscreen
          insert into userinstructionperscreen
            (userinstructionperscreen_id, systemuser_id, timestamp, dialog_id,
             generaluserinstruction_id)
          values
            (seq_userinstructionperscreen.nextval, pack_import.lvnsystemuserid, sysdate,
             fp_dialogid, fp_generaluserinstrid);
        end;
      end if;
    exception
      when dup_val_on_index then
        null;
    end upd_userinstructionperscreen;
  begin
    for x in (select g.*, l.language_id, d.dialog_id, g.rowid
              from   i_generaluserinstruction g
              left   outer join languages l
              on     l.code = g.languagecode
              left   outer join dialogs d
              on     d.code = g.dialogcode
              where  g.imported_yn = 'N'
              order  by g.code, g.dateactive, g.customernumber, g.instruction, g.languagecode) loop
      begin
        if (x.code <> lv_code or x.dateactive <> lv_dateactive0 or x.language_id <> lv_langid) then
          begin
            if (x.code <> lv_code or x.dateactive <> lv_dateactive0) then
              begin
                lv_code        := x.code;
                lv_dateactive0 := x.dateactive;
                begin
                  insert into generaluserinstruction
                    (generaluserinstruction_id, code, dateactive, dateinactive, systemuser_id,
                     timestamp, enddateautomsg)
                  values
                    (seq_generaluserinstruction.nextval, x.code, x.dateactive, x.dateinactive,
                     pack_import.lvnsystemuserid, sysdate, x.enddateautomsg)
                  returning generaluserinstruction_id into lvgeneraluserinstrid;
                exception
                  when dup_val_on_index then
                    begin
                      select g.generaluserinstruction_id
                      into   lvgeneraluserinstrid
                      from   generaluserinstruction g
                      where  g.code = lv_code
                      and    g.dateactive = lv_dateactive0;
                    end;
                end;
                if (x.language_id <> lv_langid or lv_generalid <> lvgeneraluserinstrid) then
                  begin
                    lv_langid    := x.language_id;
                    lv_generalid := lvgeneraluserinstrid;
                    insert into generaluserinstruction_desc
                      (generaluserinstruction_id, language_id, description, instruction,
                       systemuser_id, timestamp)
                    values
                      (lvgeneraluserinstrid, x.language_id, x.description, x.instruction,
                       pack_import.lvnsystemuserid, sysdate);
                  exception
                    when dup_val_on_index then
                      null;
                  end;
                end if;
              end;
            end if;
            -- get customer id
            errormsg := ' customer ' || x.customernumber;
            select c.customer_id
            into   lvcustomerid
            from   customer c
            where  c.customernumber = x.customernumber;
            if (x.customernumber <> lv_custno or x.dateactive <> lv_dateactive or
               x.instruction <> lv_instr or x.language_id <> lv_langid) then
              begin
                if x.customernumber <> lv_custno or x.dateactive <> lv_dateactive or
                   x.instruction <> lv_instr then
                  begin
                    lv_custno     := x.customernumber;
                    lv_dateactive := x.dateactive;
                    lv_instr      := x.instruction;
                    insert into generaluserinstructionpercust
                      (generaluserinstruction_id, customer_id, systemuser_id, timestamp)
                    values
                      (lvgeneraluserinstrid, lvcustomerid, pack_import.lvnsystemuserid, sysdate);
                  exception
                    when dup_val_on_index then
                      null;
                  end;
                end if;
              end;
            end if;
          end;
        end if;
        --upd_userinstructionperscreen
        upd_userinstructionperscreen(x.dialog_id, lvgeneraluserinstrid);
        --update line as being imported
        update i_generaluserinstruction i set i.imported_yn = 'Y' where i.rowid = x.rowid;
        lvcounter := lvcounter + 1;
      exception
        when no_data_found then
          begin
            errormsg := errormsg || ' not found.';
            pack_import.write_log('cfbimport_generaluserinstruction ' || errormsg, 3);
          end;
      end;
    end loop;
    commit;
    pack_import.write_log(lvcounter || ' general user instructions imported.');
  exception
    when others then
      begin
        rollback;
        errormsg := 'cfbimport_generaluserinstruction: Failed to import.';
        pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_generaluserinstruction;
  procedure cfbimport_custuserinstruction is
    lvcounter                   number := 0;
    lvcustomerid                customer.customer_id%type;
    lvcustomeruserinstructionid customeruserinstruction.customeruserinstruction_id%type;
    cr                      varchar2(1) := chr(10); -- Form feed
    lvuserinstructiontypeid customeruserinstruction.userinstructiontype_id%type;
    procedure cfbcreate_userinstructiontype is
      lcountrows number := 0;
    begin
      insert into userinstructiontype
        (userinstructiontype_id, code, description, timestamp, systemuser_id)
        select seq_userinstructiontype.nextval, y.instructiontype, y.instructiontype, sysdate,
               pack_import.lvnsystemuserid
        from   (select ic.userinstructiontype instructiontype
                 from   i_customeruserinstruction ic
                 where  ic.userinstructiontype is not null
                 group  by ic.userinstructiontype) y
        where  not exists (select 1 from userinstructiontype ut where ut.code = y.instructiontype);
      lcountrows := sql%rowcount;
      if lcountrows > 0 then
        begin
          commit;
          pack_import.write_log(lcountrows || ' userinstructiontype rows imported.');
        end;
      end if;
    exception
      when others then
        begin
          rollback;
          errormsg := 'Fail to import userinstructiontype';
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
        end;
    end cfbcreate_userinstructiontype;
    procedure upd_userinstructionperscreen(fp_custuserinstrid in customeruserinstruction.customeruserinstruction_id%type,
                                           fp_dialogid        in dialogs.dialog_id%type) is
    begin
      if fp_dialogid is not null then
        begin
          --insert into userinstructionperscreen
          insert into userinstructionperscreen
            (userinstructionperscreen_id, customeruserinstruction_id, systemuser_id, timestamp,
             dialog_id)
          values
            (seq_userinstructionperscreen.nextval, fp_custuserinstrid, pack_import.lvnsystemuserid,
             sysdate, fp_dialogid);
        end;
      end if;
    exception
      when dup_val_on_index then
        null;
    end upd_userinstructionperscreen;
  begin
    --create userinstructiontype
    cfbcreate_userinstructiontype;
    for x in (select u.customernumber, replace(u.instruction, '|', cr) instruction, u.dateactive,
                     u.dateinactive, u.enddateautomsg,
                     nvl(l.language_id, pack_import.lvnlanguageid) language_id, u.rowid, dg.dialog_id,
                     u.userinstructiontype
              from   i_customeruserinstruction u
              left   outer join languages l
              on     l.code = u.languagecode
              left   outer join dialogs dg
              on     dg.code = u.dialogcode
              where  u.imported_yn = 'N'
              order  by u.customernumber, u.instruction, u.dateactive, u.languagecode) loop
      begin
        --get userinstructiontype id
        errormsg := 'UserInstructionType ' || x.userinstructiontype || ' linked to customer ' ||
                    x.customernumber;
        if x.userinstructiontype is not null then
          begin
            select ui.userinstructiontype_id
            into   lvuserinstructiontypeid
            from   userinstructiontype ui
            where  ui.code = x.userinstructiontype;
          end;
        else
          lvuserinstructiontypeid := null;
        end if;
        -- get customer id
        errormsg := ' customer ' || x.customernumber;
        select c.customer_id
        into   lvcustomerid
        from   customer c
        where  c.customernumber = x.customernumber;
        begin
          -- insert into customeruserinstructions
          insert into customeruserinstruction
            (customeruserinstruction_id, customer_id, dateactive, dateinactive, systemuser_id,
             timestamp, enddateautomsg, userinstructiontype_id)
          values
            (seq_customeruserinstruction.nextval, lvcustomerid, x.dateactive, x.dateinactive,
             pack_import.lvnsystemuserid, sysdate,
             nvl(x.enddateautomsg, to_date('31-12-2099', 'dd-mm-yyyy')), lvuserinstructiontypeid)
          returning customeruserinstruction_id into lvcustomeruserinstructionid;
        end;
        --insert into customeruserinstruction_desc
        insert into customeruserinstruction_desc
          (customeruserinstruction_id, language_id, instruction, systemuser_id, timestamp)
        values
          (lvcustomeruserinstructionid, x.language_id, x.instruction, pack_import.lvnsystemuserid,
           sysdate);
        --upd_userinstructionperscreen
        upd_userinstructionperscreen(lvcustomeruserinstructionid, x.dialog_id);
        --update line as being imported
        update i_customeruserinstruction cu set cu.imported_yn = 'Y' where cu.rowid = x.rowid;
        lvcounter := lvcounter + 1;
      exception
        when dup_val_on_index then
          null;
        when no_data_found then
          begin
            errormsg := errormsg || ' not found.';
            pack_import.write_log('cfbimport_custuserinstruction ' || errormsg, 3);
          end;
      end;
    end loop;
    commit;
    pack_import.write_log(lvcounter || ' customer user instructions imported.');
  exception
    when others then
      begin
        rollback;
        errormsg := 'cfbimport_custuserinstruction: Failed to import.';
        pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_custuserinstruction;
  procedure cfbimportcustomersurvey is
    lvcustomerid      customer.customer_id%type;
    lvsurveyid        surveytype.surveytype_id%type;
    lvcontactpersonid contactperson.contactperson_id%type;
    lvbusinessunitid  businessunit.businessunit_id%type;
    lvplantid         plant.plant_id%type;
    lvemployeeid      employee.employee_id%type;
    lvcounter         number;
  begin
    lvcounter := 0;
    for x in (select i.customernumber, i.surveytypecode, i.contactpersonnumber, i.employeenumber,
                     i.surveyinterval, i.nextsurveydate
              from   i_customersurvey i) loop
      begin
        errormsg := ' customer ' || x.customernumber;
        select c.customer_id, c.defaultbusinessunit_id
        into   lvcustomerid, lvbusinessunitid
        from   customer c
        where  c.customernumber = x.customernumber;
        errormsg := ' surveytype ' || x.surveytypecode;
        select s.surveytype_id into lvsurveyid from surveytype s where s.code = x.surveytypecode;
        if x.contactpersonnumber is not null then
          begin
            select cp.contactperson_id
            into   lvcontactpersonid
            from   contactperson cp
            where  cp.customer_id = lvcustomerid
            and    cp.contactpersonnumber = x.contactpersonnumber;
          exception
            when no_data_found then
              begin
                lvcontactpersonid := null;
              end;
          end;
        end if;
        if x.contactpersonnumber is not null then
          begin
            select cp.contactperson_id
            into   lvcontactpersonid
            from   contactperson cp
            where  cp.customer_id = lvcustomerid
            and    cp.contactpersonnumber = x.contactpersonnumber;
          exception
            when no_data_found then
              begin
                lvcontactpersonid := null;
              end;
          end;
        end if;
        select b.plant_id
        into   lvplantid
        from   businessunit b
        where  b.businessunit_id = lvbusinessunitid;
        if x.employeenumber is not null then
          pack_import.cfbgetcreate_employee(lvplantid, lvemployeeid, x.employeenumber,
                                            to_char(x.employeenumber),
                                            nvl(substr(to_char(x.employeenumber), 1, 10), '-'),
                                            trunc(sysdate), null, null, null, null, null);
        end if;
        begin
          -- insert into customeruserinstructions
          insert into customersurveytype
            (customersurveytype_id, customer_id, surveytype_id, contactperson_id, employee_id,
             surveyinterval, nextsurveydate, systemuser_id, timestamp, lastsurveydate)
          values
            (seq_customersurveytype.nextval, lvcustomerid, lvsurveyid, lvcontactpersonid,
             lvemployeeid, x.surveyinterval, x.nextsurveydate, pack_import.lvnsystemuserid, sysdate,
             to_date('31-12-2099', 'dd-mm-yyyy'));
          lvcounter := lvcounter + 1;
        exception
          when dup_val_on_index then
            null;
        end;
      exception
        when no_data_found then
          begin
            errormsg := errormsg || ' not found.';
            pack_import.write_log('cfbimportcustomersurvey ' || errormsg, 3);
          end;
      end;
    end loop;
    commit;
    if lvcounter > 0 then
      pack_import.write_log(lvcounter || ' customer surveys imported.');
    end if;
  exception
    when others then
      begin
        rollback;
        errormsg := 'cfbimportcustomersurvey: Failed to import.';
        pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimportcustomersurvey;
  procedure import_customergarmentcharges is
    lv_countrows number := 0;
  begin
    --import_customergarmentcharges
    insert into customergarmentcharges
      (customer_id, defaultbm1rentcpwmax, rentcalcmethodpositivemove, rentcalcmethodnegativemove,
       systemuser_id, timestamp)
      select c.customer_id, nvl(igc.defaultbm1rentcpwmax, 0), nvl(igc.rentcalcmethodpositivemove, 0),
             nvl(igc.rentcalcmethodnegativemove, 0), pack_import.lvnsystemuserid, sysdate
      from   i_customergarmentcharges igc
      join   customer c
      on     c.customernumber = igc.customernumber
      where  not exists
       (select 1 from customergarmentcharges cg where cg.customer_id = c.customer_id);
    lv_countrows := sql%rowcount;
    if lv_countrows > 0 then
      begin
        commit;
        pack_import.write_log('Customers garment charges ' || to_char(lv_countrows) ||
                              ' records imported');
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('Error import customergarmentcharges.' || substr(sqlerrm, 1, 512), 3);
      end;
  end import_customergarmentcharges;
end pack_import_customer;
/
create or replace package pack_import_deliverystandards is
  -- Author  : PVD
  -- Created : 13-jun-2003 16:00:00
  -- Version : 1.0
  -- Purpose : Conversion of deliverystandards into ABSSolute DB.
  procedure cfimport_temporarydeliverystop;
  procedure cfbimport_productlistperdist;
end pack_import_deliverystandards;
/
create or replace package body pack_import_deliverystandards is
  lvnerrormsg            varchar2(256);
  lvntransportarticle_id transportarticle.transportarticle_id%type;
  lvnreasoncode_id       reasoncode.reasoncode_id%type;
  procedure cfbimport_standdeliveryamount(fpnstandarddeliveryline_id in standarddeliveryline.standarddeliveryline_id%type,
                                          fpnday_id                  in day.day_id%type,
                                          fpnamount                  in standarddeliveryamount.amount%type) is
  begin
    -- adding or update standard delivery amount values.
    pack_import.cfbstorecreate_stddelamount(fpnstandarddeliveryline_id,
                                            --fpnstddeliveryhistory_id,
                                            fpnday_id,
                                            --fpnday_id,
                                            fpnamount);
  end cfbimport_standdeliveryamount;
  procedure cfimport_temporarydeliverystop is
    lcounter                      number := 0;
    fpnseasontype_id              seasontype.seasontype_id%type;
    fpnseason_id                  season.season_id%type := null;
    fpndeliveryscheme_id          deliveryscheme.deliveryscheme_id%type;
    fpnstandarddelivery_id        standarddelivery.standarddelivery_id%type;
    fpnstandarddeliveryline_id    standarddeliveryline.standarddeliveryline_id%type;
    fpndistributionpoint_id       distributionpoint.distributionpoint_id%type;
    fpnprodlistperdistribpoint_id productlistperdistribpoint.productlistperdistribpoint_id%type;
  begin
    for x in (select c.customer_id, d.department_id, i.consumptionpointnumber, z.product_id,
                     s.sizedefinition_id, f.finishingmethod_id, i.seasontypecode, i.seasoncode,
                     i.dateactive, i.dateinactive, i.deliveryschemecode,
                     nvl(i.tempstopstartyear, 0) tempstopstartyear,
                     nvl(i.tempstopstartyearweek, 0) tempstopstartyearweek,
                     nvl(i.tempstopendyear, 0) tempstopendyear,
                     nvl(i.tempstopendyearweek, 0) tempstopendyearweek,
                     nvl(i.tempstopyearrent, 'N') tempstopyearrent,
                     nvl(i.tempstopstartweek, 0) tempstopstartweek,
                     nvl(i.tempstopendweek, 0) tempstopendweek,
                     nvl(i.tempstopreturnweek, 0) tempstopreturnweek,
                     nvl(i.tempstopweekrent, 'N') tempstopweekrent, i.startdate, i.enddate,
                     c.customernumber, d.departmentnumber,
                     nvl(i.tempstoprentfordate, 'N') tempstoprentfordate, i.productcode, i.sizecode,
                     i.finishingmethodcode
              from   i_temporarydeliverystop i, customer c, department d, product z, sizedefinition s,
                     finishingmethod f
              where  i.customernumber = c.customernumber
              and    i.departmentnumber = d.departmentnumber
              and    c.customer_id = d.customer_id
              and    z.code = trim(i.productcode)
              and    s.code = trim(i.sizecode)
              and    f.code = trim(i.finishingmethodcode)) loop
      begin
        lvnerrormsg := ' seasoncode ' || x.seasoncode;
        if trim(x.seasoncode) is not null then
          begin
            --season type.
            select seasontype_id
            into   fpnseasontype_id
            from   seasontype
            where  code = trim(x.seasontypecode);
            --adding season
            select season_id
            into   fpnseason_id
            from   season
            where  code = trim(x.seasoncode)
            and    fpnseasontype_id = seasontype_id;
          exception
            when others then
              begin
                fpnseason_id     := null;
                fpnseasontype_id := null;
              end; -- no problem just no seasons used.
          end;
        else
          fpnseason_id     := null;
          fpnseasontype_id := null;
        end if;
        -- determine fpndeliveryscheme_id
        lvnerrormsg := ' deliveryschemecode : ' || x.deliveryschemecode;
        select d.deliveryscheme_id
        into   fpndeliveryscheme_id
        from   deliveryscheme d
        where  d.code = trim(x.deliveryschemecode);
        -- determine distributionpoint
        lvnerrormsg := ' distributionpoint for cust/deptm ' || x.customernumber || '/' ||
                       x.departmentnumber || ' consumptionpoint ' || x.consumptionpointnumber;
        select p.distributionpoint_id
        into   fpndistributionpoint_id
        from   distributionpoint p
        where  p.distributionpointnumber = x.consumptionpointnumber
        and    p.department_id = x.department_id;
        -- determine productlistperdistribpoint
        lvnerrormsg := ' productlistperdistribpoint For cust/deptm ' || x.customernumber || '/' ||
                       x.departmentnumber || ' consumptionpoint ' || x.consumptionpointnumber ||
                       ' product ' || x.productcode || ' size ' || x.sizecode ||
                       ' finishingmethod ' || x.finishingmethodcode;
        select l.productlistperdistribpoint_id
        into   fpnprodlistperdistribpoint_id
        from   productlistperdistribpoint l
        where  l.distributionpoint_id = fpndistributionpoint_id
        and    l.product_id = x.product_id
        and    l.sizedefinition_id = x.sizedefinition_id
        and    l.finishingmethod_id = x.finishingmethod_id;
        -- standard delivery
        lvnerrormsg := ' standarddelivery ';
        select min(s.standarddelivery_id)
        into   fpnstandarddelivery_id
        from   standarddelivery s
        where  s.distributionpoint_id = fpndistributionpoint_id;
        -- standard delivery line.
        lvnerrormsg := ' standarddeliveryline cust/deptm ' || x.customernumber || '/' ||
                       x.departmentnumber || ' consumptionpoint ' || x.consumptionpointnumber;
        if fpnseason_id is not null then
          select min(l.standarddeliveryline_id)
          into   fpnstandarddeliveryline_id
          from   standarddeliveryline l
          where  l.standarddelivery_id = fpnstandarddelivery_id
          and    l.productlistperdistribpoint_id = fpnprodlistperdistribpoint_id
          and    l.dateactive <= x.dateactive
          and    l.dateinactive >= x.dateinactive
          and    (l.deliveryscheme_id = fpndeliveryscheme_id or l.deliveryscheme_id is null)
          and    l.season_id = fpnseason_id;
          if fpnstandarddeliveryline_id is null then
            raise no_data_found;
          end if;
        else
          select min(l.standarddeliveryline_id)
          into   fpnstandarddeliveryline_id
          from   standarddeliveryline l
          where  l.standarddelivery_id = fpnstandarddelivery_id
          and    l.productlistperdistribpoint_id = fpnprodlistperdistribpoint_id
          and    l.dateactive <= x.dateactive
          and    l.dateinactive >= x.dateinactive
          and    (l.deliveryscheme_id = fpndeliveryscheme_id or l.deliveryscheme_id is null)
          and    l.season_id is null;
          if fpnstandarddeliveryline_id is null then
            raise no_data_found;
          end if;
        end if;
        -- insert into temporarydeliverystop
        lvnerrormsg := ' insert into temporarydeliverystop ';
        insert into temporarydeliverystop
          (temporarydeliverystop_id, standarddeliveryline_id, temporarystopstartweek,
           temporarystopendweek, tempstoprentforweek, tempstoprentforyearweek,
           tempstopstartweekforyear, tempstopendweekforyear, temporarystopstartyear,
           temporarystopendyear, yearlystopreturnweek, systemuser_id, timestamp, startdate, enddate,
           tempstoprentfordate)
        values
          (seq_temporarydeliverystop.nextval, fpnstandarddeliveryline_id, x.tempstopstartweek,
           x.tempstopendweek, x.tempstopweekrent, x.tempstopyearrent, x.tempstopstartyearweek,
           x.tempstopendyearweek, x.tempstopstartyear, x.tempstopendyear, x.tempstopreturnweek,
           pack_import.lvnsystemuserid, sysdate, x.startdate, x.enddate, x.tempstoprentfordate);
        -- counter
        lcounter := lcounter + 1;
      exception
        when dup_val_on_index then
            null;
        when no_data_found then
          begin
            lvnerrormsg := 'cfimport_temporarydeliverystop: no data found for ' || lvnerrormsg;
            pack_import.write_log(lvnerrormsg, 3);
          end;
        when others then
          begin
            lvnerrormsg := 'Error others cfimport_temporarydeliverystop. For cust/deptm ' ||
                           x.customernumber || '/' || x.departmentnumber || ' consumptionpoint ' ||
                           x.consumptionpointnumber || ' product ' || x.productcode || ' size ' ||
                           x.sizecode || ' finishingmethod ' || x.finishingmethodcode || ' ';
            pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
          end;
      end;
    end loop;
    commit;
    if lcounter > 0 then
      begin
        pack_import.write_log(lcounter || ' temporarydeliverystops added to the database.');
      end;
    end if;
  end cfimport_temporarydeliverystop;
  procedure cfbimport_normstockamount(fpnnormstocklevel_id in normstockamount.productlistperdistribpoint_id%type,
                                      fpnday_id            in day.day_id%type,
                                      fpnamount            in normstockamount.amount%type,
                                      fpncustomerid        in customer.customer_id%type,
                                      fpndistributionpid   in distributionpoint.distributionpoint_id%type,
                                      fpncountsequence     in stockcountscheduledist.countsequence%type) is
    lvnstockcountscheduleid stockcountschedule.stockcountschedule_id%type;
    lv_counter              number;
  begin
    -- adding normstock amount values
    pack_import.cfbstorecreate_normstockamount(fpnnormstocklevel_id,
                                               --fpnnormstocklevel_id,
                                               fpnday_id,
                                               --fpnday_id,
                                               fpnamount);
    --check if new tables are used, was already converted in pack_import_department.import_stockcountsequence?
    select count(1) into lv_counter from i_stockcountschedule;
    if lv_counter > 0 then
      begin
        --yes should have been converted already lets check
        select count(1)
        into   lv_counter
        from   stockcountschedule sc
        join   stockcountscheduledist scd
        on     scd.stockcountschedule_id = sc.stockcountschedule_id
        join   stockcountscheduleday scda
        on     scda.stockcountschedule_id = sc.stockcountschedule_id
        where  sc.customer_id = fpncustomerid
        and    scd.distributionpoint_id = fpndistributionpid
        and    scda.day_id = fpnday_id;
        if lv_counter = 0 then
          begin
            pack_import.write_log('No stockcountschedule/dist/day for customer id ' ||
                                  to_char(fpncustomerid) || ' distributionp id ' ||
                                  to_char(fpndistributionpid) || ' day ' || to_char(fpnday_id), 3);
          end;
        end if;
      end;
    else
      begin
        --not converted we create it
        select min(d.stockcountschedule_id)
        into   lvnstockcountscheduleid
        from   stockcountscheduledist d
        where  d.distributionpoint_id = fpndistributionpid;
        if lvnstockcountscheduleid is null then
          begin
            select min(s.stockcountschedule_id)
            into   lvnstockcountscheduleid
            from   stockcountschedule s
            where  s.customer_id = fpncustomerid;
            if lvnstockcountscheduleid is null then
              begin
                insert into stockcountschedule
                  (stockcountschedule_id, customer_id, code, description, packoncountday,
                   systemuser_id, timestamp)
                values
                  (seq_stockcountschedule.nextval, fpncustomerid, '-', 'conversion added', 'N',
                   pack_import.lvnsystemuserid, sysdate)
                returning stockcountschedule_id into lvnstockcountscheduleid;
              end;
            end if;
            insert into stockcountscheduledist
              (stockcountscheduledist_id, stockcountschedule_id, distributionpoint_id,
               countsequence, systemuser_id, timestamp)
            values
              (seq_stockcountscheduledist.nextval, lvnstockcountscheduleid, fpndistributionpid,
               coalesce(fpncountsequence,
                         (select max(countsequence) + 1
                           from   stockcountscheduledist z
                           where  z.stockcountschedule_id = lvnstockcountscheduleid), 1),
               pack_import.lvnsystemuserid, sysdate);
          exception
            when others then
              begin
                pack_import.write_log('Error adding stockcountscheduledist for customer id ' ||
                                      to_char(fpncustomerid) || ' distributionp id ' ||
                                      to_char(fpndistributionpid) || ' day ' || to_char(fpnday_id) ||
                                      substr(sqlerrm, 1, 512), 3);
              end;
          end;
        end if;
        begin
          insert into stockcountscheduleday
            (stockcountschedule_id, day_id, systemuser_id, timestamp, deliveryday_id)
          values
            (lvnstockcountscheduleid, fpnday_id, pack_import.lvnsystemuserid, sysdate, fpnday_id);
        exception
          when dup_val_on_index then
            null;
          when others then
            begin
              pack_import.write_log('Error adding stockcountscheduleday for customer id ' ||
                                    to_char(fpncustomerid) || ' distributionp id ' ||
                                    to_char(fpndistributionpid) || ' day ' || to_char(fpnday_id) ||
                                    substr(sqlerrm, 1, 512), 3);
            end;
        end;
      end;
    end if;
  end cfbimport_normstockamount;
  procedure cfbinsertcustomerdeldayscheme(ncustomerid        customer.customer_id%type,
                                          ndayid             day.day_id%type,
                                          ndeliveryschemeid  deliveryscheme.deliveryscheme_id%type,
                                          ntypeofmerchandise product.typeofmerchandise%type) is
  begin
    -- add customer deliveryscheme. No problem if its already there.
    begin
      insert into customerdeliveryscheme
        (customer_id, deliveryscheme_id, day_id, systemuser_id, timestamp)
      values
        (ncustomerid, ndeliveryschemeid, ndayid, pack_import.lvnsystemuserid, sysdate);
    exception
      when others then
        null;
    end;
    -- add deliverydays. No problem if its already there.
    pack_import.add_check_customerdeliveryday(ncustomerid, ndayid, 'D', ntypeofmerchandise);
  end cfbinsertcustomerdeldayscheme;
  procedure cfbimport_productlistperdist is
    fpnseasontype_id              seasontype.seasontype_id%type;
    fpnseason_id                  season.season_id%type := null;
    fpndeliveryscheme_id          deliveryscheme.deliveryscheme_id%type;
    fpncountsequence              productlistperdistribpoint.countsequence%type;
    fpnprodlistperdistribpoint_id productlistperdistribpoint.productlistperdistribpoint_id%type;
    fpnproductlistpercustomer_id  productlistpercustomer.productlistpercustomer_id%type;
    fpnstandarddelivery_id        standarddelivery.standarddelivery_id%type;
    fpnstandarddeliveryline_id    standarddeliveryline.standarddeliveryline_id%type;
    fpnrentalqtyadjustment_id     rentalqtyadjustment.rentalqtyadjustment_id%type;
    fpndistributionpoint_id       distributionpoint.distributionpoint_id%type;
    fpncostcenter_id              costcenter.costcenter_id%type;
    fpndeliverypoint_id           deliverypoint.deliverypoint_id%type;
    fpscorrectshortages           standarddelivery.correctshortages%type;
    fpscorrectoverdeliveries      standarddelivery.correctoverdeliveries%type;
    lcountplpd                    number := 0;
    lcountstddel                  number := 0;
    lcountstddelline              number := 0;
    lvnrentalquantity             rentalqtyadjustment.quantity%type;
  begin
    pack_import.write_log('Start import productlistperdistributionpoint: ' ||
                          to_char(sysdate, 'dd-mm-yyyy hh24:mi:ss'));
    begin
      -- Add into itemporarydeliverystop the records from i_deliverystandards
      insert into i_temporarydeliverystop
        (customernumber, departmentnumber, consumptionpointnumber, productcode, sizecode,
         finishingmethodcode, seasontypecode, seasoncode, dateactive, dateinactive,
         deliveryschemecode, tempstopstartyear, tempstopstartyearweek, tempstopendyear,
         tempstopendyearweek, tempstopyearrent, tempstopstartweek, tempstopendweek,
         tempstopreturnweek, tempstopweekrent, startdate, enddate)
        select x.customernumber, x.departmentnumber, x.consumptionpointnumber, x.productcode,
               x.sizecode, x.finishingmethodcode, x.seasontypecode, x.seasoncode, x.dateactive,
               x.dateinactive, x.deliveryschemecode, to_char(x.deliverstopstartdate, 'YYYY'),
               to_char(x.deliverstopstartdate, 'IW'), to_char(x.deliverstopenddate, 'YYYY'),
               to_char(x.deliverstopenddate, 'IW'), 'N', x.deliverystopstartweek,
               x.deliverystopendweek, x.deliverystopendweek, 'N', x.deliverstopstartdate,
               x.deliverstopenddate
        from   i_deliverystandards x
        where  ((x.deliverstopstartdate is not null and x.deliverstopenddate is not null and
               x.deliverstopstartdate <= x.deliverstopenddate) or
               (x.deliverystopstartweek between 1 and 54 and x.deliverystopendweek between 1 and 54 and
               x.deliverystopstartweek <= x.deliverystopendweek))
        and    not exists (select st.customernumber
                from   i_temporarydeliverystop st
                where  st.customernumber = x.customernumber
                and    st.departmentnumber = x.departmentnumber
                and    st.consumptionpointnumber = x.consumptionpointnumber
                and    st.productcode = x.productcode
                and    st.sizecode = x.sizecode
                and    st.finishingmethodcode = x.finishingmethodcode
                and    st.dateactive = x.dateactive
                and    st.deliveryschemecode = x.deliveryschemecode);
      commit;
    exception
      when others then
        begin
          rollback;
          lvnerrormsg := 'CFbImport_ProductListPerDist: Fail to fill i_temporarydeliverystop using i_deliverystandards!';
          pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
        end;
    end;
    begin
      --making count sequence NULL when it is not really being used.
      select count(1)
      into   fpncountsequence
      from   i_deliverystandards i
      where  i.countsequencenumber <> 1;
      if (fpncountsequence = 0) then
        update i_deliverystandards i set i.countsequencenumber = null;
        commit;
      end if;
    exception
      when others then
        begin
          rollback;
          lvnerrormsg := 'CFbImport_ProductListPerDist: error resetting the count sequence!';
          pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
        end;
    end;
    -- Import into productlistperdistributionpoint
    for x in (select /*+FULL(i)*/
               c.customer_id, d.department_id, z.product_id, s.sizedefinition_id, i.dateactive,
               i.dateinactive, i.consumptionpointnumber, i.seasontypecode, i.seasoncode,
               i.orderingmethod, i.deliveryschemecode, i.countsequencenumber, i.quantity_mo,
               i.quantity_tu, i.quantity_we, i.quantity_th, i.quantity_fr, i.quantity_sa,
               i.quantity_su, i.normstocklevel_mo, i.normstocklevel_tu, i.normstocklevel_we,
               i.normstocklevel_th, i.normstocklevel_fr, i.normstocklevel_sa, i.normstocklevel_su,
               i.holidayuseagefactor, nvl(i.rentalquantity, 0) rentalquantity, i.circulatinginventory,
               replace(i.remarkforpackinginstructions, '|', chr(10)) remarkforpackinginstructions,
               i.location, f.finishingmethod_id, i.deliverystopstartweek, i.deliverystopendweek,
               z.typeofmerchandise, c.customernumber, d.departmentnumber, z.code productcode,
               i.renewalstartdate, i.renewalenddate, i.qtyfreeofcharge, i.contractperiod,
               i.prolongationperiod, i.canceladvanceperiod, i.freeqtyfrequency, i.countsequence_scs,
               i.deliverypercentage, i.billingpercentage
              from   i_deliverystandards i, customer c, department d, product z, sizedefinition s,
                     finishingmethod f
              where  i.customernumber = c.customernumber
              and    i.departmentnumber = d.departmentnumber
              and    c.customer_id = d.customer_id
              and    z.code = rtrim(ltrim(i.productcode))
              and    s.code = rtrim(ltrim(i.sizecode))
              and    f.code = rtrim(ltrim(i.finishingmethodcode))
              order  by i.customernumber, i.departmentnumber, i.consumptionpointnumber,
                        i.countsequencenumber) loop
      begin
        --Import loop start
        if trim(x.seasoncode) is not null then
          begin
            --season type.
            pack_import.cfbcreate_seasontype(fpnseasontype_id,
                                             trim(nvl(x.seasontypecode, x.seasoncode)));
            --season
            pack_import.cfbcreate_season(fpnseason_id, fpnseasontype_id, trim(x.seasoncode));
          end;
        else
          fpnseason_id     := null;
          fpnseasontype_id := null;
        end if;
        if x.deliveryschemecode is null then
         begin
              select min(cs.deliveryscheme_id)
                 into   fpndeliveryscheme_id
                 from   customerdeliveryscheme cs join deliveryscheme ds
                 on      cs.deliveryscheme_id = ds.deliveryscheme_id
                 where    cs.customer_id = x.customer_id;
          end;
    else
          begin
            -- determine fpndeliveryscheme_id
            select d.deliveryscheme_id
            into   fpndeliveryscheme_id
            from   deliveryscheme d
            where  d.code = x.deliveryschemecode;
          exception
            when no_data_found then
              begin
                -- if not found create it.
                pack_import.cfbcreate_deliveryscheme(fpndeliveryscheme_id, x.deliveryschemecode,
                                                     'N', null, null);
              end;
          end;
        end if;
        begin
          begin
            --determine costcenter.
            select min(costcenter.costcenter_id)
            into   fpncostcenter_id
            from   costcenter
            where  costcenter.customer_id = x.customer_id;
            if fpncostcenter_id is null then
              pack_import.cfbcreate_costcenter(fpncostcenter_id,
                                               --fpncostcenter_id,
                                               '-',
                                               --fpscode,
                                               '-',
                                               --fpsdescription,
                                               x.customer_id,
                                               --fpncustomer_id,
                                               null,
                                               --fpninvoiceaddress_id,
                                               null); --fpncontactperson_id);
            end if;
          end;
          begin
            -- determine deliverypoint.
            select min(deliverypoint_id)
            into   fpndeliverypoint_id
            from   deliverypoint
            where  deliverypoint.customer_id = x.customer_id;
            if fpndeliverypoint_id is null then
              pack_import.cfbcreate_deliverypoint(fpndeliverypoint_id,
                                                  --fpndeliverypoint_id,
                                                  x.customer_id,
                                                  --fpncustomer_id,
                                                  '1',
                                                  --fpscode,
                                                  '-',
                                                  --fpsdescription,
                                                  null,
                                                  --fpndeliveryaddressid,
                                                  null); --fpssortaddress
            end if;
          end;
          begin
            -- determine distributionpoint
            select min(p.distributionpoint_id)
            into   fpndistributionpoint_id
            from   distributionpoint p
            where  p.distributionpointnumber = x.consumptionpointnumber
            and    p.department_id = x.department_id;
            if fpndistributionpoint_id is null then
              pack_import.cfbcreate_distributionpoint(fpndistributionpoint_id,
                                                      --fpndistributionpoint_id,
                                                      x.consumptionpointnumber,
                                                      --fpndistributionpointnumber,
                                                      '-',
                                                      --fpsdescription,
                                                      null,
                                                      --fpsremarkonpackingnote,
                                                      null,
                                                      --fpsremarkondeliverynote,
                                                      to_date('31-12-2099', 'DD-MM-YYYY'),
                                                      --fpdtpackremarkenddate,
                                                      to_date('31-12-2099', 'DD-MM-YYYY'),
                                                      --fpdtdeliverremarkenddate,
                                                      'Y',
                                                      --fpsactive,
                                                      x.department_id,
                                                      --fpndepartment_id,
                                                      fpndeliverypoint_id,
                                                      --fpndeliverypoint_id,
                                                      fpncostcenter_id,
                                                      --fpncostcenter_id,
                                                      null, null, null);
              --fpslegacydistributionpnumber,
            end if;
          end;
          lvnerrormsg := lvnerrormsg || to_char(fpndistributionpoint_id) || ' ';
          if x.countsequencenumber is not null then
            fpncountsequence := x.countsequencenumber;
          else
            begin
              --determine the count sequence
              select nvl(max(countsequence), 0) + 1
              into   fpncountsequence
              from   productlistperdistribpoint
              where  distributionpoint_id = fpndistributionpoint_id;
            end;
          end if;
          begin
            -- determine productlistperdistribpoint
            select min(l.productlistperdistribpoint_id)
            into   fpnprodlistperdistribpoint_id
            from   productlistperdistribpoint l
            where  l.distributionpoint_id = fpndistributionpoint_id
            and    l.product_id = x.product_id
            and    l.sizedefinition_id = x.sizedefinition_id
            and    l.finishingmethod_id = x.finishingmethod_id;
            if fpnprodlistperdistribpoint_id is null then
              pack_import.cfbcreate_plpdistribpoint(fpnprodlistperdistribpoint_id,
                                                    --fpnprodlistperdistribpoint_id,
                                                    fpndistributionpoint_id,
                                                    --fpndistributionpoint_id,
                                                    x.product_id,
                                                    --fpnproduct_id,
                                                    x.sizedefinition_id,
                                                    --fpnsizedefinition_id,
                                                    x.finishingmethod_id,
                                                    --fpnfinishingmethod_id,
                                                    nvl(fpncountsequence, 1),
                                                    --fpncountsequence,
                                                    x.orderingmethod,
                                                    --fpnorderingmethod;1= Count Stock 2= Order
                                                    nvl(x.holidayuseagefactor, 100),
                                                    x.contractperiod, x.prolongationperiod,
                                                    x.canceladvanceperiod, x.deliverypercentage,
                                                    x.billingpercentage);
              --fpnholidayusagefactor,
              lcountplpd := lcountplpd + 1;
            end if;
          end;
          lvnerrormsg := to_char(x.customer_id) || ' ' || to_char(x.department_id) || ' ' ||
                         to_char(fpnprodlistperdistribpoint_id) || ' ';
          -- determine productlistpercustomer 1st with size then with size *.
          select max(l.productlistpercustomer_id)
          into   fpnproductlistpercustomer_id
          from   productlistpercustomer l
          where  l.customer_id = x.customer_id
          and    l.product_id = x.product_id
          and    l.finishingmethod_id = x.finishingmethod_id
          and    l.sizedefinition_id = x.sizedefinition_id
          and    l.dateactive <= x.dateactive
          and    l.dateinactive >= x.dateinactive;
          if fpnproductlistpercustomer_id is null then
            begin
              select l.productlistpercustomer_id
              into   fpnproductlistpercustomer_id
              from   productlistpercustomer l
              where  l.customer_id = x.customer_id
              and    l.product_id = x.product_id
              and    l.finishingmethod_id = x.finishingmethod_id
              and    l.sizedefinition_id =
                     (select s.sizedefinition_id from sizedefinition s where s.code = '*')
              and    l.dateactive <= x.dateactive
              and    l.dateinactive >= x.dateinactive;
            exception
              when others then
                begin
                  fpnproductlistpercustomer_id := null;
                  pack_import.write_log('Error consumptionpoint conversion, no active plpc found for cust/custID:' ||
                                        x.customernumber || '/' || to_char(x.customer_id) ||
                                        ' dep/depID:' || x.departmentnumber || '/' ||
                                        to_char(x.department_id) || ' ' || ' product/productID ' ||
                                        x.productcode || '/' || to_char(x.product_id) ||
                                        ' plpc not found', 2);
                end;
            end;
          end if;
          if fpnproductlistpercustomer_id > 0 then
            begin
              --update plpc season type
              update productlistpercustomer l
              set    l.seasontype_id = fpnseasontype_id
              where  l.seasontype_id is null
              and    l.productlistpercustomer_id = fpnproductlistpercustomer_id;
              begin
                -- determine setting shortages and overdeliveries.
                select i.correctshortages, i.correctoverdeliveries
                into   fpscorrectshortages, fpscorrectoverdeliveries
                from   i_consumptionpoint i, customer c, department d
                where  i.customernumber = c.customernumber
                and    i.departmentnumber = d.departmentnumber
                and    c.customer_id = d.customer_id
                and    c.customer_id = x.customer_id
                and    d.department_id = x.department_id;
              exception
                when others then
                  fpscorrectshortages      := 'N';
                  fpscorrectoverdeliveries := 'N';
              end;
              begin
                -- standard delivery.
                select min(s.standarddelivery_id)
                into   fpnstandarddelivery_id
                from   standarddelivery s
                where  s.distributionpoint_id = fpndistributionpoint_id
                and    s.sequencenumber = 1;
                if fpnstandarddelivery_id is null then
                  pack_import.cfbcreate_standarddelivery(fpnstandarddelivery_id,
                                                         --fpnstandarddelivery_id,
                                                         1,
                                                         --fpnsequencenumber,
                                                         'N',
                                                         --fpsdeliversterile,
                                                         null,
                                                         --fpnplantdepartment_id,
                                                         'N',
                                                         --fpscleanreturn,
                                                         lvntransportarticle_id,
                                                         --fpntransportarticle_id,
                                                         'N',
                                                         --fpsgeneratezerolines,
                                                         1,
                                                         --fpnnumberoftransportarticles,
                                                         fpndistributionpoint_id,
                                                         --fpndistributionpoint_id,
                                                         x.dateactive,
                                                         --fpdtlastpackingdate,
                                                         fpscorrectshortages,
                                                         --fpscorrectshortages,
                                                         fpscorrectoverdeliveries,
                                                         --fpscorrectoverdeliveries,
                                                         null);
                  --fpstruckloadposition,
                  lcountstddel := lcountstddel + 1;
                end if;
              end;
              lvnerrormsg := lvnerrormsg || to_char(fpnstandarddelivery_id) || ' ';
              begin
                -- standard delivery line.
                if fpnseason_id is not null then
                  select min(l.standarddeliveryline_id)
                  into   fpnstandarddeliveryline_id
                  from   standarddeliveryline l
                  where  l.standarddelivery_id = fpnstandarddelivery_id
                  and    l.productlistperdistribpoint_id = fpnprodlistperdistribpoint_id
                  and    l.dateactive = x.dateactive
                  and    l.dateinactive = x.dateinactive
                  and    (l.deliveryscheme_id = fpndeliveryscheme_id or
                        l.deliveryscheme_id is null)
                  and    l.season_id = fpnseason_id;
                else
                  select min(l.standarddeliveryline_id)
                  into   fpnstandarddeliveryline_id
                  from   standarddeliveryline l
                  where  l.standarddelivery_id = fpnstandarddelivery_id
                  and    l.productlistperdistribpoint_id = fpnprodlistperdistribpoint_id
                  and    l.dateactive = x.dateactive
                  and    l.dateinactive = x.dateinactive
                  and    (l.deliveryscheme_id = fpndeliveryscheme_id or
                        l.deliveryscheme_id is null)
                  and    l.season_id is null;
                end if;
                if fpnstandarddeliveryline_id is not null then
                  -- update deliveryscheme when its null
                  update standarddeliveryline l
                  set    l.deliveryscheme_id = fpndeliveryscheme_id
                  where  l.deliveryscheme_id is null
                  and    l.standarddeliveryline_id = fpnstandarddeliveryline_id;
                  --
                end if;
                if fpnstandarddeliveryline_id is null then
                  -- insert standarddeliveryline.
                  pack_import.cfbcreate_standarddeliveryline(fpnstandarddeliveryline_id,
                                                             --fpnstandarddeliveryline_id,
                                                             fpnstandarddelivery_id,
                                                             --fpnstandarddelivery_id,
                                                             fpnprodlistperdistribpoint_id,
                                                             --fpnprodlistperdistribpoint_id,
                                                             x.location,
                                                             --fpslocation,
                                                             x.remarkforpackinginstructions,
                                                             --fpsremarkforpackinstructions,
                                                             fpnseason_id,
                                                             --fpnseason_id,
                                                             x.rentalquantity,
                                                             --fpnfixedrentquantity,
                                                             x.dateactive,
                                                             --fpdtdateactive,
                                                             x.dateinactive,
                                                             --fpdtdateinactive,
                                                             fpndeliveryscheme_id,
                                                             --fpndeliveryscheme_id,
                                                             fpnproductlistpercustomer_id,
                                                             --fpnproductlistpercustomer_id,
                                                             x.renewalstartdate, x.renewalenddate,
                                                             x.qtyfreeofcharge, x.freeqtyfrequency);
                  lcountstddelline := lcountstddelline + 1;
                end if;
                if x.renewalstartdate is not null and x.renewalenddate is not null then
                  -- update renewal if its null
                  update standarddeliveryline l
                  set    l.renewalstartdate = x.renewalstartdate,
                         l.renewalenddate = x.renewalenddate, l.renewal = 'Y'
                  where  (l.renewalstartdate is null or l.renewal = 'N')
                  and    l.standarddeliveryline_id = fpnstandarddeliveryline_id;
                  --
                end if;
              end;
              begin
                -- Entering quantities for days 1-7
                if x.quantity_mo >= 0 then
                  --mo quantity
                  cfbimport_standdeliveryamount(fpnstandarddeliveryline_id,
                                                --fpnstandarddeliveryline_id,
                                                1,
                                                --fpnday_id,
                                                x.quantity_mo); --fpnamount)
                  cfbinsertcustomerdeldayscheme(x.customer_id, 1, fpndeliveryscheme_id,
                                                x.typeofmerchandise);
                end if;
                if x.quantity_tu >= 0 then
                  --tu quantity
                  cfbimport_standdeliveryamount(fpnstandarddeliveryline_id,
                                                --fpnstandarddeliveryline_id,
                                                2,
                                                --fpnday_id,
                                                x.quantity_tu); --fpnamount)
                  cfbinsertcustomerdeldayscheme(x.customer_id, 2, fpndeliveryscheme_id,
                                                x.typeofmerchandise);
                end if;
                if x.quantity_we >= 0 then
                  --we quantity
                  cfbimport_standdeliveryamount(fpnstandarddeliveryline_id,
                                                --fpnstandarddeliveryline_id,
                                                3,
                                                --fpnday_id,
                                                x.quantity_we); --fpnamount)
                  cfbinsertcustomerdeldayscheme(x.customer_id, 3, fpndeliveryscheme_id,
                                                x.typeofmerchandise);
                end if;
                if x.quantity_th >= 0 then
                  --th quantity
                  cfbimport_standdeliveryamount(fpnstandarddeliveryline_id,
                                                --fpnstandarddeliveryline_id,
                                                4,
                                                --fpnday_id,
                                                x.quantity_th); --fpnamount)
                  cfbinsertcustomerdeldayscheme(x.customer_id, 4, fpndeliveryscheme_id,
                                                x.typeofmerchandise);
                end if;
                if x.quantity_fr >= 0 then
                  --fr quantity
                  cfbimport_standdeliveryamount(fpnstandarddeliveryline_id,
                                                --fpnstandarddeliveryline_id,
                                                5,
                                                --fpnday_id,
                                                x.quantity_fr); --fpnamount)
                  cfbinsertcustomerdeldayscheme(x.customer_id, 5, fpndeliveryscheme_id,
                                                x.typeofmerchandise);
                end if;
                if x.quantity_sa >= 0 then
                  --sa quantity
                  cfbimport_standdeliveryamount(fpnstandarddeliveryline_id,
                                                --fpnstandarddeliveryline_id,
                                                6,
                                                --fpnday_id,
                                                x.quantity_sa); --fpnamount)
                  cfbinsertcustomerdeldayscheme(x.customer_id, 6, fpndeliveryscheme_id,
                                                x.typeofmerchandise);
                end if;
                if x.quantity_su >= 0 then
                  --su quantity
                  cfbimport_standdeliveryamount(fpnstandarddeliveryline_id,
                                                --fpnstandarddeliveryline_id,
                                                7,
                                                --fpnday_id,
                                                x.quantity_su); --fpnamount)
                  cfbinsertcustomerdeldayscheme(x.customer_id, 7, fpndeliveryscheme_id,
                                                x.typeofmerchandise);
                end if;
                -- Entering normstocklevels for days 1-7
                if x.normstocklevel_mo >= 0 then
                  --mo normstocklevel
                  cfbimport_normstockamount(fpnprodlistperdistribpoint_id,
                                            --PRODUCTLISTPERDISTRIBPOINT_ID
                                            1,
                                            --fpnday_id,
                                            x.normstocklevel_mo, x.customer_id,
                                            fpndistributionpoint_id, x.countsequence_scs);
                end if;
                if x.normstocklevel_tu >= 0 then
                  --tu normstocklevel
                  cfbimport_normstockamount(fpnprodlistperdistribpoint_id,
                                            --PRODUCTLISTPERDISTRIBPOINT_ID
                                            2,
                                            --fpnday_id,
                                            x.normstocklevel_tu, x.customer_id,
                                            fpndistributionpoint_id, x.countsequence_scs);
                end if;
                if x.normstocklevel_we >= 0 then
                  --we normstocklevel
                  cfbimport_normstockamount(fpnprodlistperdistribpoint_id,
                                            --PRODUCTLISTPERDISTRIBPOINT_ID
                                            3,
                                            --fpnday_id,
                                            x.normstocklevel_we, x.customer_id,
                                            fpndistributionpoint_id, x.countsequence_scs);
                end if;
                if x.normstocklevel_th >= 0 then
                  --th normstocklevel
                  cfbimport_normstockamount(fpnprodlistperdistribpoint_id,
                                            --PRODUCTLISTPERDISTRIBPOINT_ID
                                            4,
                                            --fpnday_id,
                                            x.normstocklevel_th, x.customer_id,
                                            fpndistributionpoint_id, x.countsequence_scs);
                end if;
                if x.normstocklevel_fr >= 0 then
                  --fr normstocklevel
                  cfbimport_normstockamount(fpnprodlistperdistribpoint_id,
                                            --PRODUCTLISTPERDISTRIBPOINT_ID
                                            5,
                                            --fpnday_id,
                                            x.normstocklevel_fr, x.customer_id,
                                            fpndistributionpoint_id, x.countsequence_scs);
                end if;
                if x.normstocklevel_sa >= 0 then
                  --sa normstocklevel
                  cfbimport_normstockamount(fpnprodlistperdistribpoint_id,
                                            --PRODUCTLISTPERDISTRIBPOINT_ID
                                            6,
                                            --fpnday_id,
                                            x.normstocklevel_sa, x.customer_id,
                                            fpndistributionpoint_id, x.countsequence_scs);
                end if;
                if x.normstocklevel_su >= 0 then
                  --su normstocklevel
                  cfbimport_normstockamount(fpnprodlistperdistribpoint_id,
                                            --PRODUCTLISTPERDISTRIBPOINT_ID
                                            7,
                                            --fpnday_id,
                                            x.normstocklevel_su, x.customer_id,
                                            fpndistributionpoint_id, x.countsequence_scs);
                end if;
                --billingmethod=3 then circulatinginventory is filled
                --it can otherwise be filled with rentalquantity also for billingmethod=3
                if x.circulatinginventory is not null then
                  lvnrentalquantity := x.circulatinginventory;
                else
                  lvnrentalquantity := x.rentalquantity;
                end if;
                pack_import.cfbcreate_rentalqtyadjustment(fpnrentalqtyadjustment_id,
                                                          --fpnrentalqtyadjustment_id,
                                                          fpnprodlistperdistribpoint_id,
                                                          --fpnproductlistperdip_id,
                                                          null,
                                                          --fpsremark,
                                                          lvnrentalquantity,
                                                          --fpnquantity,
                                                          x.dateactive,
                                                          --fpdtadjustmentdate,
                                                          lvnreasoncode_id,
                                                          --fpnreasoncode_id,
                                                          null); --fpndeliveryvariation_id);
              exception
                when dup_val_on_index then
                  null; -- no problem already exists.
              end;
            end;
          end if; --          if fpnproductlistpercustomer_id is not null then begin
        end;
      exception
        when dup_val_on_index then
          lvnerrormsg := 'CFbImport_ProductListPerDist: during loop fail to import; ' ||
                         lvnerrormsg;
          pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
          lvnerrormsg := null;
      end;
    end loop; --import loop end.
    commit; --commit when it was succesfull.
    begin
      -- Fix to add packingdepartments by default.
      insert into packingdepartmentdefinition
        (productgroup_id, plant_id, plantdepartment_id, systemuser_id, timestamp,
         soilreceiveplantdepartment_id)
        select e.productgroup_id, e.plant_id, e.plantdepartment_id, pack_import.lvnsystemuserid,
               sysdate, null
        from   (select g.productgroup_id, d.plant_id, max(d.plantdepartment_id) plantdepartment_id
                 from   plantdepartment d
                 cross  join productgroup g
                 where  not exists (select 1
                         from   packingdepartmentdefinition p
                         where  p.productgroup_id = g.productgroup_id
                         and    p.plant_id = d.plant_id)
                 group  by g.productgroup_id, d.plant_id) e;
    exception
      when others then
        lvnerrormsg := 'CFbImport_ProductListPerDist: add packingdepartments by default. ';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
    end;
    commit; --commit when it was succesfull.
    cfimport_temporarydeliverystop;
    ---logging conversion
    if lcountplpd <> 0 then
      pack_import.write_log(lcountplpd || ' productlistperdistributionpoint records imported.');
    end if;
    if lcountstddel <> 0 then
      pack_import.write_log(lcountstddel || ' standarddelivery records imported.');
    end if;
    if lcountstddelline <> 0 then
      pack_import.write_log(lcountstddelline || ' standarddeliveryline records imported.');
    end if;
    pack_import.write_log('Stop import productlistperdistributionpoint: ' ||
                          to_char(sysdate, 'dd-mm-yyyy hh24:mi:ss'));
  exception
    when others then
      begin
        rollback;
        lvnerrormsg := 'CFbImport_ProductListPerDist: Fail to import; ' || lvnerrormsg;
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_productlistperdist;
begin
  --initialization
  select min(transportarticle_id) into lvntransportarticle_id from transportarticle;
  begin
    select reasoncode_id into lvnreasoncode_id from reasoncode where code = '-';
  exception
    when others then
      pack_import.cfbcreate_reasoncode(lvnreasoncode_id,
                                       --fpnreasoncode_id,
                                       '-',
                                       --fpscode,
                                       'N',
                                       --fpsinternetselectable,
                                       'Y',
                                       --fpsallowprepcharges,
                                       'Y',
                                       --fpsgarmentreason,
                                       'Y',
                                       --fpslinenreason,
                                       'N',
                                       --fpsexporttohandheld,
                                       0,
                                       --fpncancelinvoice,
                                       'N',
                                       --fpsaffectsnextinvoice,
                                       'N',
                                       --fpsaffectscurrentinvoice,
                                       0,
                                       --fpninvoiceadjustment,
                                       'N',
                                       --fpsfirstissue,
                                       0,
                                       --fpninventorytrigger,
                                       'Y',
                                       --fpschargeresidualvalue
                                       'N'
                                       --fpschargerestockingfee
                                       );
      pack_import.cfbcreate_reasoncode_desc(lvnreasoncode_id,
                                            --fpnreasoncode_id,
                                            '-');
      --fpsdescription,
      commit;
  end;
exception
  when others then
    begin
      lvnerrormsg := 'Initialization error.';
      pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
    end;
end pack_import_deliverystandards;
/
create or replace package pack_import_department is
  -- Author  : PVD
  -- Created : 11-jun-2003
  -- Version : 1.0
  -- Updated : 14-jan-2011 only create deliverypoint for department when its filled or none for customer
  -- Purpose : Conversion from departments and consumptionpoints into ABSSolute DB.
  --           14-dec-2018 ABS-73322 Extend Conversion with MBYO options ABS-76341
  --           22-Mar-2019 ABS-75876 Expand conversion tool with Compulsory Order Days
  --           13-Mar-2023 ABS-149315 I-tables: extend with ADRESSLINE 3 and 40 characters
  procedure cfbadd_missing_departments;
  procedure import_stockcountsequence;
  function cfbimport_departments(ncustomernumber customer.customernumber%type) return number;
  procedure convert_i_department;
  procedure convert_i_nobudgetdepartment;
  procedure imp_conspointbudgetprotection;
  procedure convert_i_consumptionpoints;
  procedure convert_costcentergroup(fp_customernumber in customer.customernumber%type default null);
  procedure convert_costcenter;
end pack_import_department;
/
create or replace package body pack_import_department is
  lvnerrormsg            varchar2(256);
  fpntransportarticle_id transportarticle.transportarticle_id%type;
  procedure cfbadd_missing_departments is
    counter number := 0;
  begin
    -- knoei recht breien.
    update i_wearer w
    set    w.departmentnumber = 1
    where  w.departmentnumber = 0
    or     w.departmentnumber is null;
    -- add missing departments 1.
    for x in (select c.customernumber, i.departmentnumber, max(c.usesbundles) usesbundles
              from   i_wearer i, customer c
              where  i.customernumber = c.customernumber
              and    not exists (select d.department_id
                      from   department d
                      where  d.customer_id = c.customer_id
                      and    d.departmentnumber = i.departmentnumber)
              and    not exists (select d.departmentnumber
                      from   i_department d
                      where  d.customernumber = c.customernumber
                      and    d.departmentnumber = i.departmentnumber)
              group  by c.customernumber, i.departmentnumber) loop
      begin
        insert into i_department
          (customernumber, departmentnumber, departmentname, deliverypointnumber,
           deliverypointdescription, delivernotetoemail, delivery_mo, delivery_tu, delivery_we,
           delivery_th, delivery_fr, delivery_sa, delivery_su, active, standardpackqty)
        values
          (x.customernumber, x.departmentnumber, to_char(x.departmentnumber), '1', '-', 'Y', 'Y',
           'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', x.usesbundles);
        counter := counter + 1;
      exception
        when dup_val_on_index then
          null;
      end;
    end loop;
    -- add missing departments 2.
    for x in (select i.customernumber, i.usesbundles
              from   i_customer i
              where  not exists (select d.department_id
                      from   department d, customer c
                      where  i.customernumber = c.customernumber
                      and    c.customer_id = d.customer_id)
              and    not exists (select id.departmentnumber
                      from   i_department id
                      where  id.customernumber = i.customernumber)) loop
      begin
        insert into i_department
          (customernumber, departmentnumber, departmentname, deliverypointnumber,
           deliverypointdescription, delivernotetoemail, delivery_mo, delivery_tu, delivery_we,
           delivery_th, delivery_fr, delivery_sa, delivery_su, active, standardpackqty)
        values
          (x.customernumber, 1, '-', 1, '-', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y',
           x.usesbundles);
        counter := counter + 1;
      exception
        when dup_val_on_index then
          null;
      end;
    end loop;
    --update occupancylevel, default = 100.
    update i_department i set i.occupancylevel = 100 where i.occupancylevel is null;
    --update standardpackqty, default = 'Y'.
    update i_department i set i.standardpackqty = 'Y' where i.standardpackqty is null;
    commit; -- commit when it was succesfull.
    if counter > 0 then
      begin
        pack_import.write_log(to_char(counter) || ' departments added to i_department!');
      end;
    end if;
  exception
    when others then
      begin
        lvnerrormsg := 'cfbadd_missing_departments: Fail to insert into i_department.';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbadd_missing_departments;
  procedure import_stockcountsequence is
    lv_counter number;
    procedure default_stockcntsch is
    begin
      --import stockcountschedule MO
      insert into stockcountschedule
        (stockcountschedule_id, customer_id, code, description, packoncountday, systemuser_id,
         timestamp)
        select seq_stockcountschedule.nextval, c.customer_id, '1', '1', 'N',
               pack_import.lvnsystemuserid, sysdate
        from   customer c
        where  exists (select d.stockcountsequence_mo
                from   i_department d
                where  d.customernumber = c.customernumber
                and    d.stockcountsequence_mo > 0)
        and    not exists (select x.stockcountschedule_id
                from   stockcountschedule x
                where  x.customer_id = c.customer_id
                and    x.code = '1');
      --import stockcountschedule TU
      insert into stockcountschedule
        (stockcountschedule_id, customer_id, code, description, packoncountday, systemuser_id,
         timestamp)
        select seq_stockcountschedule.nextval, c.customer_id, '2', '2', 'N',
               pack_import.lvnsystemuserid, sysdate
        from   customer c
        where  exists (select d.stockcountsequence_tu
                from   i_department d
                where  d.customernumber = c.customernumber
                and    d.stockcountsequence_tu > 0)
        and    not exists (select x.stockcountschedule_id
                from   stockcountschedule x
                where  x.customer_id = c.customer_id
                and    x.code = '2');
      --import stockcountschedule WE
      insert into stockcountschedule
        (stockcountschedule_id, customer_id, code, description, packoncountday, systemuser_id,
         timestamp)
        select seq_stockcountschedule.nextval, c.customer_id, '3', '3', 'N',
               pack_import.lvnsystemuserid, sysdate
        from   customer c
        where  exists (select d.stockcountsequence_we
                from   i_department d
                where  d.customernumber = c.customernumber
                and    d.stockcountsequence_we > 0)
        and    not exists (select x.stockcountschedule_id
                from   stockcountschedule x
                where  x.customer_id = c.customer_id
                and    x.code = '3');
      --import stockcountschedule TH
      insert into stockcountschedule
        (stockcountschedule_id, customer_id, code, description, packoncountday, systemuser_id,
         timestamp)
        select seq_stockcountschedule.nextval, c.customer_id, '4', '4', 'N',
               pack_import.lvnsystemuserid, sysdate
        from   customer c
        where  exists (select d.stockcountsequence_th
                from   i_department d
                where  d.customernumber = c.customernumber
                and    d.stockcountsequence_th > 0)
        and    not exists (select x.stockcountschedule_id
                from   stockcountschedule x
                where  x.customer_id = c.customer_id
                and    x.code = '4');
      --import stockcountschedule FR
      insert into stockcountschedule
        (stockcountschedule_id, customer_id, code, description, packoncountday, systemuser_id,
         timestamp)
        select seq_stockcountschedule.nextval, c.customer_id, '5', '5', 'N',
               pack_import.lvnsystemuserid, sysdate
        from   customer c
        where  exists (select d.stockcountsequence_fr
                from   i_department d
                where  d.customernumber = c.customernumber
                and    d.stockcountsequence_fr > 0)
        and    not exists (select x.stockcountschedule_id
                from   stockcountschedule x
                where  x.customer_id = c.customer_id
                and    x.code = '5');
      --import stockcountschedule SA
      insert into stockcountschedule
        (stockcountschedule_id, customer_id, code, description, packoncountday, systemuser_id,
         timestamp)
        select seq_stockcountschedule.nextval, c.customer_id, '6', '6', 'N',
               pack_import.lvnsystemuserid, sysdate
        from   customer c
        where  exists (select d.stockcountsequence_sa
                from   i_department d
                where  d.customernumber = c.customernumber
                and    d.stockcountsequence_sa > 0)
        and    not exists (select x.stockcountschedule_id
                from   stockcountschedule x
                where  x.customer_id = c.customer_id
                and    x.code = '6');
      --import stockcountschedule SU
      insert into stockcountschedule
        (stockcountschedule_id, customer_id, code, description, packoncountday, systemuser_id,
         timestamp)
        select seq_stockcountschedule.nextval, c.customer_id, '7', '7', 'N',
               pack_import.lvnsystemuserid, sysdate
        from   customer c
        where  exists (select d.stockcountsequence_su
                from   i_department d
                where  d.customernumber = c.customernumber
                and    d.stockcountsequence_su > 0)
        and    not exists (select x.stockcountschedule_id
                from   stockcountschedule x
                where  x.customer_id = c.customer_id
                and    x.code = '7');
    end default_stockcntsch;
    procedure default_stockcntday is
    begin
      begin
        --import stockcountscheduleday's
        insert into stockcountscheduleday
          (stockcountschedule_id, day_id, systemuser_id, timestamp, deliveryday_id)
          select s.stockcountschedule_id, d.day_id, pack_import.lvnsystemuserid, sysdate, d.day_id
          from   stockcountschedule s, day d
          where  s.code = to_char(d.daynumber)
          and    not exists (select 1
                  from   stockcountscheduleday sx
                  where  sx.stockcountschedule_id = s.stockcountschedule_id
                  and    sx.day_id = d.day_id)
          and    exists (select 1
                  from   i_customer i, customer c
                  where  c.customer_id = s.customer_id
                  and    i.customernumber = c.customernumber);
      exception
        when others then
          begin
            pack_import.write_log('Error import_stockcountsequence/stockcountscheduleday: ' ||
                                  substr(sqlerrm, 1, 200));
          end;
      end;
    end default_stockcntday;
    procedure default_stockcntdep is
    begin
      --import stockcountscheduledept MO
      insert into stockcountscheduledept
        (stockcountscheduledept_id, department_id, stockcountschedule_id, countsequence,
         systemuser_id, timestamp)
        select seq_stockcountscheduledept.nextval, d.department_id, s.stockcountschedule_id,
               i.stockcountsequence_mo, pack_import.lvnsystemuserid, sysdate
        from   i_department i, department d, customer c, stockcountschedule s
        where  i.departmentnumber = d.departmentnumber
        and    i.customernumber = c.customernumber
        and    d.customer_id = c.customer_id
        and    s.code = '1'
        and    i.stockcountsequence_mo > 0
        and    s.customer_id = c.customer_id
        and    not exists (select x.stockcountscheduledept_id
                from   stockcountscheduledept x
                where  x.countsequence = i.stockcountsequence_mo
                and    x.department_id = d.department_id
                and    x.stockcountschedule_id = s.stockcountschedule_id);
      --import stockcountscheduledept TU
      insert into stockcountscheduledept
        (stockcountscheduledept_id, department_id, stockcountschedule_id, countsequence,
         systemuser_id, timestamp)
        select seq_stockcountscheduledept.nextval, d.department_id, s.stockcountschedule_id,
               i.stockcountsequence_tu, pack_import.lvnsystemuserid, sysdate
        from   i_department i, department d, customer c, stockcountschedule s
        where  i.departmentnumber = d.departmentnumber
        and    i.customernumber = c.customernumber
        and    d.customer_id = c.customer_id
        and    s.code = '2'
        and    i.stockcountsequence_tu > 0
        and    s.customer_id = c.customer_id
        and    not exists (select x.stockcountscheduledept_id
                from   stockcountscheduledept x
                where  x.countsequence = i.stockcountsequence_tu
                and    x.department_id = d.department_id
                and    x.stockcountschedule_id = s.stockcountschedule_id);
      --import stockcountscheduledept WE
      insert into stockcountscheduledept
        (stockcountscheduledept_id, department_id, stockcountschedule_id, countsequence,
         systemuser_id, timestamp)
        select seq_stockcountscheduledept.nextval, d.department_id, s.stockcountschedule_id,
               i.stockcountsequence_we, pack_import.lvnsystemuserid, sysdate
        from   i_department i, department d, customer c, stockcountschedule s
        where  i.departmentnumber = d.departmentnumber
        and    i.customernumber = c.customernumber
        and    d.customer_id = c.customer_id
        and    s.code = '3'
        and    i.stockcountsequence_we > 0
        and    s.customer_id = c.customer_id
        and    not exists (select x.stockcountscheduledept_id
                from   stockcountscheduledept x
                where  x.countsequence = i.stockcountsequence_we
                and    x.department_id = d.department_id
                and    x.stockcountschedule_id = s.stockcountschedule_id);
      --import stockcountscheduledept TH
      insert into stockcountscheduledept
        (stockcountscheduledept_id, department_id, stockcountschedule_id, countsequence,
         systemuser_id, timestamp)
        select seq_stockcountscheduledept.nextval, d.department_id, s.stockcountschedule_id,
               i.stockcountsequence_th, pack_import.lvnsystemuserid, sysdate
        from   i_department i, department d, customer c, stockcountschedule s
        where  i.departmentnumber = d.departmentnumber
        and    i.customernumber = c.customernumber
        and    d.customer_id = c.customer_id
        and    s.code = '4'
        and    i.stockcountsequence_th > 0
        and    s.customer_id = c.customer_id
        and    not exists (select x.stockcountscheduledept_id
                from   stockcountscheduledept x
                where  x.countsequence = i.stockcountsequence_th
                and    x.department_id = d.department_id
                and    x.stockcountschedule_id = s.stockcountschedule_id);
      --import stockcountscheduledept FR
      insert into stockcountscheduledept
        (stockcountscheduledept_id, department_id, stockcountschedule_id, countsequence,
         systemuser_id, timestamp)
        select seq_stockcountscheduledept.nextval, d.department_id, s.stockcountschedule_id,
               i.stockcountsequence_fr, pack_import.lvnsystemuserid, sysdate
        from   i_department i, department d, customer c, stockcountschedule s
        where  i.departmentnumber = d.departmentnumber
        and    i.customernumber = c.customernumber
        and    d.customer_id = c.customer_id
        and    s.code = '5'
        and    i.stockcountsequence_fr > 0
        and    s.customer_id = c.customer_id
        and    not exists (select x.stockcountscheduledept_id
                from   stockcountscheduledept x
                where  x.countsequence = i.stockcountsequence_fr
                and    x.department_id = d.department_id
                and    x.stockcountschedule_id = s.stockcountschedule_id);
      --import stockcountscheduledept SA
      insert into stockcountscheduledept
        (stockcountscheduledept_id, department_id, stockcountschedule_id, countsequence,
         systemuser_id, timestamp)
        select seq_stockcountscheduledept.nextval, d.department_id, s.stockcountschedule_id,
               i.stockcountsequence_sa, pack_import.lvnsystemuserid, sysdate
        from   i_department i, department d, customer c, stockcountschedule s
        where  i.departmentnumber = d.departmentnumber
        and    i.customernumber = c.customernumber
        and    d.customer_id = c.customer_id
        and    s.code = '6'
        and    i.stockcountsequence_sa > 0
        and    s.customer_id = c.customer_id
        and    not exists (select x.stockcountscheduledept_id
                from   stockcountscheduledept x
                where  x.countsequence = i.stockcountsequence_sa
                and    x.department_id = d.department_id
                and    x.stockcountschedule_id = s.stockcountschedule_id);
      --import stockcountscheduledept SU
      insert into stockcountscheduledept
        (stockcountscheduledept_id, department_id, stockcountschedule_id, countsequence,
         systemuser_id, timestamp)
        select seq_stockcountscheduledept.nextval, d.department_id, s.stockcountschedule_id,
               i.stockcountsequence_su, pack_import.lvnsystemuserid, sysdate
        from   i_department i, department d, customer c, stockcountschedule s
        where  i.departmentnumber = d.departmentnumber
        and    i.customernumber = c.customernumber
        and    d.customer_id = c.customer_id
        and    s.code = '7'
        and    i.stockcountsequence_su > 0
        and    s.customer_id = c.customer_id
        and    not exists (select x.stockcountscheduledept_id
                from   stockcountscheduledept x
                where  x.countsequence = i.stockcountsequence_su
                and    x.department_id = d.department_id
                and    x.stockcountschedule_id = s.stockcountschedule_id);
    end default_stockcntdep;
    procedure import_stockcount is
      lv_message              abslog.message%type;
      lv_customerid           customer.customer_id%type;
      lv_stockcountscheduleid stockcountschedule.stockcountschedule_id%type;
      lv_departmentid         department.department_id%type;
      lv_distributionpointid  distributionpoint.distributionpoint_id%type;
    begin
      --import_stockcount
      for x in (select customernumber, stockcountschedulecode, stockcountscheduledesc, packoncountday,
                       replenishmenttype, deliverydaydetermination
                from   i_stockcountschedule
                order  by customernumber, stockcountschedulecode) loop
        begin
          --get customer id
          lv_message := 'customer number ' || x.customernumber;
          select c.customer_id
          into   lv_customerid
          from   customer c
          where  c.customernumber = x.customernumber;
          --get / create stockcountschedule
          begin
            select scs.stockcountschedule_id
            into   lv_stockcountscheduleid
            from   stockcountschedule scs
            where  scs.customer_id = lv_customerid
            and    scs.code = x.stockcountschedulecode;
          exception
            when no_data_found then
              begin
                --insert into stockcountschedule
                lv_message := 'insert into stockcountschedule for customer ' || x.customernumber ||
                              ' code ' || x.stockcountschedulecode;
                insert into stockcountschedule
                  (stockcountschedule_id, customer_id, code, description, packoncountday,
                   systemuser_id, timestamp, replenishmenttype, deliverydaydetermination)
                values
                  (seq_stockcountschedule.nextval, lv_customerid, x.stockcountschedulecode,
                   coalesce(x.stockcountscheduledesc, x.stockcountschedulecode),
                   nvl(x.packoncountday, 'N'), pack_import.lvnsystemuserid, sysdate,
                   nvl(x.replenishmenttype, 0), nvl(x.deliverydaydetermination, 0))
                returning stockcountschedule_id into lv_stockcountscheduleid;
              end;
          end;
          --loop fill i_stockcountscheduledist (y)
          for y in (select issd.customernumber, issd.stockcountschedulecode, issd.departmentnumber,
                           issd.consumptionpointnumber, issd.countsequence
                    from   i_stockcountscheduledist issd
                    where  issd.customernumber = x.customernumber
                    and    issd.stockcountschedulecode = x.stockcountschedulecode
                    order  by issd.departmentnumber, issd.consumptionpointnumber, issd.countsequence) loop
            begin
              --get department id
              lv_message := 'Department ' || y.departmentnumber || ' for customer number ' ||
                            x.customernumber;
              select t.department_id
              into   lv_departmentid
              from   department t
              where  t.customer_id = lv_customerid
              and    t.departmentnumber = y.departmentnumber;
              --get distributionpoint id
              lv_message := 'Consumption point ' || y.consumptionpointnumber || ' for department ' ||
                            y.departmentnumber || ' for customer number ' || x.customernumber;
              select dp.distributionpoint_id
              into   lv_distributionpointid
              from   distributionpoint dp
              where  dp.department_id = lv_departmentid
              and    dp.distributionpointnumber = y.consumptionpointnumber;
              --insert into stockcountscheduledist
              lv_message := 'insert into stockcountscheduledist for consumption point ' ||
                            y.consumptionpointnumber || ' for department ' || y.departmentnumber ||
                            ' for customer number ' || x.customernumber;
              insert into stockcountscheduledist
                (stockcountscheduledist_id, stockcountschedule_id, distributionpoint_id,
                 countsequence, systemuser_id, timestamp)
                select seq_stockcountscheduledist.nextval, lv_stockcountscheduleid,
                       lv_distributionpointid, coalesce(y.countsequence, zzx.countsequence, 1),
                       pack_import.lvnsystemuserid, sysdate
                from   (select max(zz.countsequence) + 1 countsequence
                         from   stockcountscheduledist zz
                         where  zz.stockcountschedule_id = lv_stockcountscheduleid) zzx;
            exception
              when dup_val_on_index then
                null; --its ok it is already there
              when no_data_found then
                begin
                  pack_import.write_log('Import_stockcount(y); No data found ' || lv_message);
                end;
            end;
          end loop; --y
          --loop fill i_stockcountscheduleday (z)
          for z in (select issx.customernumber, issx.stockcountschedulecode, issx.day,
                           issx.deliveryday, issx.orderingdeadline, issx.compulsoryorderday
                    from   i_stockcountscheduleday issx
                    where  issx.customernumber = x.customernumber
                    and    issx.stockcountschedulecode = x.stockcountschedulecode
                    and    not exists
                     (select 1
                            from   stockcountscheduleday sx
                            where  sx.stockcountschedule_id = lv_stockcountscheduleid
                            and    sx.day_id = issx.day)
                    order  by issx.day) loop
            begin
              --insert into stockcountscheduleday
              lv_message := 'insert into stockcountscheduleday for customer ' || x.customernumber ||
                            ' code ' || x.stockcountschedulecode;
              insert into stockcountscheduleday
                (stockcountschedule_id, day_id, systemuser_id, timestamp, deliveryday_id,
                 orderingdeadline, compulsoryorderday)
              values
                (lv_stockcountscheduleid, z.day, pack_import.lvnsystemuserid, sysdate,
                 nvl(z.deliveryday, z.day),
                 nvl(z.orderingdeadline, to_date('12:00:00', 'HH24:MI:SS')),
                 nvl(z.compulsoryorderday, 0));
            exception
              when dup_val_on_index then
                null; --its ok it is already there
              when no_data_found then
                begin
                  pack_import.write_log('Import_stockcount(z); No data found ' || lv_message);
                end;
            end;
          end loop; --z
          lv_counter := lv_counter + 1;
        exception
          when no_data_found then
            begin
              pack_import.write_log('Import_stockcount(x); No data found ' || lv_message);
            end;
        end;
      end loop; --x
    exception
      when others then
        begin
          pack_import.write_log('Import_stockcount; Error ' || sqlerrm || ' during ' || lv_message);
        end;
    end import_stockcount;
  begin
    select count(1) into lv_counter from i_stockcountschedule;
    if lv_counter = 0 then
      begin
        --old way of importing
        default_stockcntsch;
        default_stockcntday;
        default_stockcntdep;
        commit;
        pack_import.write_log('Default Import_stockcountsequence ran succesfully.');
      end;
    else
      begin
        --new import stockcount
        lv_counter := 0;
        import_stockcount;
        commit;
        pack_import.write_log('Import_stockcountsequence ran succesfully, processed ' ||
                              lv_counter || ' Stockcount schedules');
      end;
    end if;
  exception
    when others then
      begin
        pack_import.write_log('Error import_stockcountsequence: ' || substr(sqlerrm, 1, 200));
      end;
  end import_stockcountsequence;
  procedure cfbimport_consumptionpoints(fpndepartment_id         department.department_id%type,
                                        fpconsumptionpointnumber in distributionpoint.distributionpointnumber%type default null) is
    fpndeliverypoint_id       deliverypoint.deliverypoint_id%type;
    fpndistributionpoint_id   distributionpoint.distributionpoint_id%type;
    fpncostcenter_id          costcenter.costcenter_id%type;
    fpnmintransportarticle_id transportarticle.transportarticle_id%type;
    fpnstandarddelivery_id    standarddelivery.standarddelivery_id%type;
    fpnsequencenumber         standarddelivery.sequencenumber%type;
  begin
    -- determine default transport article
    select min(t.transportarticle_id) into fpnmintransportarticle_id from transportarticle t;
    -- loop consumptionpoint i-table
    for x in (select c.customer_id, c.visitaddress_id, d.department_id, i.consumptionpointnumber,
                     nvl(i.consumptionpointdescription, '-') consumptionpointdescription,
                     nvl(to_char(i.deliverypointnumber), '1') deliverypointnumber,
                     replace(i.remarkondeliverynote, '|', chr(10)) remarkondeliverynote,
                     replace(i.remarkonpackingnote, '|', chr(10)) remarkonpackingnote, i.cleanreturn,
                     i.correctshortages, i.correctoverdeliveries, i.truckloadposition,
                     i.transportarticlecode, i.numberoftransportarticles, i.generatezerolines,
                     i.deliversterile, i.proofofvisitbarcode,
                     replace(i.driverinstruction, '|', chr(10)) driverinstruction,
                     i.legacyconsumptionpointnumber, i.materialmaintenance, i.garmentsetup,
                     i.garmentmaintenance, i.garmentloss, i.garmentrepair, i.mbyoprotection,
                     i.garmentemblem
              from   i_consumptionpoint i, department d, customer c
              where  i.customernumber = c.customernumber
              and    i.departmentnumber = d.departmentnumber
              and    c.customer_id = d.customer_id
              and    d.department_id = fpndepartment_id
              and    (i.consumptionpointnumber = fpconsumptionpointnumber or
                    fpconsumptionpointnumber is null)) loop
      begin
        begin
          select p.deliverypoint_id
          into   fpndeliverypoint_id
          from   deliverypoint p
          where  p.customer_id = x.customer_id
          and    p.code = x.deliverypointnumber;
        exception
          when no_data_found then
            begin
              -- inserting the delivery and distributionpoints.
              pack_import.cfbcreate_deliverypoint(fpndeliverypoint_id,
                                                  --fpndeliverypoint_id,
                                                  x.customer_id,
                                                  --fpncustomer_id,
                                                  x.deliverypointnumber,
                                                  --fpscode,
                                                  x.consumptionpointdescription,
                                                  --fpsdescription,
                                                  x.visitaddress_id,
                                                  --fpndeliveryaddressid,
                                                  null); --fpssortaddress
            end;
        end;
        select min(c.costcenter_id)
        into   fpncostcenter_id
        from   costcenter c
        where  c.customer_id = x.customer_id;
        begin
          select p.distributionpoint_id
          into   fpndistributionpoint_id
          from   distributionpoint p
          where  p.distributionpointnumber = x.consumptionpointnumber
          and    p.department_id = x.department_id;
          update distributionpoint p
          set    p.proofofvisitbarcode = x.proofofvisitbarcode,
                 p.driverinstruction = x.driverinstruction, p.costcenter_id = fpncostcenter_id
          where  p.distributionpoint_id = fpndistributionpoint_id
          and    trunc(p.timestamp) = trunc(sysdate);
        exception
          when no_data_found then
            begin
              pack_import.cfbcreate_distributionpoint(fpndistributionpoint_id,
                                                      --fpndistributionpoint_id,
                                                      x.consumptionpointnumber,
                                                      --fpndistributionpointnumber,
                                                      x.consumptionpointdescription,
                                                      --fpsdescription,
                                                      x.remarkonpackingnote,
                                                      --fpsremarkonpackingnote,
                                                      x.remarkondeliverynote,
                                                      --fpsremarkondeliverynote,
                                                      to_date('31-12-2099', 'DD-MM-YYYY'),
                                                      --fpdtpackremarkenddate,
                                                      to_date('31-12-2099', 'DD-MM-YYYY'),
                                                      --fpdtdeliverremarkenddate,
                                                      'Y',
                                                      --fpsactive,
                                                      x.department_id,
                                                      --fpndepartment_id,
                                                      fpndeliverypoint_id,
                                                      --fpndeliverypoint_id,
                                                      fpncostcenter_id,
                                                      --fpncostcenter_id,
                                                      x.legacyconsumptionpointnumber,
                                                      x.proofofvisitbarcode, x.driverinstruction,
                                                      x.materialmaintenance, x.garmentsetup,
                                                      x.garmentmaintenance, x.garmentloss,
                                                      x.garmentrepair, x.mbyoprotection,
                                                      x.garmentemblem);
            end;
        end;
        --get transport article if needed
        if trim(x.transportarticlecode) is null then
          begin
            fpntransportarticle_id := fpnmintransportarticle_id;
          end;
        else
          begin
            select a.transportarticle_id
            into   fpntransportarticle_id
            from   transportarticle a
            where  a.code = trim(x.transportarticlecode);
          exception
            when others then
              fpntransportarticle_id := fpnmintransportarticle_id;
          end;
        end if;
        --determine fpnsequencenumber
        select nvl(count(*), 0) + 1
        into   fpnsequencenumber
        from   standarddelivery
        where  distributionpoint_id = fpndistributionpoint_id;
        pack_import.cfbcreate_standarddelivery(fpnstandarddelivery_id,
                                               --fpnstandarddelivery_id,
                                               fpnsequencenumber,
                                               --fpnsequencenumber,
                                               x.deliversterile,
                                               --fpsdeliversterile,
                                               null,
                                               --fpnplantdepartment_id,
                                               x.cleanreturn,
                                               --fpscleanreturn,
                                               fpntransportarticle_id,
                                               --fpntransportarticle_id,
                                               x.generatezerolines,
                                               --fpsgeneratezerolines,
                                               x.numberoftransportarticles,
                                               --fpnnumberoftransportarticles,
                                               fpndistributionpoint_id,
                                               --fpndistributionpoint_id,
                                               null,
                                               --fpdtlastpackingdate,
                                               x.correctshortages,
                                               --fpscorrectshortages,
                                               x.correctoverdeliveries,
                                               --fpscorrectoverdeliveries,
                                               x.truckloadposition);
      exception
        when dup_val_on_index then
          null; -- already exists no problem.
      end;
    end loop;
  exception
    when others then
      begin
        rollback;
        lvnerrormsg := 'CFbImport_ConsumptionPoints: Fail to import.';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_consumptionpoints;
  procedure imp_conspointbudgetprotection is
    lvcounter number := 0;
  begin
    --imp_conspointbudgetprotection
    lvnerrormsg := 'imp_conspointbudgetprotection';
    for pp in (select dp.distributionpoint_id, cc.consumptionpointnumber, cc.materialmaintenance,
                      cc.garmentsetup, cc.garmentmaintenance, cc.garmentloss, cc.garmentrepair,
                      cc.mbyoprotection
               from   i_consumptionpoint cc
               join   customer c
               on     c.customernumber = cc.customernumber
               join   department t
               on     (t.customer_id = c.customer_id and t.departmentnumber = cc.departmentnumber)
               join   distributionpoint dp
               on     (dp.department_id = t.department_id and
                      dp.distributionpointnumber = cc.consumptionpointnumber)
               where  (cc.materialmaintenance = 'Y' or cc.garmentsetup = 'Y' or
                      cc.garmentmaintenance = 'Y' or cc.garmentloss = 'Y' or cc.garmentrepair = 'Y' or
                      cc.mbyoprotection = 'Y')) loop
      begin
        update distribpointbgprotection dpp
        set    dpp.materialmaintenance = pp.materialmaintenance,
               dpp.garmentsetup = nvl(pp.garmentsetup, 'Y'),
               dpp.garmentmaintenance = nvl(pp.garmentmaintenance, 'Y'),
               dpp.garmentloss = nvl(pp.garmentloss, 'Y'),
               dpp.garmentrepair = nvl(pp.garmentrepair, 'Y'),
               dpp.systemuser_id = pack_import.lvnsystemuserid, dpp.timestamp = sysdate,
               dpp.mbyoprotection = nvl(pp.mbyoprotection, 'Y')
        where  dpp.distributionpoint_id = pp.distributionpoint_id;
        --count rows inserted
        lvcounter := lvcounter + 1;
      end;
    end loop; --pp
    commit;
    if lvcounter > 0 then
      pack_import.write_log(lvcounter || ' Consumptionpoint Budget Protection rows imported.');
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('imp_conspointbudgetprotection: Failed to import/update with i-table values ' ||
                              substr(sqlerrm, 1, 512), 3);
      end;
  end imp_conspointbudgetprotection;
  procedure convert_i_consumptionpoints is
  begin
    for x in (select t.department_id, i.consumptionpointnumber
              from   i_consumptionpoint i
              join   customer c
              on     c.customernumber = i.customernumber
              join   department t
              on     (t.customer_id = c.customer_id and t.departmentnumber = i.departmentnumber)
              where  not exists (select 1
                      from   distributionpoint dp
                      where  dp.distributionpointnumber = i.consumptionpointnumber
                      and    dp.department_id = t.department_id)) loop
      begin
        cfbimport_consumptionpoints(x.department_id, x.consumptionpointnumber);
      exception
        when others then
          pack_import.write_log('Error convert_i_consumptionpoints during loop: ' ||
                                substr(sqlerrm, 1, 200));
      end;
    end loop;
  exception
    when others then
      begin
        pack_import.write_log('Error convert_i_consumptionpoints: ' || substr(sqlerrm, 1, 200));
      end;
  end convert_i_consumptionpoints;
  procedure cfbimport_nonebusinessdays(fpndepartmentid in department.department_id%type,
                                       fpncustomernumber in customer.customernumber%type) is
    lvnerrormsg abslog.message%type;
  begin
    --create none businessdays records
    for m in (select c.customer_id, t.department_id, n.nonbusinessdate, n.closestatus,
                     n.customernumber, n.departmentnumber, bu.plant_id
              from   i_nonbusinessday n
              join customer c
                on n.customernumber = c.customernumber
              left outer join department t
                on (n.departmentnumber = t.departmentnumber  and t.customer_id = c.customer_id)
              join businessunit bu
                on c.defaultbusinessunit_id = bu.businessunit_id
              and  ((fpndepartmentid = t.department_id) or (t.department_id is null))
              and  n.customernumber = fpncustomernumber) loop
      begin
        lvnerrormsg := ' customer ' || m.customernumber || ' depart# ' || m.departmentnumber ||
                       ' non.bu.date ' || to_char(m.nonbusinessdate, 'DD-MON-YYYY');
        insert into nonbusinessday
          (nonbusinessday_id, nonbusinessday, department_id, customer_id, systemuser_id, timestamp,
           plant_id, closestatus, movedays)
        values
          (seq_nonbusinessday.nextval, m.nonbusinessdate, m.department_id, m.customer_id,
           pack_import.lvnsystemuserid, sysdate, m.plant_id, m.closestatus, 0);
      exception
        when dup_val_on_index then
          null;
      end;
    end loop;
  exception
    when others then
      begin
        lvnerrormsg := 'cfbimport_nonebusinessdays: Fail to import.';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_nonebusinessdays;
  function cfbimport_departments(ncustomernumber customer.customernumber%type) return number is
    fpndepartment_id     department.department_id%type;
    fpndeliverypoint_id  deliverypoint.deliverypoint_id%type;
    fpncostcenter_id     costcenter.costcenter_id%type;
    fpserrormsg          varchar2(100);
    fpndeliveryaddressid address.address_id%type;
    fpncontactpersonid   contactperson.contactperson_id%type;
    fpncounter           number := 0;
    procedure cfbcreate_deliveryday(fp_customerid    in customer.customer_id%type,
                                    fp_department_id in deliveryday.department_id%type,
                                    fp_day_id        in deliveryday.day_id%type) is
      lv_dayid day.day_id%type;
    begin
      begin
        select cdd.day_id
        into   lv_dayid
        from   customerdeliveryday cdd
        where  cdd.customer_id = fp_customerid
        and    cdd.day_id = fp_day_id
        and    cdd.typeofmerchadise = 1;
      exception
        when no_data_found then
          begin
            select max(i.daynumber)
            into   lv_dayid
            from   i_deliverydays i
            where  i.customernumber = ncustomernumber
            and    i.daynumber = fp_day_id;
          end;
      end;
      if lv_dayid is not null then
        begin
          --only create deliveryday when customer is also visited!!
          insert into deliveryday
            (department_id, day_id, systemuser_id, timestamp)
          values
            (fp_department_id, lv_dayid, pack_import.lvnsystemuserid, sysdate);
        end;
      end if;
    exception
      when no_data_found then
        begin
          null;
        end;
    end cfbcreate_deliveryday;
    procedure create_deliverypoint(fp_customer_id       in customer.customer_id%type,
                                   fp_customernumber    customer.customernumber%type,
                                   fp_departmentnumber  department.departmentnumber%type,
                                   fp_deliverypointcode in deliverypoint.code%type,
                                   fp_deliverypointdesc in deliverypoint.description%type,
                                   fp_delcity           in address.city%type,
                                   fp_delzipcode        in address.zipcode%type,
                                   fp_deladdress        in address.street%type,
                                   fp_delstate          in address.state%type,
                                   fp_delcounty         in address.county%type,
                                   fp_deladdress2       in address.street2%type,
                                   fp_deladdress3       in address.street3%type) is
    begin
      begin
        if fp_delcity is not null and fp_delzipcode is not null then
          begin
            -- create or get the delivery address.
            fpndeliveryaddressid := pack_import_customer.getaddressid(fp_deladdress, fp_delzipcode,
                                                                      fp_delcity, fp_delstate,
                                                                      fp_delcounty, fp_deladdress2,null,null,fp_deladdress3);
          end;
        end if;
        if fpndeliveryaddressid is null then
          begin
            -- get address from customer
            select c.visitaddress_id
            into   fpndeliveryaddressid
            from   customer c
            where  c.customer_id = fp_customer_id;
          end;
        end if;
      end;
      -- inserting the delivery and distributionpoints.
      pack_import.cfbcreate_deliverypoint(fpndeliverypoint_id,
                                          --fpndeliverypoint_id,
                                          fp_customer_id,
                                          --fpncustomer_id,
                                          fp_deliverypointcode,
                                          --fpscode,
                                          fp_deliverypointdesc,
                                          --fpsdescription,
                                          fpndeliveryaddressid,
                                          --fpndeliveryaddressid,
                                          null); --fpssortaddress
      --insert missing consumptionpoints
      insert into i_consumptionpoint
        (consumptionpointnumber, customernumber, departmentnumber, consumptionpointdescription,
         deliverypointnumber, transportarticlecode, correctshortages)
        select to_number(substr(to_char(di.departmentnumber), 1, 2)), di.customernumber,
               di.departmentnumber, fp_deliverypointcode, di.deliverypointnumber, '1',
               nvl((select ic.correctshortages
                    from   i_customer ic
                    where  ic.customernumber = di.customernumber), 'N') correctshortages
        from   i_department di
        where  di.customernumber = fp_customernumber
        and    di.departmentnumber = fp_departmentnumber
        and    not exists (select i.consumptionpointnumber
                from   i_consumptionpoint i
                where  i.departmentnumber = di.departmentnumber
                and    i.customernumber = di.customernumber);
    end create_deliverypoint;
  begin
    cfbimport_nonebusinessdays(null, ncustomernumber);
    for x in -- start entering the departments from itables into database
     (select c.customer_id, i.departmentnumber, i.departmentname, i.occupancylevel, i.standardpackqty,
             i.delivernotetoemail, i.contactpersonnumber, i.active, o.costcenter_id, i.delivery_mo,
             i.delivery_tu, i.delivery_we, i.delivery_th, i.delivery_fr, i.delivery_sa, i.delivery_su,
             c.customernumber, i.deliverypointnumber,
             nvl(i.deliverypointdescription, '-') deliverypointdescription, i.deliveryaddress,
             i.deliveryaddress2, i.deliveryzipcode, i.deliverycity, i.deliverycounty, i.deliverystate,
             i.legacydepartmentcode, i.deliveryaddress3
      from   i_department i, customer c, costcenter o
      where  ncustomernumber = i.customernumber
      and    i.customernumber = c.customernumber
      and    c.customer_id = o.customer_id(+)
      and    not exists (select x.department_id
              from   department x
              where  x.departmentnumber = i.departmentnumber
              and    x.customer_id = c.customer_id)) loop
      begin
        -- for error message
        fpserrormsg := to_char(x.customernumber) || '/' || to_char(x.departmentnumber);
        --convert_costcentergroup
        pack_import_department.convert_costcentergroup(x.customernumber);
        --get contactperson
        if x.contactpersonnumber is not null then
          begin
            select c.contactperson_id
            into   fpncontactpersonid
            from   contactperson c
            where  c.customer_id = x.customer_id
            and    c.contactpersonnumber = x.contactpersonnumber;
          exception
            when others then
              begin
                fpncontactpersonid := null;
              end;
          end;
        else
          begin
            fpncontactpersonid := null;
          end;
        end if;
        fpncostcenter_id := null;
        if x.costcenter_id is null then
          --create costcenter if it does not yet exist.
          begin
            for xy in (select i.consumptionpointnumber, i.costcentercode, i.costcenterdescription,
                              i.deliverypointcode, i.ponumber, i.requisitionnumber,
                              i.accountingstring, i.eannumber, i.exportedi, ccg.costcentergroup_id
                       from   i_costcenter i
                       join   customer c
                       on     c.customernumber = i.customernumber
                       left   outer join costcentergroup ccg
                       on     (ccg.customer_id = c.customer_id and ccg.code = i.costcentergroupcode)
                       where  c.customer_id = x.customer_id
                       and    i.departmentnumber = x.departmentnumber) loop
              begin
                select cc.costcenter_id
                into   fpncostcenter_id
                from   costcenter cc
                where  cc.code = xy.costcentercode
                and    cc.customer_id = x.customer_id;
                exit;
              exception
                when no_data_found then
                  begin
                    pack_import.cfbcreate_costcenter(fpncostcenter_id, xy.costcentercode,
                                                     xy.costcenterdescription, x.customer_id, null,
                                                     fpncontactpersonid, xy.ponumber,
                                                     xy.requisitionnumber, xy.accountingstring,
                                                     xy.eannumber, xy.exportedi,
                                                     xy.costcentergroup_id);
                    exit;
                  end;
              end;
            end loop; --xy
            if fpncostcenter_id is null then
              begin
                pack_import.cfbcreate_costcenter(fpncostcenter_id,
                                                 --fpncostcenter_id,
                                                 to_char(substr(x.departmentnumber, 1, 12)),
                                                 --fpscode,
                                                 substr(x.departmentname, 1, 30),
                                                 --fpsdescription,
                                                 x.customer_id,
                                                 --fpncustomer_id,
                                                 null,
                                                 --fpninvoiceaddress_id,
                                                 fpncontactpersonid);
              end;
            end if;
          exception
            when others then
              lvnerrormsg := 'Fail to import costcenter. customer/department: ' || fpserrormsg;
              pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
          end;
        else
          fpncostcenter_id := x.costcenter_id;
        end if;
        pack_import.cfbcreate_department(fpndepartment_id,
                                         --fpndepartment_id,
                                         x.departmentnumber,
                                         --fpsnumber,
                                         x.departmentname,
                                         --fpsdescription,
                                         fpncostcenter_id,
                                         --fpncostcenter_id,
                                         x.occupancylevel,
                                         --fpnoccupancy,
                                         x.standardpackqty,
                                         --fpsstandardpackamount,
                                         x.active,
                                         --fpsactive,
                                         x.customer_id,
                                         --fpncustomer_id,
                                         x.legacydepartmentcode,
                                         --fpslegacydepartmentcode,
                                         fpncontactpersonid,
                                         --fpncontactperson_id,
                                         x.delivernotetoemail); --fpsdelnotetoemail);
        if x.deliverypointnumber is null then
          begin
            --check if there is at least 1 deliverypoint for this customer,
            --if not create it with department number!
            --if so it is ok.
            select min(dp.deliverypoint_id)
            into   fpndeliverypoint_id
            from   deliverypoint dp
            where  dp.customer_id = x.customer_id;
            if fpndeliverypoint_id is null then
              begin
                --only create one when there are none, they should be there otherwise already
                --with the customer conversion
                create_deliverypoint(x.customer_id, x.customernumber, x.departmentnumber,
                                     to_char(x.departmentnumber),
                                     --departmentnumber=deliverypoint
                                     x.deliverypointdescription, x.deliverycity, x.deliveryzipcode,
                                     x.deliveryaddress, x.deliverystate, x.deliverycounty,
                                     x.deliveryaddress2, x.deliveryaddress3);
              end;
            end if;
          end;
        else
          begin
            --check if it is there, if not create it
            select p.deliverypoint_id
            into   fpndeliverypoint_id
            from   deliverypoint p
            where  p.customer_id = x.customer_id
            and    p.code = x.deliverypointnumber;
          exception
            when no_data_found then
              create_deliverypoint(x.customer_id, x.customernumber, x.departmentnumber,
                                   x.deliverypointnumber, x.deliverypointdescription, x.deliverycity,
                                   x.deliveryzipcode, x.deliveryaddress, x.deliverystate,
                                   x.deliverycounty, x.deliveryaddress2, x.deliveryaddress3);
          end;
        end if;
        --add consumptionpoints
        cfbimport_consumptionpoints(fpndepartment_id);
        --add nonbusinessdays
        cfbimport_nonebusinessdays(fpndepartment_id, x.customernumber);
        /* 1 = monday and 7 = sunday */
        if x.delivery_mo = 'N' then
          -- insert so it will NOT be visited.
          cfbcreate_deliveryday(x.customer_id, fpndepartment_id, 1);
        end if;
        if x.delivery_tu = 'N' then
          -- insert so it will NOT be visited.
          cfbcreate_deliveryday(x.customer_id, fpndepartment_id, 2);
        end if;
        if x.delivery_we = 'N' then
          -- insert so it will NOT be visited.
          cfbcreate_deliveryday(x.customer_id, fpndepartment_id, 3);
        end if;
        if x.delivery_th = 'N' then
          -- insert so it will NOT be visited.
          cfbcreate_deliveryday(x.customer_id, fpndepartment_id, 4);
        end if;
        if x.delivery_fr = 'N' then
          -- insert so it will NOT be visited.
          cfbcreate_deliveryday(x.customer_id, fpndepartment_id, 5);
        end if;
        if x.delivery_sa = 'N' then
          -- insert so it will NOT be visited.
          cfbcreate_deliveryday(x.customer_id, fpndepartment_id, 6);
        end if;
        if x.delivery_su = 'N' then
          -- insert so it will NOT be visited.
          cfbcreate_deliveryday(x.customer_id, fpndepartment_id, 7);
        end if;
        fpncounter := fpncounter + 1;
      exception
        when dup_val_on_index then
          null;
      end; -- already exists no problem.
    end loop;
    commit; -- commit when it was succesfull.
    return fpncounter;
  exception
    when others then
      begin
        rollback;
        lvnerrormsg := 'Fail to import. Department/customer: ' || fpserrormsg;
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
        return fpncounter;
      end;
  end cfbimport_departments;
  procedure convert_i_department is
    lresult number;
    lcount  number := 0;
  begin
    for x in (select i.customernumber from i_department i group by i.customernumber) loop
      begin
        lresult := pack_import_department.cfbimport_departments(x.customernumber);
        lcount  := lcount + lresult;
      exception
        when others then
          pack_import.write_log('Error convert_i_department during loop: ' ||
                                substr(sqlerrm, 1, 200));
      end;
    end loop; --x
    if lcount > 0 then
      pack_import.write_log(lcount || ' extra department rows imported.');
    end if;
    --convert_i_nobudgetdepartment
    convert_i_nobudgetdepartment;
    --get missing consumtionpoints
    convert_i_consumptionpoints;
  exception
    when others then
      begin
        pack_import.write_log('Error convert_i_department: ' || substr(sqlerrm, 1, 200));
      end;
  end convert_i_department;
  procedure convert_i_nobudgetdepartment is
    lv_counter         number := 0;
    lv_customerid      customer.customer_id%type;
    lv_departmentid    department.department_id%type;
    lv_custbudgetdefid customerbudgetdefinition.customerbudgetdefinition_id%type;
  begin
    --convert_i_nobudgetdepartment
    lvnerrormsg := 'convert_i_nobudgetdepartment';
    for xnd in (select * from i_nobudgetdepartment) loop
      begin
        --get customer
        lvnerrormsg := 'convert_i_nobudgetdepartment get customer ' || xnd.customernumber;
        select c.customer_id
        into   lv_customerid
        from   customer c
        where  c.customernumber = xnd.customernumber;
        --get department
        lvnerrormsg := 'convert_i_nobudgetdepartment get department ' || xnd.departmentnumber ||
                       ' for customer ' || xnd.customernumber;
        select t.department_id
        into   lv_departmentid
        from   department t
        where  t.customer_id = lv_customerid
        and    t.departmentnumber = xnd.departmentnumber;
        --get customer budgetdefinition
        lvnerrormsg := 'get customer budgetcode ' || xnd.budgetcode || ' for customer ' ||
                       xnd.customernumber;
        select cbd.customerbudgetdefinition_id
        into   lv_custbudgetdefid
        from   customerbudgetdefinition cbd
        where  cbd.customer_id = lv_customerid
        and    cbd.code = xnd.budgetcode;
        --insert into nobudgetdepartment
        lvnerrormsg := 'insert into nobudgetdepartment';
        insert into nobudgetdepartment
          (customerbudgetdefinition_id, department_id, systemuser_id, timestamp)
        values
          (lv_custbudgetdefid, lv_departmentid, pack_import.lvnsystemuserid, sysdate);
        --count
        lv_counter := lv_counter + 1;
      exception
        when no_data_found then
          pack_import.write_log('Error during import nobudgetdepartment, no data found ' ||
                                lvnerrormsg, 3);
        when dup_val_on_index then
          null; --no problem if it is already there
      end;
    end loop; --xnd
    commit;
    if lv_counter > 0 then
      pack_import.write_log(lv_counter || ' nobudgetdepartment rows imported.');
    end if;
  exception
    when others then
      begin
        rollback;
        lvnerrormsg := 'convert_i_nobudgetdepartment: Failed to import.';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end convert_i_nobudgetdepartment;
  procedure convert_costcentergroup(fp_customernumber in customer.customernumber%type default null) is
    lv_addcount number := 0;
  begin
    --convert_costcentergroup
    for y in (select c.customer_id, cc.costcentergroupcode,
                     max(cc.costcentergroupdescription) costcentergroupdescription
              from   i_costcenter cc
              join   customer c
              on     c.customernumber = cc.customernumber
              where  cc.costcentergroupcode is not null
              and    (c.customernumber = fp_customernumber or fp_customernumber is null)
              and    not exists (select 1
                      from   costcentergroup ccg
                      where  ccg.code = cc.costcentergroupcode
                      and    ccg.customer_id = c.customer_id)
              group  by c.customer_id, cc.costcentergroupcode) loop
      begin
        insert into costcentergroup
          (costcentergroup_id, customer_id, code, description, invoiceaddress_id, contactperson_id,
           systemuser_id, timestamp)
        values
          (seq_costcentergroup.nextval, y.customer_id, y.costcentergroupcode,
           nvl(y.costcentergroupdescription, y.costcentergroupcode), null /*invoiceaddress_id*/,
           null /*contactperson_id*/, pack_import.lvnsystemuserid, sysdate);
        --count added records
        lv_addcount := lv_addcount + 1;
      end;
    end loop;
    if lv_addcount > 0 then
      begin
        pack_import.write_log('Imported ' || to_char(lv_addcount) || ' costcentergroup(s)' || case when
                              fp_customernumber is not null then
                              ' for cust# ' || to_char(fp_customernumber) else ' ' end, 1);
      end;
    end if;
  exception
    when others then
      begin
        pack_import.write_log('Error during convert_costcentergroup ' || substr(sqlerrm, 1, 512), 3);
      end;
  end convert_costcentergroup;
  procedure convert_costcenter is
    lcount                  number := 0;
    lcountadd               number := 0;
    fpncostcenter_id        costcenter.costcenter_id%type;
    fpndistributionpoint_id distributionpoint.distributionpoint_id%type;
    fpndeliverypoint_id     deliverypoint.deliverypoint_id%type;
    fpnstandarddelivery_id  standarddelivery.standarddelivery_id%type;
    lvntransportarticle_id  transportarticle.transportarticle_id%type;
  begin
    --initialization
    select min(transportarticle_id) into lvntransportarticle_id from transportarticle;
    --convert_costcentergroup
    convert_costcentergroup;
    --conversion of costcenters from i_costcenter
    for x in (select i.consumptionpointnumber, i.costcentercode, i.costcenterdescription,
                     c.customer_id, d.department_id, i.deliverypointcode, c.visitaddress_id,
                     i.ponumber, i.requisitionnumber, i.accountingstring, i.eannumber, i.exportedi,
                     ccg.costcentergroup_id
              from   i_costcenter i
              join   customer c
              on     c.customernumber = i.customernumber
              join   department d
              on     (d.customer_id = c.customer_id and d.departmentnumber = i.departmentnumber)
              left   outer join costcentergroup ccg
              on     (ccg.customer_id = c.customer_id and ccg.code = i.costcentergroupcode)) loop
      begin
        begin
          select cc.costcenter_id
          into   fpncostcenter_id
          from   costcenter cc
          where  cc.code = x.costcentercode
          and    cc.customer_id = x.customer_id;
        exception
          when no_data_found then
            begin
              pack_import.cfbcreate_costcenter(fpncostcenter_id, x.costcentercode,
                                               x.costcenterdescription, x.customer_id, null, null,
                                               x.ponumber, x.requisitionnumber, x.accountingstring,
                                               x.eannumber, x.exportedi, x.costcentergroup_id);
              lcountadd := lcountadd + 1;
            end;
        end;
        begin
          select d.distributionpoint_id
          into   fpndistributionpoint_id
          from   distributionpoint d
          where  d.department_id = x.department_id
          and    d.distributionpointnumber = x.consumptionpointnumber;
          update distributionpoint p
          set    p.costcenter_id = fpncostcenter_id
          where  p.distributionpoint_id = fpndistributionpoint_id
          and    p.costcenter_id <> fpncostcenter_id;
        exception
          when no_data_found then
            begin
              begin
                select p.deliverypoint_id
                into   fpndeliverypoint_id
                from   deliverypoint p
                where  p.customer_id = x.customer_id
                and    p.code = x.deliverypointcode;
              exception
                when no_data_found then
                  begin
                    -- inserting the delivery and distributionpoints.
                    pack_import.cfbcreate_deliverypoint(fpndeliverypoint_id,
                                                        --fpndeliverypoint_id,
                                                        x.customer_id,
                                                        --fpncustomer_id,
                                                        x.deliverypointcode,
                                                        --fpscode,
                                                        x.costcenterdescription,
                                                        --fpsdescription,
                                                        x.visitaddress_id,
                                                        --fpndeliveryaddressid,
                                                        null); --fpssortaddress
                  end;
              end;
              begin
                pack_import.cfbcreate_distributionpoint(fpndistributionpoint_id,
                                                        --fpndistributionpoint_id,
                                                        x.consumptionpointnumber,
                                                        --fpndistributionpointnumber,
                                                        x.costcenterdescription,
                                                        --fpsdescription,
                                                        null,
                                                        --fpsremarkonpackingnote,
                                                        null,
                                                        --fpsremarkondeliverynote,
                                                        to_date('31-12-2099', 'DD-MM-YYYY'),
                                                        --fpdtpackremarkenddate,
                                                        to_date('31-12-2099', 'DD-MM-YYYY'),
                                                        --fpdtdeliverremarkenddate,
                                                        'Y',
                                                        --fpsactive,
                                                        x.department_id,
                                                        --fpndepartment_id,
                                                        fpndeliverypoint_id,
                                                        --fpndeliverypoint_id,
                                                        fpncostcenter_id,
                                                        --fpncostcenter_id,
                                                        null, 'N', null);
                pack_import.cfbcreate_standarddelivery(fpnstandarddelivery_id, 1, 'N', null, 'N',
                                                       lvntransportarticle_id, 'N', 1,
                                                       fpndistributionpoint_id, null, 'N', 'N', null);
              end;
            end;
        end;
        update department d
        set    d.costcenter_id = fpncostcenter_id
        where  d.department_id = x.department_id
        and    d.costcenter_id <> fpncostcenter_id;
        lcount := lcount + 1;
      end;
    end loop;
    if lcount > 0 then
      begin
        pack_import.write_log(lcountadd || ' costcenter rows imported.');
        pack_import.write_log('ready convert_costcenter #' || lcount || ' costcenters checked');
      end;
    end if;
  exception
    when others then
      begin
        pack_import.write_log('Error convert_costcenter: ' || substr(sqlerrm, 1, 512), 3);
      end;
  end convert_costcenter;
begin
  --initialization
  for x in (select distinct trim(i.transportarticlecode) transportarticlecode
            from   i_consumptionpoint i
            where  ltrim(rtrim(i.transportarticlecode)) is not null
            and    not exists (select a.transportarticle_id
                    from   transportarticle a
                    where  a.code = i.transportarticlecode)) loop
    begin
      -- add transport articles.
      pack_import.cfbcreate_transportarticle(fpntransportarticle_id, x.transportarticlecode, 'N',
                                             x.transportarticlecode);
    exception
      when others then
        null; -- could not created, no problem.
    end;
  end loop;
  commit;
end pack_import_department;
/
create or replace package pack_import_dvariation is
  -- Author  : TATIANA
  -- Created : 4/11/2003 6:38:35 PM
  -- Version : 1.0
  -- Purpose : CONVERSION US
  -- Changed : 7-may-2003 added   procedure CFbMisccharges;
  -- Public function and procedure declarations
  procedure cfbdeliveryvariations;
  procedure cfbmisccharges;
end pack_import_dvariation;
/
create or replace package body pack_import_dvariation is
  errormsg  varchar2(256);
  countrows integer;
  procedure cfbdeliveryvariations is
    deliveryvariationsid deliveryvariations.deliveryvariations_id%type;
    updaterentquantity   varchar2(1);
    fpnreasoncode_id     reasoncode.reasoncode_id%type;
  begin
    update i_deliveryvariation
    set    productcode = ltrim(rtrim(productcode)), sizecode = ltrim(rtrim(sizecode)),
           finishingmethodcode = ltrim(rtrim(finishingmethodcode));
    countrows := 0;
    for vcursor in (select a.*, p.product_id, s.sizedefinition_id, f.finishingmethod_id,
                           d2.distributionpoint_id, c.defaultbusinessunit_id,
                           bup.businessunit_id procbusinessunit_id,
                           bui.businessunit_id intbusinessunit_id
                    from   i_deliveryvariation a
                    join   customer c
                    on     a.customernumber = c.customernumber
                    join   product p
                    on     p.code = a.productcode
                    join   department_link k
                    on     (k.customer_link_id = c.customer_id and
                           k.departmentnumber = a.departmentnumber)
                    join   sizedefinition s
                    on     s.code = a.sizecode
                    join   finishingmethod f
                    on     f.code = a.finishingmethodcode
                    join   distributionpoint d2
                    on     (d2.distributionpointnumber = a.consumptionpointnumber and
                           d2.department_id = k.department_id)
                    left   outer join businessunit bup
                    on     bup.code = a.processbusinessunitcode
                    left   outer join businessunit bui
                    on     bui.code = a.internalbusinessunitcode
                    where  not exists (select d.deliveryvariations_id
                            from   deliveryvariations d
                            where  d.product_id = p.product_id
                            and    d.sizedefinition_id = s.sizedefinition_id
                            and    d.finishingmethod_id = f.finishingmethod_id
                            and    d.distributionpoint_id = d2.distributionpoint_id
                            and    d.deliverydate = a.deliverydate)) loop
      begin
        if vcursor.adjustmentreason is null then
          begin
            updaterentquantity := 'N';
            fpnreasoncode_id   := null;
          end;
        else
          begin
            -- Determine the reason code.
            updaterentquantity := 'Y';
            select r.reasoncode_id
            into   fpnreasoncode_id
            from   reasoncode r
            where  r.garmentreason = 'Y'
            and    r.code = vcursor.adjustmentreason;
          exception
            when no_data_found then
              begin
                pack_import.cfbcreate_reasoncode(fpnreasoncode_id,
                                                 --fpnreasoncode_id,
                                                 vcursor.adjustmentreason,
                                                 --fpscode,
                                                 'N',
                                                 --fpsinternetselectable,
                                                 'Y',
                                                 --fpsallowprepcharges,
                                                 'Y',
                                                 --fpsgarmentreason,
                                                 'Y',
                                                 --fpslinenreason,
                                                 'N',
                                                 --fpsexporttohandheld,
                                                 0,
                                                 --fpncancelinvoice,
                                                 'N',
                                                 --fpsaffectsnextinvoice,
                                                 'N',
                                                 --fpsaffectscurrentinvoice,
                                                 0,
                                                 --fpninvoiceadjustment,
                                                 'N',
                                                 --fpsfirstissue,
                                                 0,
                                                 --fpninventorytrigger,
                                                 'Y',
                                                 --fpschargeresidualvalue
                                                 'N'
                                                 --fpschargerestockingfee
                                                 );
                pack_import.cfbcreate_reasoncode_desc(fpnreasoncode_id,
                                                      --fpnreasoncode_id,
                                                      vcursor.adjustmentreason);
              end;
          end;
        end if; -- End reason code.
        pack_import.cfbcreate_deliveryvariations(deliveryvariationsid, vcursor.product_id,
                                                 vcursor.deliverydate, vcursor.origin,
                                                 vcursor.quantity, vcursor.finishingmethod_id,
                                                 vcursor.fixedquantity, vcursor.distributionpoint_id,
                                                 null,
                                                 --.PACKINGNOTE_ID,
                                                 vcursor.sizedefinition_id, vcursor.reference,
                                                 vcursor.processed, null,
                                                 --.causenote_id,
                                                 updaterentquantity, fpnreasoncode_id,
                                                 coalesce(vcursor.procbusinessunit_id,
                                                           vcursor.defaultbusinessunit_id),
                                                 coalesce(vcursor.intbusinessunit_id,
                                                           vcursor.procbusinessunit_id,
                                                           vcursor.defaultbusinessunit_id));
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'Fail to import deliveryvariations for customernumber/consumptionpoint/product/size/fin/date ' ||
                      vcursor.customernumber || '/' || vcursor.consumptionpointnumber || '/' ||
                      vcursor.productcode || '/' || vcursor.sizecode || '/' ||
                      vcursor.finishingmethodcode || '/' || vcursor.deliverydate;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(countrows || ' deliveryvariations rows imported.');
    end if;
  end cfbdeliveryvariations;
  procedure cfbmisccharges is
    fpnmiscellaneouscharge_id miscellaneouscharge.miscellaneouscharge_id%type;
    fpncostcenterid           costcenter.costcenter_id%type;
  begin
    -- turnovergroup
    for x in (select i.turnovergroupcode
              from   i_misccharge i
              where  not exists (select t.turnovergroup_id
                      from   turnovergroup t
                      where  t.code = i.turnovergroupcode)
              group  by i.turnovergroupcode) loop
      begin
        insert into turnovergroup
          (turnovergroup_id, salesjournalgroup_id, code, legacycode, active, systemuser_id,
           timestamp)
        values
          (seq_turnovergroup.nextval, pack_import.lvnsalesjournalgroupminusid, x.turnovergroupcode,
           null, 'Y', pack_import.lvnsystemuserid, sysdate);
        insert into turnovergroup_desc
          (turnovergroup_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_turnovergroup.currval, pack_import.lvnlanguageid, x.turnovergroupcode,
           pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      exception
        when others then
          errormsg := 'Pack_import_dvariation.cfbmisccharges: Fail to import turnovergroup code ' ||
                      x.turnovergroupcode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    countrows := 0;
    for x in (select c.customer_id, i.creationdate, i.description, t.turnovergroup_id, i.quantity,
                     i.price, i.discountpercentage, i.amount, i.chargestatus, g.taxgroup_id,
                     c.customernumber, b.businessunit_id, i.costcenter
              from   i_misccharge i
              inner  join customer c
              on     i.deltocustnumber = c.customernumber
              inner  join businessunit b
              on     b.code = i.businessunitnumber
              inner  join plant p
              on     p.plant_id = b.plant_id
              left   outer join turnovergroup t
              on     t.code = i.turnovergroupcode
              left   outer join taxgroup g
              on     g.code = i.taxgroupcode
              and    g.country_id = p.country_id
              where  not exists (select m.miscellaneouscharge_id
                      from   miscellaneouscharge m, businessunit b
                      where  m.customer_link_id = c.customer_id
                      and    b.businessunit_id = m.invoicebusinessunit_id
                      and    b.code = i.businessunitnumber)) loop
      begin
        --get costcenter if needed
        if x.costcenter is null then
          fpncostcenterid := null;
        else
          begin
            select cc.costcenter_id
            into   fpncostcenterid
            from   costcenter cc
            where  cc.customer_id = x.customer_id
            and    cc.code = x.costcenter;
          end;
        end if;
        pack_import.cfbcreate_miscellaneouscharge(fpnmiscellaneouscharge_id,
                                                  --fpnmiscellaneouscharge_id,
                                                  x.businessunit_id,
                                                  --fpninvoicebusinessunit_id,
                                                  x.customer_id,
                                                  --fpncustomer_link_id,
                                                  x.creationdate,
                                                  --fpdtcreationdate,
                                                  x.description,
                                                  --fpsdescription,
                                                  x.turnovergroup_id,
                                                  --fpnturnovergroup_id,
                                                  null,
                                                  --fpninvoiceheader_id,
                                                  x.quantity,
                                                  --fpnquantity,
                                                  x.price,
                                                  --fpnprice,
                                                  x.discountpercentage,
                                                  --fpndiscountpercentage,
                                                  x.amount,
                                                  --fpnamount,
                                                  x.chargestatus,
                                                  --fpnchargestatus,
                                                  x.taxgroup_id,
                                                  --fpntaxgroup_id,
                                                  fpncostcenterid);
        countrows := countrows + 1;
      exception
        when others then
          begin
            pack_import.write_log('Error during loop: ' || substr(sqlerrm, 1, 512), -3);
          end;
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(countrows || ' miscellaneouscharge rows imported.');
    end if;
  exception
    when others then
      begin
        pack_import.write_log('Insert miscellaneouscharge failed. Error: ' ||
                              substr(sqlerrm, 1, 512), 3);
      end;
  end cfbmisccharges;
end pack_import_dvariation;
/
create or replace package pack_import_emblem is
  -- Author  : PVD
  -- Created : 28-nov-2003 10:18:18
  -- Version : 1.0
  -- Updated : 24-Jul-2018 added color desc
  function cfbdeterminecolor(fp_color_code        in color.code%type,
                             fp_color_description in varchar2 default null) return number;
  procedure cfbimport_emblemtemplate;
  procedure cfbimport_standardinventory;
  procedure cfbimportemblems;
end pack_import_emblem;
/
create or replace package body pack_import_emblem is
  function cfbdeterminecolor(fp_color_code        in color.code%type,
                             fp_color_description in varchar2 default null) return number is
    fpncolor_id number;
  begin
    if fp_color_code is not null then
      begin
        -- determine the color.
        select c.color_id into fpncolor_id from color c where c.code = fp_color_code;
        -- make use for emblems.
        update color c set c.usedforemblem = 'Y' where c.color_id = fpncolor_id;
      exception
        when no_data_found then
          -- add color if it does not already exist.
          pack_import.cfbcreate_color(fpncolor_id,
                                      --fpncolor_id,
                                      fp_color_code,
                                      --fpscode,
                                      null,
                                      --fpsralcode,
                                      'Y'); --fpsusedforemblem);
          pack_import.cfbcreate_color_desc(fpncolor_id,
                                           --fpncolor_id,
                                           nvl(fp_color_description, fp_color_code)
                                           --fpsdescription,
                                           );
      end;
    else
      fpncolor_id := null;
    end if;
    return(fpncolor_id);
  end cfbdeterminecolor;
  procedure cfbimport_emblemtemplate is
    lcounter                   number := 0;
    lcounterline               number := 0;
    lcustomerid                customer.customer_id%type;
    lproductid                 product.product_id%type;
    lsizeid                    sizedefinition.sizedefinition_id%type;
    lemblemtemplateid          emblemtemplate.emblemtemplate_id%type;
    lemblemtemplatelineid      emblemtemplateline.emblemtemplateline_id%type;
    lemblemtemplinepriceid     emblemtemplatelineprice.emblemtemplatelineprice_id%type;
    lfabricid                  fabric.fabric_id%type;
    lplacement_id              placement.placement_id%type;
    lemblemfontid              emblemfont.emblemfont_id%type;
    lerror                     varchar2(155);
    limportyn                  varchar2(1);
    fpnpricelistpercustomer_id pricelistpercustomer.pricelistpercustomer_id%type;
    lv_embroiderylettering     emblemtemplate.embroidery%type;
  begin
    for x in (select i.*, rowid from i_emblemtemplate i where i.emblemtemplateline_id is null) loop
      begin
        limportyn := 'Y';
        --customer
        lerror := ' customer ' || x.customernumber;
        select c.customer_id
        into   lcustomerid
        from   customer c
        where  c.customernumber = x.customernumber;
        --product
        lerror := ' emblem product ' || x.productcode;
        if x.productcode is null then
          lproductid := null;
        else
          begin
            select p.product_id
            into   lproductid
            from   product p, emblemproduct ep
            where  p.code = x.productcode
            and    p.product_id = ep.product_id;
          exception
            when no_data_found then
              begin
                pack_import.write_log('Error cfbimport_emblemtemplate: ' || lerror ||
                                      ' not found! Not imported template ' || x.templatecode);
                limportyn := 'N';
              end;
          end;
        end if; --productid
        begin
          --size
          lerror := ' size ' || x.sizecode;
          select s.sizedefinition_id into lsizeid from sizedefinition s where s.code = x.sizecode;
        exception
          when no_data_found then
            begin
              pack_import.cfbcreate_sizedefinition(lsizeid, x.sizecode, 'N', null, null, null, 'Y');
              pack_import.cfbcreate_sizedefinition_desc(lsizeid, x.sizecode);
            end;
        end;
        --fabric
        begin
          lerror := ' fabric ' || x.fabriccode;
          select f.fabric_id into lfabricid from fabric f where f.code = x.fabriccode;
        exception
          when no_data_found then
            begin
              -- Call the procedure to add fabric
              pack_import.cfbcreate_fabric(lfabricid, x.fabriccode, 'Y');
              pack_import.cfbcreate_fabric_desc(lfabricid, x.fabriccode);
            end;
        end;
        -- determine the placement if it is not null.
        lerror := ' placement ' || x.placementcode;
        if x.placementcode is null then
          lplacement_id := null;
        else
          begin
            select p.placement_id
            into   lplacement_id
            from   placement p
            where  p.code = x.placementcode;
          exception
            when no_data_found then
              begin
                pack_import.cfbcreate_placement(lplacement_id, x.placementcode);
                pack_import.cfbcreate_placement_desc(lplacement_id, x.placementdescription);
              end;
          end;
        end if;
        --emblemfont
        lerror := ' emblemfontdescription ' || x.emblemfontdescription;
        if x.emblemfontdescription is null then
          lemblemfontid := null;
        else
          begin
            select f.emblemfont_id
            into   lemblemfontid
            from   emblemfont f
            where  upper(f.description) = upper(x.emblemfontdescription);
          exception
            when others then
              begin
                begin
                  insert into emblemfont
                    (emblemfont_id, description, active, systemuser_id, timestamp)
                  values
                    (seq_emblemfont.nextval, x.emblemfontdescription, 'Y',
                     pack_import.lvnsystemuserid, sysdate)
                  returning emblemfont_id into lemblemfontid;
                exception
                  when others then
                    begin
                      pack_import.write_log(' insert into emblemfont failed: ' ||
                                            substr(sqlerrm, 1, 512), 3);
                      lemblemfontid := null;
                    end;
                end;
              end;
          end;
        end if;
        if limportyn = 'Y' then
          begin
            --find or create the right template
            lerror := ' template ' || x.templatecode;
            begin
              select t.emblemtemplate_id, t.embroidery
              into   lemblemtemplateid, lv_embroiderylettering
              from   emblemtemplate t
              where  t.code = x.templatecode
              and    t.customer_id = lcustomerid;
              if nvl(x.embroiderylettering, 'N') = 'Y' and lv_embroiderylettering = 'N' then
                begin
                  update emblemtemplate t
                  set    t.embroidery = 'Y'
                  where  t.embroidery = 'N'
                  and    t.timestamp > (sysdate - 2 / 24)
                  and    t.emblemtemplate_id = lemblemtemplateid;
                end;
              end if;
            exception
              when no_data_found then
                begin
                  --create
                  insert into emblemtemplate
                    (emblemtemplate_id, customer_id, code, description, systemuser_id, timestamp,
                     printnamelabel, active, rentemblem, embroidery)
                  values
                    (seq_emblemtemplate.nextval, lcustomerid, x.templatecode, x.templatedescription,
                     pack_import.lvnsystemuserid, sysdate, x.printnamelabel, 'Y', x.rentemblem,
                     nvl(x.embroiderylettering, 'N'))
                  returning emblemtemplate_id into lemblemtemplateid;
                end;
            end;
            --template price add if not null
            if x.templaterentprice is not null then
              begin
                insert into emblemtemplateprice
                  (emblemtemplateprice_id, emblemtemplate_id, startdate, price, systemuser_id,
                   timestamp)
                values
                  (seq_emblemtemplateprice.nextval, lemblemtemplateid, trunc(sysdate) - 1,
                   x.templaterentprice, pack_import.lvnsystemuserid, sysdate);
                lcounter := lcounter + 1;
              exception
                when dup_val_on_index then
                  null;
              end;
            end if;
            --create emblemtemplate line
            insert into emblemtemplateline
              (emblemtemplateline_id, emblemtemplate_id, product_id, sizedefinition_id, description,
               textcolor_id, bordercolor_id, bkgcolor_id, fabric_id, placement_id, emblemtype,
               attachmentby, qtypergarment, systemuser_id, timestamp, emblemfont_id, fontsize,
               embroideryfilepathoriginal, embroideryfilepathproduction, stitchcount, setupfee,
               colorpalette, embroiderylettering, embroideryletteringline1, embroideryletteringline2,
               embroideryletteringline3, customcolor, customsize, description2, stylecode,
               customersupplied)
            values
              (seq_emblemtemplateline.nextval, lemblemtemplateid, lproductid, lsizeid,
               x.description, cfbdeterminecolor(x.textcolorcode),
               cfbdeterminecolor(x.bordercolorcode), cfbdeterminecolor(x.backgroundcolorcode),
               lfabricid, lplacement_id, x.emblemtype, x.attachmentby, x.qtypergarment,
               pack_import.lvnsystemuserid, sysdate, lemblemfontid, x.fontsize,
               x.embroideryfilepathoriginal, x.embroideryfilepathproduction, x.stitchcount,
               x.setupfee, x.colorpalette, nvl(x.embroiderylettering, 'N'),
               x.embroideryletteringline1, x.embroideryletteringline2, x.embroideryletteringline3,
               x.customcolor, x.customsize, x.description2, x.stylecode, x.customersupplied)
            returning emblemtemplateline_id into lemblemtemplatelineid;
            --emblem template line price
            if x.price is not null then
              begin
                pack_import.cfbcreate_emblemtemplineprice(lemblemtemplinepriceid,
                                                          lemblemtemplatelineid, x.price,
                                                          trunc(sysdate) - 1);
              exception
                when dup_val_on_index then
                  null;
              end;
            end if;
            begin
              pack_import.cfbcreate_pricelistpercustomer(fpnpricelistpercustomer_id,
                                                         --fpnpricelistpercustomer_id,
                                                         lcustomerid,
                                                         --fpncustomer_id,
                                                         7,
                                                         --fpnpricetype,
                                                         null,
                                                         --fpngeneralpricelist_id,
                                                         null,
                                                         --fpnpriority,
                                                         trunc(sysdate) - 1,
                                                         --fpdtdateactive,
                                                         to_date('31-12-2099', 'DD-MM-YYYY'),
                                                         --fpdtdateinactive,
                                                         null, null, null);
            exception
              when dup_val_on_index then
                null;
            end;
            lerror := 'update i_emblemtemplate';
            update i_emblemtemplate t
            set    t.emblemtemplateline_id = lemblemtemplatelineid
            where  t.rowid = x.rowid;
            --counter
            lcounterline := lcounterline + 1;
          end;
        end if; --- limportyn = 'Y'
      exception
        when dup_val_on_index then
          null; --did already exist no problem
        when others then
          pack_import.write_log('Error cfbimport_emblemtemplate: ' || lerror ||
                                substr(sqlerrm, 1, 512), -3);
      end;
    end loop; --x
    commit;
    if lcounter > 0 then
      pack_import.write_log(lcounter || ' emblem template rows imported.');
    end if;
    if lcounterline > 0 then
      pack_import.write_log(lcounterline || ' emblem template line rows imported.');
    end if;
  exception
    when others then
      rollback;
      pack_import.write_log('Error cfbimport_emblemtemplate: ' || lerror ||
                            substr(sqlerrm, 1, 512), 3);
  end cfbimport_emblemtemplate;
  procedure cfbimport_standardinventory is
    lcounter          number := 0;
    lcustomerid       customer.customer_id%type;
    lproductid        product.product_id%type;
    lfunctionid       wearerfunction.wearerfunction_id%type;
    lemblemtemplateid emblemtemplate.emblemtemplate_id%type;
    lerror            varchar2(155);
  begin
    for x in (select * from i_standardinventory) loop
      begin
        --customer
        lerror := ' customer ' || x.customernumber;
        select c.customer_id
        into   lcustomerid
        from   customer c
        where  c.customernumber = x.customernumber;
        --product
        lerror := ' product ' || x.productcode;
        select p.product_id into lproductid from product p where p.code = x.productcode;
        --template
        lerror := ' template ' || x.templatecode;
        if x.templatecode is null then
          lemblemtemplateid := null;
        else
          begin
            select t.emblemtemplate_id
            into   lemblemtemplateid
            from   emblemtemplate t
            where  t.code = x.templatecode
            and    t.customer_id = lcustomerid;
          exception
            when no_data_found then
              begin
                lemblemtemplateid := null;
                pack_import.write_log('  template ' || x.templatecode || ' not found ' ||
                                      ' for customer/function ' || x.customernumber || '/' ||
                                      x.functioncode);
              end;
          end;
        end if;
        --wearer function
        lerror := ' wearerfunction ' || x.functioncode;
        begin
          select f.wearerfunction_id
          into   lfunctionid
          from   wearerfunction f
          where  f.customer_id = lcustomerid
          and    f.code = x.functioncode;
        exception
          when no_data_found then
            begin
              insert into wearerfunction
                (wearerfunction_id, customer_id, code, description, defaultdispensecredit,
                 systemuser_id, timestamp)
              values
                (seq_wearerfunction.nextval, lcustomerid, x.functioncode, x.functiondescription, 0,
                 pack_import.lvnsystemuserid, sysdate)
              returning wearerfunction_id into lfunctionid;
            end;
        end;
        begin
          --standard inventory
          insert into standardinventory
            (standardinventory_id, wearerfunction_id, product_id, emblemtemplate_id, putinuse,
             changesperweek, systemuser_id, timestamp, dispensecredit)
          values
            (seq_standardinventory.nextval, lfunctionid, lproductid, lemblemtemplateid,
             x.maxinventory, x.changesperweek, pack_import.lvnsystemuserid, sysdate, 0);
        exception
          when dup_val_on_index then
            null;
            --ignore already existing lines
        end;
        --counter
        lcounter := lcounter + 1;
      end;
    end loop;
    commit;
    if lcounter > 0 then
      pack_import.write_log(lcounter || ' standard inventory rows imported.');
    end if;
  exception
    when others then
      rollback;
      pack_import.write_log('Error cfbimport_standardinventory: ' || lerror ||
                            substr(sqlerrm, 1, 512), 3);
  end cfbimport_standardinventory;
  procedure cfbimportemblems is
    fpnfinishingmethod_id         finishingmethod.finishingmethod_id%type;
    fpnsizedefinition_id          sizedefinition.sizedefinition_id%type;
    fpnemblemtemplate_id          emblemtemplate.emblemtemplate_id%type;
    fpnemblemtemplateline_id      emblemtemplateline.emblemtemplateline_id%type;
    fpnemblemtemplatelineprice_id emblemtemplatelineprice.emblemtemplatelineprice_id%type;
    fpnfabric_id                  fabric.fabric_id%type;
    fpnpricelistpercustomer_id    pricelistpercustomer.pricelistpercustomer_id%type;
  begin
    -- Determine default values such as size and finishingmethod.
    select f.finishingmethod_id
    into   fpnfinishingmethod_id
    from   finishingmethod f
    where  f.code = '-';
    select s.sizedefinition_id into fpnsizedefinition_id from sizedefinition s where s.code = '-';
    select f.fabric_id into fpnfabric_id from fabric f where f.code = '-';
    -- Add emblem products.
    for x in (select p.product_id
              from   i_emblem e, product p
              where  p.code = e.code
              group  by p.product_id) loop
      begin
        pack_import.cfbcreate_emblemproduct(x.product_id,
                                            --fpnproduct_id,
                                            3,
                                            --fpnemblemtype,
                                            null,
                                            --fpntextcolor_id,
                                            null,
                                            --fpnbordercolor_id,
                                            null);
        -- when it already exists no problem.
      exception
        when dup_val_on_index then
          null;
      end;
    end loop;
    -- Make all emblems, typeofmerchandise 4, meaning emblems.
    update product p
    set    p.typeofmerchandise = 4
    where  p.product_id in (select e.product_id from emblemproduct e);
    -- Add emblems to customer.
    for x in (select c.customer_id, p.product_id, e.price, c.dateactive
              from   i_emblem e, customer c, product p
              where  c.customernumber = e.customernumber
              and    p.code = e.code) loop
      begin
        -- determine customer template.
        select min(t.emblemtemplate_id)
        into   fpnemblemtemplate_id
        from   emblemtemplate t
        where  t.customer_id = x.customer_id
        and    t.code = '1';
        if fpnemblemtemplate_id is null then
          --not found so create it.
          pack_import.cfbcreate_emblemtemplate(fpnemblemtemplate_id,
                                               --fpnemblemtemplate_id,
                                               x.customer_id,
                                               --fpncustomer_id,
                                               '1',
                                               --fpscode,
                                               '-',
                                               --fpsdescription,
                                               'N',
                                               --fpsprintnamelabel,
                                               'Y',
                                               --fpsactive,
                                               'N'); --fpsrentemblem
        end if;
        begin
          pack_import.cfbcreate_emblemtemplateline(fpnemblemtemplateline_id,
                                                   --fpnemblemtemplateline_id,
                                                   fpnemblemtemplate_id,
                                                   --fpnemblemtemplate_id,
                                                   x.product_id,
                                                   --fpnproduct_id,
                                                   fpnsizedefinition_id,
                                                   --fpnsizedefinition_id,
                                                   8,
                                                   --fpnfontsize
                                                   '-',
                                                   --fpsdescription,
                                                   null,
                                                   --fpntextcolor_id,
                                                   null,
                                                   --fpnbordercolor_id,
                                                   null,
                                                   --fpnbkgcolor_id,
                                                   fpnfabric_id,
                                                   --fpnfabric_id,
                                                   null,
                                                   --fpnplacement_id,
                                                   3,
                                                   --fpnemblemtype,
                                                   1,
                                                   --fpnattachmentby,
                                                   1,
                                                   --fpnqtypergarment,
                                                   null,
                                                   --fpnemblemimage_id,
                                                   null,
                                                   --fpnplacementimage_id,
                                                   null);
          pack_import.cfbcreate_emblemtemplineprice(fpnemblemtemplatelineprice_id,
                                                    --fpnemblemtemplatelineprice_id,
                                                    fpnemblemtemplateline_id,
                                                    --fpnemblemtemplateline_id,
                                                    x.price,
                                                    --fpnprice,
                                                    x.dateactive
                                                    --fpdtstartdate,
                                                    );
          pack_import.cfbcreate_pricelistpercustomer(fpnpricelistpercustomer_id,
                                                     --fpnpricelistpercustomer_id,
                                                     x.customer_id,
                                                     --fpncustomer_id,
                                                     7,
                                                     --fpnpricetype,
                                                     null,
                                                     --fpngeneralpricelist_id,
                                                     null,
                                                     --fpnpriority,
                                                     x.dateactive,
                                                     --fpdtdateactive,
                                                     to_date('31-12-2099', 'DD-MM-YYYY'),
                                                     --fpdtdateinactive,
                                                     null, null, null);
        exception
          when dup_val_on_index then
            null; -- when it already exists no problem.
        end;
      end;
    end loop;
    commit;
    --insert into i_emblemtemplate
    insert into i_emblemtemplate
      (customernumber, templatecode, templatedescription, sizecode, fabriccode)
      select i.customernumber, i.templatecode, i.templatecode, '-', '-'
      from   i_standardinventory i
      where  i.templatecode is not null
      and    not exists (select t.customernumber, t.templatecode
              from   i_emblemtemplate t
              where  t.templatecode = i.templatecode
              and    t.customernumber = i.customernumber)
      group  by i.templatecode, i.customernumber;
    commit;
    --call other emblem functions.
    cfbimport_emblemtemplate;
    cfbimport_standardinventory;
    pack_import.write_log('Import_Emblems succeeded.');
  exception
    when others then
      rollback;
      pack_import.write_log('Import_Emblems failed: ' || substr(sqlerrm, 1, 512), 3);
  end cfbimportemblems;
end pack_import_emblem;
/
create or replace package pack_import_eu is
  -- Author  : ABS
  -- Created : 23-jun-2003
  -- Version : 1.0
  -- Purpose : Based upon PACK_IMPORT_US.
  procedure cfbimporteu_1;
  procedure cfbimporteu_2;
  procedure cfbimporteu_3;
  procedure cfbimporteu_4;
  procedure cfbimporteu_5;
  procedure cfbimporteu_6;
  procedure cfbimporteu_7;
  procedure cfbimporteu_8;
  procedure cfbimporteu_9;
  procedure cfbimporteu_10;
  procedure cfbimporteu_11;
end pack_import_eu;
/
create or replace package body pack_import_eu is
  procedure cfbimporteu_1 is
  begin
    -- import products and related info.
    pack_import.write_log('***** Start conversion *****');
    pack_import.write_log('***** Begin import 1, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
    --Import plants and businessunits
    pack_import_businessunit.import_all;
    --Import porducts
    pack_import_customer.cfbimporttaxauthorities;
    commit;
    pack_import_product.cfbimportproduct;
    pack_import_product.cfbimportemblemproduct;
    pack_import.write_log('Imported product info.');
    commit;
    pack_import_product.cfbimportproductsize;
    pack_import_product.add_alternativesizes;
    pack_import.write_log('Imported product size info.');
    commit;
    --Import plant product settings
    pack_import_businessunit.import_plantproductsettings;
    pack_import_businessunit.import_plantproductsizesettings;
    commit;
    pack_import_supplier.cfbimport_supplierproducts;
    commit;
    pack_import.write_log('***** End import 1, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
  exception
    when pack_import.lvnuserexception then
      begin
        raise pack_import.lvnuserexception;
      end;
    when others then
      begin
        rollback;
        pack_import.write_log('cfbimport_1 Error ' || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimporteu_1;
  procedure cfbimporteu_2 is
  begin
    -- add missing departments
    pack_import.write_log('***** Begin import 2, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
    pack_import_department.cfbadd_missing_departments;
    pack_import_customer.cfbimportcustomer;
    pack_import_department.convert_i_department;
    pack_import_department.convert_costcenter;
    pack_import_department.import_stockcountsequence;
    pack_import.write_log('Imported customer.');
    commit;
    pack_import_customer.cfbimportcontactpersons;
    pack_import_customer.cfbimportcontactcalls;
    pack_import.write_log('Imported Contact Person.');
    commit;
    pack_import_customer.cfbimportcustomerdeliverydays;
    pack_import.write_log('Imported Customer delivery days.');
    commit;
    pack_import_customer.cfbimportcontractspercustomer;
    pack_import.write_log('Imported Contracts per Customer');
    commit;
    pack_import_customer.cfbimporttaxauthorities;
    commit;
    pack_import_customer.cfbimport_weighingcategpercust;
    pack_import_customer.cfbimport_generaluserinstruction;
    pack_import_customer.cfbimport_custuserinstruction;
    pack_import_customer.cfbimportcustomersurvey;
    commit;
    pack_import_web.convert_web;
    -- import emblems
    pack_import_emblem.cfbimportemblems;
    commit;
    pack_import.write_log('***** End import 2, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
  exception
    when pack_import.lvnuserexception then
      begin
        raise pack_import.lvnuserexception;
      end;
    when others then
      begin
        rollback;
        pack_import.write_log('cfbimport_2 Error ' || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimporteu_2;
  procedure cfbimporteu_3 is
  begin
    -- import productlists
    pack_import.write_log('***** Begin import 3, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
    --- import contracts
    pack_import_contract.import_contract;
    pack_import_contract.import_contractcustomer;
    pack_import_contract.import_contractpricelist;
    pack_import_contract.import_contractprice;
    pack_import_contract.import_contractproduct;
    --Import PLPC
    pack_import_plcustomer.cfbimportplcust;
    pack_import.write_log('Imported ProductListPerCustomer.');
    commit;
    pack_import_deliverystandards.cfbimport_productlistperdist;
    pack_import.write_log('Imported ProductListPerDist.');
    commit;
    pack_import_plcustomer.cfbimportinventoryadjustment;
    commit;
    pack_import.write_log('Imported import inventoryadjustment.');
    pack_import_plcustomer.cfbimportturnoverplpc;
    commit;
    pack_import.write_log('***** End import 3, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
  exception
    when pack_import.lvnuserexception then
      begin
        raise pack_import.lvnuserexception;
      end;
    when others then
      begin
        rollback;
        pack_import.write_log('cfbimport_3 Error ' || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimporteu_3;
  procedure cfbimporteu_4 is
  begin
    -- add missing departments
    pack_import.write_log('***** Begin import 4, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
    pack_import_department.cfbadd_missing_departments;
    pack_import_department.convert_i_department;
    commit;
    -- import wearer and wearer inventory.
    pack_import_wearer.cfbimportwearer;
    pack_import.write_log('Imported Wearers.');
    commit;
    pack_import_wearer.cfbimportwearerinventory;
    pack_import.write_log('Imported WearerInventory.');
    commit;
    pack_import_productsizeconv.phaseout;
    pack_import.write_log('***** End import 4, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
  exception
    when pack_import.lvnuserexception then
      begin
        raise pack_import.lvnuserexception;
      end;
    when others then
      begin
        rollback;
        pack_import.write_log('cfbimport_4 Error ' || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimporteu_4;
  procedure cfbimporteu_5 is
  begin
    -- import invoice header and lines.
    pack_import.write_log('***** Begin import 5, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
    pack_import_invoice.cfbimportinvoiceheader;
  pack_import_invoice.cfbimportinvoiceline;
    commit;
    pack_import_invoice.cfbcreateroutecontrol;
    commit;
    pack_import_invoice.cfbcreatesoilticketfrominvoice;
    commit;
    pack_import_artransaction.cfbimportartransaction;
    pack_import_artransaction.cfbimportcashapplication;
    commit;
    pack_import_pricestructure.cfbimport_specialchargepercust;
    pack_import_pricestructure.cfbimport_specialchargeperprod;
    commit;
    -- price list imports.
    pack_import_pricestructure.cfbimport_pricelist;
    pack_import_pricestructure.cfbimport_pricelistpercustomer;
    pack_import_pricestructure.cfbimport_freqrelatedprices;
    pack_import_pricestructure.cfbimport_changespwrentprices;
    commit;
    pack_import_pricestructure.cfbimport_customerstockcharge;
    pack_import_pricestructure.cfbimport_customercharges;
    pack_import_pricestructure.cfbimport_costpricelist;
  pack_import_pricestructure.imp_priceindex;
    commit;
    pack_import.write_log('Imported Prices.');
    pack_import.write_log('***** End import 5, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
  exception
    when pack_import.lvnuserexception then
      begin
        raise pack_import.lvnuserexception;
      end;
    when others then
      begin
        rollback;
        pack_import.write_log('cfbimport_5 Error ' || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimporteu_5;
  procedure cfbimporteu_6 is
  begin
    -- import delivery variations and mis. charges.
    pack_import.write_log('***** Begin import 6, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
    pack_import_soilticket.cfbsoilticket;
    pack_import_soilticket.cfbsoilticketline;
    commit;
    pack_import_soilticket.cfbimport_soilreasonability;
    commit;
    pack_import_dvariation.cfbdeliveryvariations;
    commit;
    pack_import_dvariation.cfbmisccharges;
    commit;
    pack_import_stock.import_stockroomquantity;
    commit;
    pack_import.write_log('Imported soilticket,deliveryvariations,misccharges and stockroomquantity.');
    pack_import.write_log('***** End import 6, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
  exception
    when pack_import.lvnuserexception then
      begin
        raise pack_import.lvnuserexception;
      end;
    when others then
      begin
        rollback;
        pack_import.write_log('cfbimport_6 Error ' || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimporteu_6;
  procedure cfbimporteu_7 is
    fpnnumberofuniqueitems number := 0;
  begin
    -- import active stock locations
    pack_import.write_log('***** Begin import 7, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
    pack_import_uniqueitem.import_activestocklocation;
    -- import unique items.
    select count(*) into fpnnumberofuniqueitems from i_uniqueitem i;
    pack_import.write_log('Total to be converted :  ' || to_char(fpnnumberofuniqueitems));
    fpnnumberofuniqueitems := 0;
    pack_import_uniqueitem.convertuniqueitem(fpnnumberofuniqueitems);
    pack_import.write_log('Total number of       :  ' || to_char(fpnnumberofuniqueitems) ||
                          ' imported.');
    pack_import.write_log('Imported uniqueitems.');
    commit;
    pack_import_stock.update_stockquantity_unqiue;
    commit;
    -- import unique items flag.
    pack_import_uniqueitem.import_uniqueitemflag;
    commit;
    pack_import.write_log('Imported uniqueitem flags.');
    commit;
    pack_import.write_log('***** End import 7, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
  exception
    when pack_import.lvnuserexception then
      begin
        raise pack_import.lvnuserexception;
      end;
    when others then
      begin
        rollback;
        pack_import.write_log('cfbimport_7, Error ' || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimporteu_7;
  procedure cfbimporteu_8 is
  begin
    -- import work orders and lines.
    pack_import.write_log('***** Begin import 8, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
    pack_import_workorder.cfbimportworkorder;
    pack_import_workorder.cfbimportworkorderline;
    commit;
    pack_import_purchaseorder.cfbimportpurchaseorder;
    commit;
    pack_import.write_log('Imported workorders and purchaseorders.');
    pack_import.write_log('***** End import 8, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
  exception
    when pack_import.lvnuserexception then
      begin
        raise pack_import.lvnuserexception;
      end;
    when others then
      begin
        rollback;
        pack_import.write_log('cfbimport_8 Error ' || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimporteu_8;
  procedure cfbimporteu_9 is
  begin
    -- import stockroom procedures.
    pack_import.write_log('***** Begin import 9, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
    --- import container
    pack_import_container.cfbimport_container;
    commit;
    pack_import_packingnote.import_packingnote;
    pack_import_packingnote.import_packingnotecontainer;
    commit;
    --import charge special size price
    pack_import_pricestructure.import_chargespecialsize_price;
    commit;
    pack_import.write_log('Imported containers and packingnotes.');
    pack_import.write_log('***** End import 9, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
  exception
    when pack_import.lvnuserexception then
      begin
        raise pack_import.lvnuserexception;
      end;
    when others then
      begin
        rollback;
        pack_import.write_log('cfbimport_9 Error ' || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimporteu_9;
  procedure cfbimporteu_10 is
  begin
    -- import residential procedures.
    pack_import.write_log('***** Begin import 10, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
    pack_import_residential.import_custresidentialsettings;
    pack_import_residential.import_residentialplpc;
    pack_import_residential.import_client;
    pack_import_residential.import_uniqueresitem;
    commit;
    pack_import.write_log('Imported residential data.');
    --process flexfields, last step!
    pack_import_flexfields.import_all_flexfields;
    pack_import_product.add_missing_default_prodsize;
    commit;
    pack_import_history.convertdeliveryhistory;
    pack_import_history.convert_scanhistory;
    pack_import_history.import_outofstockhistory;
    pack_import_history.import_issuehistory;
    pack_import_history.import_emblemhistory;
  pack_import_history.import_allocationtrans;
    commit;
    pack_import.write_log('Imported historical data.');
    pack_import.write_log('***** End import 10, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
    pack_import.write_log('***** End conversion*****');
  exception
    when pack_import.lvnuserexception then
      begin
        raise pack_import.lvnuserexception;
      end;
    when others then
      begin
        rollback;
        pack_import.write_log('cfbimport_10 Error ' || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimporteu_10;
procedure cfbimporteu_11 is
  begin
      --import cleanroombatchcustomer
    pack_import.write_log('***** Begin import 11, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
    pack_import_sterilizationlot.cfbimport_cleanroombatchcustomer;
  pack_import.write_log('Imported cleanroombatch customer.');
  commit;
    pack_import_sterilizationlot.cfbimport_cleanroomuidelivery;
  pack_import.write_log('Imported cleanroomuidelivery records.');
    commit;
    pack_import.write_log('***** End import 11, using language ' || pack_import.lvnlanguagecode ||
                          ' *****');
  exception
    when pack_import.lvnuserexception then
      begin
        raise pack_import.lvnuserexception;
      end;
    when others then
      begin
        rollback;
        pack_import.write_log('cfbimport_11 Error ' || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimporteu_11;
begin
  --pack_import.cfbimportplantfixedinfo, initialize
  pack_import.cfbimportplantfixedinfo;
exception
  when pack_import.lvnuserexception then
    begin
      pack_import.write_log('Conversion stopped with errors!', 3);
      raise pack_import.lvnuserexception;
    end;
  when others then
    begin
      rollback;
      pack_import.write_log('Error ' || substr(sqlerrm, 1, 512), 3);
    end;
end pack_import_eu;
/
create or replace package pack_import_flexfields is
  --Purpose : Import flexfields ABSSolute
  --process i-table i_dialogflexflields, per dialog
  -- Version : 1.0
  procedure import_customer_flexfields;
  procedure import_product_flexfields;
  procedure import_plpc_flexfields;
  procedure import_contract_flexfields;
  --process whole table
  procedure import_all_flexfields;
end pack_import_flexfields;
/
create or replace package body pack_import_flexfields is
  gv_message abslog.message%type;
  error_predefinedvalue exception;
  lv_characteristicpredefvalueid characteristicpredefvalue.characteristicpredefvalue_id%type;
  procedure import_customer_flexfields is
    lv_dialogid         dialogs.dialog_id%type;
    lv_counter          number;
    lv_characteristicid characteristic.characteristic_id%type;
    lv_customerid       customer.customer_id%type;
    procedure initialize is
    begin
      --Get dialog id for dialog.code Customer
      gv_message := 'Get dialog id for dialog.code Customer';
      select dg.dialog_id into lv_dialogid from dialogs dg where dg.code = 'Customer';
      --reset counter
      lv_counter := 0;
    end initialize;
  begin
    --initialize
    initialize;
    --process i-table i_dialogflexflields
    for x in (select ic.*
              from   i_dialogflexflields ic
              where  ic.dialogcode = 'Customer'
              and    ic.entity_number1 is not null
              order  by ic.characteristiccode, ic.entity_number1) loop
      begin
        --get characteristic
        gv_message := 'Characteristic code ' || x.characteristiccode || ' for dialog Customer';
        select chr.characteristic_id
        into   lv_characteristicid
        from   characteristic chr
        where  chr.code = x.characteristiccode
        and    chr.dialog_id = lv_dialogid;
        --get customer id
        gv_message := 'Customer number ' || x.entity_number1;
        select c.customer_id
        into   lv_customerid
        from   customer c
        where  c.customernumber = x.entity_number1;
        --check predefined value
        lv_characteristicpredefvalueid := null;
        if x.predefinedvalue = 'Y' then
          begin
            gv_message := 'Customer number ' || x.entity_number1 || ' Characteristic code ' ||
                          x.characteristiccode || ' string value ' || x.stringvalue ||
                          ' for dialog Customer';
            select pdv.characteristicpredefvalue_id
            into   lv_characteristicpredefvalueid
            from   characteristicpredefvalue pdv
            where  pdv.characteristic_id = lv_characteristicid
            and    pdv.stringvalue = x.stringvalue;
          exception
            when no_data_found then
              begin
                raise error_predefinedvalue;
              end;
          end;
        end if;
        --insert into dialogflexfields
        gv_message := 'insert into dialogflexfields Characteristic code ' || x.characteristiccode ||
                      ' for customer ' || x.numbervalue;
        insert into dialogflexfields
          (dialogflexfield_id, dialog_id, entity_id, characteristic_id, numbervalue, stringvalue,
           datevalue, characteristicpredefvalue_id, systemuser_id, timestamp)
        values
          (seq_dialogflexfields.nextval, lv_dialogid, lv_customerid, lv_characteristicid,
           x.numbervalue, x.stringvalue, x.datevalue, lv_characteristicpredefvalueid,
           pack_import.lvnsystemuserid, sysdate /*timestamp*/);
        --count number of customer/fields imported
        lv_counter := lv_counter + 1;
      exception
        when dup_val_on_index then
          begin
            pack_import.write_log('import_customer_flexfields already exists ' || gv_message, 3);
          end;
        when no_data_found then
          begin
            pack_import.write_log('import_customer_flexfields No data found ' || gv_message, 3);
          end;
        when error_predefinedvalue then
          begin
            pack_import.write_log('import_customer_flexfields, predefined values not found ' ||
                                  gv_message, 3);
          end;
      end;
    end loop; --x
    if lv_counter > 0 then
      begin
        commit;
        --write in log number of records imported into dialogflexfields
        pack_import.write_log('Imported ' || to_char(lv_counter) ||
                              ' record(s) into dialogflexfields for Customer(s)', 1);
      end;
    end if;
  exception
    --error handling
    when no_data_found then
      begin
        rollback;
        pack_import.write_log('import_customer_flexfields No data found ' || gv_message, 3);
      end;
    when others then
      begin
        rollback;
        pack_import.write_log('import_customer_flexfields ' || gv_message || ' error: ' ||
                              substr(sqlerrm, 1, 512), 3);
      end;
  end import_customer_flexfields;
  procedure import_product_flexfields is
    lv_dialogid         dialogs.dialog_id%type;
    lv_counter          number;
    lv_characteristicid characteristic.characteristic_id%type;
    lv_productid        product.product_id%type;
    procedure initialize is
    begin
      --Get dialog id for dialog.code product
      gv_message := 'Get dialog id for dialog.code Product';
      select dg.dialog_id into lv_dialogid from dialogs dg where dg.code = 'Product';
      --reset counter
      lv_counter := 0;
    end initialize;
  begin
    --initialize
    initialize;
    --process i-table i_dialogflexflields
    for x in (select ic.*
              from   i_dialogflexflields ic
              where  ic.dialogcode = 'Product'
              and    ic.entity_code1 is not null
              order  by ic.characteristiccode, ic.entity_code1) loop
      begin
        --get characteristic
        gv_message := 'Characteristic code ' || x.characteristiccode || ' for dialog product';
        select chr.characteristic_id
        into   lv_characteristicid
        from   characteristic chr
        where  chr.code = x.characteristiccode
        and    chr.dialog_id = lv_dialogid;
        --get product id
        gv_message := 'Product code ' || x.entity_code1;
        select p.product_id into lv_productid from product p where p.code = x.entity_code1;
        --check predefined value
        lv_characteristicpredefvalueid := null;
        if x.predefinedvalue = 'Y' then
          begin
            gv_message := 'Product code ' || x.entity_code1 || ' Characteristic code ' ||
                          x.characteristiccode || ' string value ' || x.stringvalue ||
                          ' for dialog product';
            select pdv.characteristicpredefvalue_id
            into   lv_characteristicpredefvalueid
            from   characteristicpredefvalue pdv
            where  pdv.characteristic_id = lv_characteristicid
            and    pdv.stringvalue = x.stringvalue;
          exception
            when no_data_found then
              begin
                raise error_predefinedvalue;
              end;
          end;
        end if;
        --insert into dialogflexfields
        gv_message := 'insert into dialogflexfields Characteristic code ' || x.characteristiccode ||
                      ' for product ' || x.entity_code1;
        insert into dialogflexfields
          (dialogflexfield_id, dialog_id, entity_id, characteristic_id, numbervalue, stringvalue,
           datevalue, characteristicpredefvalue_id, systemuser_id, timestamp)
        values
          (seq_dialogflexfields.nextval, lv_dialogid, lv_productid, lv_characteristicid,
           x.numbervalue, x.stringvalue, x.datevalue, lv_characteristicpredefvalueid,
           pack_import.lvnsystemuserid, sysdate /*timestamp*/);
        --count number of product/fields imported
        lv_counter := lv_counter + 1;
      exception
        when dup_val_on_index then
          begin
            pack_import.write_log('import_product_flexfields already exists ' || gv_message, 3);
          end;
        when no_data_found then
          begin
            pack_import.write_log('import_product_flexfields No data found ' || gv_message, 3);
          end;
        when error_predefinedvalue then
          begin
            pack_import.write_log('import_product_flexfields, predefined values not found ' ||
                                  gv_message, 3);
          end;
      end;
    end loop; --x
    if lv_counter > 0 then
      begin
        commit;
        --write in log number of records imported into dialogflexfields
        pack_import.write_log('Imported ' || to_char(lv_counter) ||
                              ' record(s) into dialogflexfields for Product(s)', 1);
      end;
    end if;
  exception
    --error handling
    when no_data_found then
      begin
        rollback;
        pack_import.write_log('import_product_flexfields No data found ' || gv_message, 3);
      end;
    when others then
      begin
        rollback;
        pack_import.write_log('import_product_flexfields ' || gv_message || ' error: ' ||
                              substr(sqlerrm, 1, 512), 3);
      end;
  end import_product_flexfields;
  procedure import_plpc_flexfields is
    lv_dialogid          dialogs.dialog_id%type;
    lv_counter           number;
    lv_characteristicid  characteristic.characteristic_id%type;
    lv_customerid        customer.customer_id%type;
    lv_productid         product.product_id%type;
    lv_sizeid            sizedefinition.sizedefinition_id%type;
    lv_finishingmethodid finishingmethod.finishingmethod_id%type;
    procedure initialize is
    begin
      --Get dialog id for dialog.code product
      gv_message := 'Get dialog id for dialog.code Product';
      select dg.dialog_id
      into   lv_dialogid
      from   dialogs dg
      where  dg.code = 'ProductListPerCustomer';
      --reset counter
      lv_counter := 0;
    end initialize;
  begin
    --initialize
    initialize;
    --process i-table i_dialogflexflields
    for x in (select ic.*
              from   i_dialogflexflields ic
              where  ic.dialogcode = 'ProductListPerCustomer'
              and    ic.entity_number1 is not null
              and    ic.entity_code1 is not null
              order  by ic.characteristiccode, ic.entity_number1, ic.entity_code1, ic.entity_code2,
                        ic.entity_code3) loop
      begin
        --get characteristic
        gv_message := 'Characteristic code ' || x.characteristiccode || ' for dialog plpc';
        select chr.characteristic_id
        into   lv_characteristicid
        from   characteristic chr
        where  chr.code = x.characteristiccode
        and    chr.dialog_id = lv_dialogid;
        --get customer id
        gv_message := 'Customer number ' || x.entity_number1;
        select c.customer_id
        into   lv_customerid
        from   customer c
        where  c.customernumber = x.entity_number1;
        --get product id
        gv_message := 'Product code ' || x.entity_code1;
        select p.product_id into lv_productid from product p where p.code = x.entity_code1;
        --get size id
        gv_message := 'Size code ' || nvl(x.entity_code2, 'NULL');
        select s.sizedefinition_id
        into   lv_sizeid
        from   sizedefinition s
        where  s.code = nvl(x.entity_code2, '-');
        --get finishingmethod id
        gv_message := 'Finishingmetod code ' || nvl(x.entity_code3, 'NULL');
        select f.finishingmethod_id
        into   lv_finishingmethodid
        from   finishingmethod f
        where  f.code = nvl(x.entity_code3, '-');
        --check predefined value
        lv_characteristicpredefvalueid := null;
        if x.predefinedvalue = 'Y' then
          begin
            gv_message := 'Product code ' || x.entity_code1 || ' Characteristic code ' ||
                          x.characteristiccode || ' string value ' || x.stringvalue ||
                          '  for dialog plpc';
            select pdv.characteristicpredefvalue_id
            into   lv_characteristicpredefvalueid
            from   characteristicpredefvalue pdv
            where  pdv.characteristic_id = lv_characteristicid
            and    pdv.stringvalue = x.stringvalue;
          exception
            when no_data_found then
              begin
                raise error_predefinedvalue;
              end;
          end;
        end if;
        --update productlistpercustomer flex fields
        for y in (select l.productlistpercustomer_id
                  from   productlistpercustomer l
                  where  l.customer_id = lv_customerid
                  and    l.product_id = lv_productid
                  and    l.sizedefinition_id = lv_sizeid
                  and    l.finishingmethod_id = lv_finishingmethodid) loop
          begin
            --insert into dialogflexfields
            gv_message := 'insert into dialogflexfields Characteristic code ' ||
                          x.characteristiccode || ' for plpc id ' || y.productlistpercustomer_id;
            insert into dialogflexfields
              (dialogflexfield_id, dialog_id, entity_id, characteristic_id, numbervalue,
               stringvalue, datevalue, characteristicpredefvalue_id, systemuser_id, timestamp)
            values
              (seq_dialogflexfields.nextval, lv_dialogid, y.productlistpercustomer_id,
               lv_characteristicid, x.numbervalue, x.stringvalue, x.datevalue,
               lv_characteristicpredefvalueid, pack_import.lvnsystemuserid, sysdate /*timestamp*/);
            --count number of plpc/fields imported
            lv_counter := lv_counter + 1;
          end;
        end loop; --y
      exception
        when dup_val_on_index then
          begin
            pack_import.write_log('import_plpc_flexfields already exists ' || gv_message, 3);
          end;
        when no_data_found then
          begin
            pack_import.write_log('import_plpc_flexfields No data found ' || gv_message, 3);
          end;
        when error_predefinedvalue then
          begin
            pack_import.write_log('import_plpc_flexfields, predefined values not found ' ||
                                  gv_message, 3);
          end;
      end;
    end loop; --x
    if lv_counter > 0 then
      begin
        commit;
        --write in log number of records imported into dialogflexfields
        pack_import.write_log('Imported ' || to_char(lv_counter) ||
                              ' record(s) into dialogflexfields for ProductListPerCustomer(s)', 1);
      end;
    end if;
  exception
    --error handling
    when no_data_found then
      begin
        rollback;
        pack_import.write_log('import_plpc_flexfields No data found ' || gv_message, 3);
      end;
    when others then
      begin
        rollback;
        pack_import.write_log('import_plpc_flexfields ' || gv_message || ' error: ' ||
                              substr(sqlerrm, 1, 512), 3);
      end;
  end import_plpc_flexfields;
  procedure import_contract_flexfields is
    lv_dialogid         dialogs.dialog_id%type;
    lv_counter          number;
    lv_characteristicid characteristic.characteristic_id%type;
    lv_contractid       contract.contract_id%type;
    procedure initialize is
    begin
      --Get dialog id for dialog.code Contract
      gv_message := 'Get dialog id for dialog.code Contract';
      select dg.dialog_id into lv_dialogid from dialogs dg where dg.code = 'Contract';
      --reset counter
      lv_counter := 0;
    end initialize;
  begin
    --initialize
    initialize;
    --process i-table i_dialogflexflields
    for x in (select ic.*
              from   i_dialogflexflields ic
              where  ic.dialogcode = 'Contract'
              and    ic.entity_code1 is not null
              order  by ic.characteristiccode, ic.entity_code1) loop
      begin
        --get characteristic
        gv_message := 'Characteristic code ' || x.characteristiccode || ' for dialog Contract';
        select chr.characteristic_id
        into   lv_characteristicid
        from   characteristic chr
        where  chr.code = x.characteristiccode
        and    chr.dialog_id = lv_dialogid;
        --get contract id
        gv_message := 'Contract code ' || x.entity_code1;
        select ct.contract_id into lv_contractid from contract ct where ct.code = x.entity_code1;
        --check predefined value
        lv_characteristicpredefvalueid := null;
        if x.predefinedvalue = 'Y' then
          begin
            gv_message := 'Contract code ' || x.entity_code1 || ' Characteristic code ' ||
                          x.characteristiccode || ' string value ' || x.stringvalue ||
                          ' for dialog Contract';
            select pdv.characteristicpredefvalue_id
            into   lv_characteristicpredefvalueid
            from   characteristicpredefvalue pdv
            where  pdv.characteristic_id = lv_characteristicid
            and    pdv.stringvalue = x.stringvalue;
          exception
            when no_data_found then
              begin
                raise error_predefinedvalue;
              end;
          end;
        end if;
        --insert into dialogflexfields
        gv_message := 'insert into dialogflexfields Characteristic code ' || x.characteristiccode ||
                      ' for contract ' || x.entity_code1;
        insert into dialogflexfields
          (dialogflexfield_id, dialog_id, entity_id, characteristic_id, numbervalue, stringvalue,
           datevalue, characteristicpredefvalue_id, systemuser_id, timestamp)
        values
          (seq_dialogflexfields.nextval, lv_dialogid, lv_contractid, lv_characteristicid,
           x.numbervalue, x.stringvalue, x.datevalue, lv_characteristicpredefvalueid,
           pack_import.lvnsystemuserid, sysdate /*timestamp*/);
        --count number of contract/fields imported
        lv_counter := lv_counter + 1;
      exception
        when dup_val_on_index then
          begin
            pack_import.write_log('import_contract_flexfields already exists ' || gv_message, 3);
          end;
        when no_data_found then
          begin
            pack_import.write_log('import_contract_flexfields No data found ' || gv_message, 3);
          end;
        when error_predefinedvalue then
          begin
            pack_import.write_log('import_contract_flexfields, predefined values not found ' ||
                                  gv_message, 3);
          end;
      end;
    end loop; --x
    if lv_counter > 0 then
      begin
        commit;
        --write in log number of records imported into dialogflexfields
        pack_import.write_log('Imported ' || to_char(lv_counter) ||
                              ' record(s) into dialogflexfields for Contract(s)', 1);
      end;
    end if;
  exception
    --error handling
    when no_data_found then
      begin
        rollback;
        pack_import.write_log('import_contract_flexfields No data found ' || gv_message, 3);
      end;
    when others then
      begin
        rollback;
        pack_import.write_log('import_contract_flexfields ' || gv_message || ' error: ' ||
                              substr(sqlerrm, 1, 512), 3);
      end;
  end import_contract_flexfields;
  procedure import_all_flexfields is
    lv_tobeconverted number;
  begin
    select count(1) into lv_tobeconverted from i_dialogflexflields;
    if lv_tobeconverted > 0 then
      begin
        pack_import.write_log('Begin import flexfields, ' || lv_tobeconverted ||
                              ' flexfield value(s) to be converted');
        --import_all_flexfields
        import_customer_flexfields;
        import_product_flexfields;
        import_plpc_flexfields;
        import_contract_flexfields;
      end;
    end if;
    commit;
  exception
    --error handling
    when others then
      begin
        rollback;
        pack_import.write_log('import_all_flexfields error: ' || substr(sqlerrm, 1, 512), 3);
      end;
  end import_all_flexfields;
end pack_import_flexfields;
/
create or replace package pack_import_history is
  -- Author  : PVD
  -- Created : 09-05-2006 14:10:31
  -- Version : 1.0
  -- Purpose : Conversion history information into the database
  procedure convertdeliveryhistory;
  procedure convert_scanhistory;
  --Optional procedure to import scans with sendtrackinfo
  procedure import_scans;
  --Optional conversion procedure to convert outofstockhistory
  procedure import_outofstockhistory;
  procedure import_issuehistory;
  procedure import_emblemhistory;
  procedure import_allocationtrans;
end pack_import_history;
/
create or replace package body pack_import_history is
  -- Private variable declarations
  gv_message varchar2(256);
  procedure convertdeliveryhistory is
    fpbimport_allowed            boolean := true;
    fpnproduct_link_id           number := 0;
    fpnsizedefinition_link_id    number := 0;
    fpnfinishingmethod_id        number := 0;
    fpncustomer_link_id          number := 0;
    fpndepartment_link_id        number := 0;
    fpndistributionpoint_link_id number := 0;
    fpnbusinessunit_id           number := 0;
    fpncurrency_id               number := 0;
    fpncounter                   number := 0;
    fpnexistingrecords           number := 0;
  begin
    --check how many records exist in i_deliveryhistory
    select count(*) into fpncounter from i_deliveryhistory;
    if fpncounter > 0 then
      pack_import.write_log(to_char(fpncounter) || ' i_deliveryhistory records.');
    end if;
    fpncounter := 0;
    --currency does not matter price not converted anyway
    select min(c.currency_id) into fpncurrency_id from currency c;
    --start inserting the deliveryhistory
    for x in (select * from i_deliveryhistory) loop
      begin
        begin
          -- Determine product.
          select max(product_link_id)
          into   fpnproduct_link_id
          from   product_link
          where  code = x.productcode;
        exception
          when no_data_found then
            begin
              gv_message := ' NO_DATA product_link: ' || x.productcode;
              pack_import.write_log(gv_message);
              fpbimport_allowed  := false;
              fpnproduct_link_id := null;
            end;
        end;
        begin
          -- Determine size.
          select max(sizedefinition_link_id)
          into   fpnsizedefinition_link_id
          from   sizedefinition_link
          where  code = x.sizecode;
        exception
          when no_data_found then
            begin
              gv_message := ' NO_DATA sizedefinition_link: ' || x.sizecode;
              pack_import.write_log(gv_message);
              fpbimport_allowed         := false;
              fpnsizedefinition_link_id := null;
            end;
        end;
        begin
          --determine finishing method id
          select f.finishingmethod_id
          into   fpnfinishingmethod_id
          from   finishingmethod f
          where  f.code = x.finishingmethodcode;
        exception
          when no_data_found then
            begin
              gv_message := ' NO_DATA finishingmethodcode : ' || x.finishingmethodcode;
              pack_import.write_log(gv_message);
              fpbimport_allowed     := false;
              fpnfinishingmethod_id := null;
            end;
        end;
        begin
          -- Determine business unit.
          select businessunit_id
          into   fpnbusinessunit_id
          from   businessunit x
          where  x.code = to_char(x.businessunitnumber);
        exception
          when no_data_found then
            begin
              gv_message := ' NO_DATA bunissunit: ' || to_char(x.businessunitnumber);
              pack_import.write_log(gv_message);
              fpbimport_allowed  := false;
              fpnbusinessunit_id := null;
            end;
        end;
        begin
          -- Determine customer.
          select max(customer_id)
          into   fpncustomer_link_id
          from   customer_link
          where  customernumber = x.customernumber;
        exception
          when no_data_found then
            begin
              gv_message := ' NO_DATA customer_link: ' || to_char(x.customernumber);
              pack_import.write_log(gv_message);
              fpbimport_allowed   := false;
              fpncustomer_link_id := null;
            end;
        end;
        begin
          -- Determine department.
          select max(department_link_id)
          into   fpndepartment_link_id
          from   department_link
          where  customer_link_id = fpncustomer_link_id
          and    departmentnumber = x.departmentnumber;
        exception
          when no_data_found then
            begin
              gv_message := ' NO_DATA department_link for customer/department: ' ||
                            to_char(x.customernumber) || '/' || to_char(x.departmentnumber);
              pack_import.write_log(gv_message);
              fpbimport_allowed     := false;
              fpndepartment_link_id := null;
            end;
        end;
        begin
          -- Determine department.
          select min(l.distributionpoint_link_id)
          into   fpndistributionpoint_link_id
          from   distributionpoint_link l
          where  l.department_link_id = fpndepartment_link_id;
          if fpndistributionpoint_link_id is null then
            begin
              gv_message := ' NO_DATA distributionpoint_link for customer/department: ' ||
                            to_char(x.customernumber) || '/' || to_char(x.departmentnumber);
              pack_import.write_log(gv_message);
              fpbimport_allowed := false;
            end;
          end if;
        end;
        if fpbimport_allowed then
          begin
            insert into deliveryhistory
              (deliveryhistory_id, deliverydate, year, week, daynumber, customer_link_id,
               department_link_id, distributionpoint_link_id, product_link_id,
               sizedefinition_link_id, finishingmethod_id, amountdelivered, currency_id,
               amountshortage, price, amountordered, internalprice, discount, processbusinessunit_id,
               systemuser_id, invoicebusinessunit_id, timestamp, parentpackproduct_link_id,
               packindication, parentproduct_link_id, amountstandard, pieceweight)
            values
              (seq_deliveryhistory.nextval, x.deliverydate, getyearofweek(x.deliverydate),
               getisoweek(x.deliverydate), getabsdaynumber(x.deliverydate), fpncustomer_link_id,
               fpndepartment_link_id, fpndistributionpoint_link_id, fpnproduct_link_id,
               fpnsizedefinition_link_id, fpnfinishingmethod_id, x.amount, fpncurrency_id, 0, 0, 0,
               0, 0, fpnbusinessunit_id, pack_import.lvnsystemuserid, fpnbusinessunit_id, sysdate,
               fpnproduct_link_id, 1, fpnproduct_link_id, 0, 0);
            --1 deliveryhistory record added
            commit;
            fpncounter := fpncounter + 1;
          exception
            when dup_val_on_index then
              begin
                fpnexistingrecords := fpnexistingrecords + 1;
              end;
            when others then
              begin
                gv_message := ' Convertdeliveryhistory error; insert into deliveryhistory ';
                pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 3);
              end;
          end;
        end if; -- import allowed
      end;
    end loop;
    commit;
    if fpnexistingrecords > 0 then
      pack_import.write_log(to_char(fpnexistingrecords) || ' already existed in deliveryhistory.');
    end if;
    if fpncounter > 0 then
      pack_import.write_log(to_char(fpncounter) || ' deliveryhistory records imported.');
    end if;
  exception
    when others then
      begin
        pack_import.write_log('Error convertdeliveryhistory ' || gv_message || ' ' ||
                              substr(sqlerrm, 1, 512), 3);
      end;
  end convertdeliveryhistory;
  procedure convert_scanhistory is
    --internal variables
    cursor scan_cur is
      select * from i_scanhistory ish where ish.processed_yn = 'N';
    type scan_aat is table of scan_cur%rowtype index by pls_integer;
    lv_rec_scan     scan_aat;
    lv_statusid     status.status_id%type;
    lv_stay_inscan  stay.stay_id%type;
    lv_stay_outscan stay.stay_id%type;
    lv_stay_repair  stay.stay_id%type;
    lv_stay_rewash  stay.stay_id%type;
    lv_stay_onsitesoil stay.stay_id%type;
    lv_stay_onsiteinventory stay.stay_id%type;
    lv_counter      number;
    lv_error_cnt    number;
    --internal procedure insert_scan
    procedure initialize is
    begin
      --initialize
      lv_counter   := 0;
      lv_error_cnt := 0;
      --get status In Circulation
      gv_message := 'convert_scanhistory.initialize get status In Circulation';
      select st.status_id
      into   lv_statusid
      from   status st
      where  st.statustype = 'UI'
      and    st.code = '20';
      --get stay can/Soiled Received
      gv_message := 'convert_scanhistory.initialize get stay can/Soiled Received';
      select sy.stay_id
      into   lv_stay_inscan
      from   stay sy
      where  sy.staytype = 1
      and    sy.staynr = 30;
      --get stay Outscan/At Customer
      gv_message := 'convert_scanhistory.initialize get stay Outscan/At Customer';
      select sy.stay_id
      into   lv_stay_outscan
      from   stay sy
      where  sy.staytype = 1
      and    sy.staynr = 20;
      --get stay Repair/Mending
      gv_message := 'convert_scanhistory.initialize get stay Repair/Mending';
      select sy.stay_id
      into   lv_stay_repair
      from   stay sy
      where  sy.staytype = 1
      and    sy.staynr = 32;
    --get stay Rewash
      gv_message := 'convert_scanhistory initialise get stay Rewash';
      select sy.stay_id
      into lv_stay_rewash
      from stay sy
      where sy.staytype = 1
      and  sy.staynr =31;
       --get stay Onsite Soil
      gv_message := 'convert_scanhistory initialise get stay Onsite Soil';
      select sy.stay_id
      into lv_stay_onsitesoil
      from stay sy
      where sy.staytype = 1
      and  sy.staynr =20;
       --get stay Onsiteinventory
      gv_message := 'convert_scanhistory initialise get stay Onsite Inventory';
      select sy.stay_id
      into lv_stay_onsiteinventory
      from stay sy
      where sy.staytype = 1
      and  sy.staynr =27;
    end initialize;
    procedure insert_scan(fp_scanhistory in i_scanhistory%rowtype) is
    begin
      --insert_scan
      gv_message := 'convert_scanhistory.insert_scan';
      insert into scan
        (scan_id, businessunit_id, scantimestamp, year, week, dayno, transactiontype_id, primaryid,
         product_link_id, sizedefinition_link_id, stay_id, status_id, scanstation, issuedate,
         customerowned, dayslate, uniqueitem_link_id, systemuser_id, timestamp, deliverynotenumber,
         customer_link_id, distributionpoint_link_id ,batchnumber)
        select seq_scan.nextval, u.businessunit_id, fp_scanhistory.scandatetime,
               getyearofweek(fp_scanhistory.scandatetime), getisoweek(fp_scanhistory.scandatetime),
               getabsdaynumber(fp_scanhistory.scandatetime), fp_scanhistory.in_out_scan, u.primaryid,
               u.product_id, u.sizedefinition_id,
               case fp_scanhistory.in_out_scan
                 when 1 then
                  lv_stay_inscan
                 when 2 then
                  lv_stay_outscan
                 when 3 then
                  lv_stay_repair
         when 4 then
                  lv_stay_rewash
                 when 75 then
                   lv_stay_onsitesoil
                 when 76 then
                   lv_stay_onsiteinventory
                 else
                  u.stay_id
               end, lv_statusid, nvl(fp_scanhistory.scanstation, 'CONVERSION'), uf.lastissuedate,
               u.customerowned, 0, u.uniqueitem_id, pack_import.lvnsystemuserid, sysdate,
               case fp_scanhistory.in_out_scan
                 when 2 then
                  fp_scanhistory.deliverynotenumber
                 else
                  null
               end, delp.customer_id, pk.distributionpoint_id , fp_scanhistory.batchnumber
        from   uniqueitem u
        join   uniqueitemfixedinfo uf
        on     uf.uniqueitem_id = u.uniqueitem_id
        left   outer join(packingnote pk
        join   deliverypoint delp
        on     delp.deliverypoint_id = pk.deliverypoint_id) on pk.notenumber = fp_scanhistory.deliverynotenumber
        where  u.primaryid = fp_scanhistory.primaryid
        and    u.businessunit_id =
               (select bu.businessunit_id
                 from   businessunit bu
                 where  bu.code = fp_scanhistory.businessunit)
        and    u.idcodesequencenumber = fp_scanhistory.idcodesequencenumber;
      if sql%rowcount = 1 then
        begin
          --processed i_scanhistory
          update i_scanhistory ih
          set    ih.processed_yn = 'Y' --processed successfully
          where  ih.scandatetime = fp_scanhistory.scandatetime
          and    ih.businessunit = fp_scanhistory.businessunit
          and    ih.primaryid = fp_scanhistory.primaryid
          and    ih.idcodesequencenumber = fp_scanhistory.idcodesequencenumber;
          --count successfully inserted records
          lv_counter := lv_counter + 1;
        end;
      else
        begin
          --processed i_scanhistory
          update i_scanhistory ih
          set    ih.processed_yn = 'E' ---error
          where  ih.scandatetime = fp_scanhistory.scandatetime
          and    ih.businessunit = fp_scanhistory.businessunit
          and    ih.primaryid = fp_scanhistory.primaryid
          and    ih.idcodesequencenumber = fp_scanhistory.idcodesequencenumber;
          --count errors
          lv_error_cnt := lv_error_cnt + 1;
        end;
      end if;
    exception
      when dup_val_on_index then
        begin
          --processed i_scanhistory
          update i_scanhistory ih
          set    ih.processed_yn = 'Y' --processed successfully
          where  ih.scandatetime = fp_scanhistory.scandatetime
          and    ih.businessunit = fp_scanhistory.businessunit
          and    ih.primaryid = fp_scanhistory.primaryid
          and    ih.idcodesequencenumber = fp_scanhistory.idcodesequencenumber;
          --but not counted as processed, scan was already there!
        end;
      when others then
        begin
          --processed i_scanhistory
          update i_scanhistory ih
          set    ih.processed_yn = 'E' ---error
          where  ih.scandatetime = fp_scanhistory.scandatetime
          and    ih.businessunit = fp_scanhistory.businessunit
          and    ih.primaryid = fp_scanhistory.primaryid
          and    ih.idcodesequencenumber = fp_scanhistory.idcodesequencenumber;
          --count errors
          lv_error_cnt := lv_error_cnt + 1;
          pack_import.write_log('Error convert_scanhistory bu ' || fp_scanhistory.businessunit ||
                                ' id code ' || fp_scanhistory.primaryid || ' ' ||
                                substr(sqlerrm, 1, 512), 3);
        end;
    end insert_scan;
    procedure finalize is
    begin
      --logging
      if lv_counter > 0 then
        begin
          pack_import.write_log(to_char(lv_counter) || ' scans imported', 1);
        end;
      end if;
      if lv_error_cnt > 0 then
        begin
          pack_import.write_log('Warning ' || to_char(lv_error_cnt) || ' scans NOT imported', 2);
        end;
      end if;
    end finalize;
  begin
    --convert_scanhistory
    gv_message := 'convert_scanhistory';
    initialize;
    open scan_cur;
    loop
      fetch scan_cur bulk collect
        into lv_rec_scan limit 500;
      for i in 1 .. lv_rec_scan.count loop
        begin
          insert_scan(lv_rec_scan(i));
        end;
      end loop;
      commit;
      exit when lv_rec_scan.count = 0;
    end loop;
    close scan_cur;
    commit;
    finalize;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('Error convert_scanhistory ' || gv_message || ' ' ||
                              substr(sqlerrm, 1, 512), 3);
      end;
  end convert_scanhistory;
  procedure import_scans is
    lv_statusout number;
    lv_noflag    flag.code%type;
  begin
    --loop all scans not processed yet, that is processed_yn = 'N'
    for x in (select i.*, i.rowid
              from   i_scan i
              where  i.processed_yn = 'N'
              order  by i.scandate, i.scantime) loop
      begin
        sendtrackinfo(x.barcode, x.plantcode, x.scandate, x.scantime, x.locationcode,
                      x.nextlocation, lv_noflag, lv_noflag, lv_noflag, lv_noflag, null, null, null,
                      null, lv_statusout);
        --always update import result!
        update i_scan i
        set    i.processed_yn = 'Y', i.statusout = lv_statusout
        where  i.rowid = x.rowid;
        commit;
        if lv_statusout <> 0 then
          begin
            --scan not processed see status out number
            pack_import.write_log('import_scans sendtrackinfo returned status ' ||
                                  to_char(lv_statusout) || ' for barcode ' || x.barcode ||
                                  ' for date/time ' || x.scandate || '/' || x.scantime, 2);
          end;
        end if;
      exception
        when others then
          begin
            --error during running of procedure, see sqlerrm log
            pack_import.write_log('import_scans ' || sqlerrm, 5);
          end;
      end;
    end loop; --x
    --can always commit, only update of i_scan when it was succesfull
    commit;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('Error import_scans ' || substr(sqlerrm, 1, 512), 3);
      end;
  end import_scans;
  procedure import_outofstockhistory is
    lv_counter number := 0;
  begin
    --import_outofstockhistory
    gv_message := 'import_outofstockhistory';
    for x in (select io.*, procbu.businessunit_id procbu_id, forbu.businessunit_id forbu_id,
                     invbu.businessunit_id invbu_id, c.customer_id, t.department_id,
                     dp.distributionpoint_id, rs.reasoncode_id, rg.ragreason_id, cy.currency_id,
                     w.wearer_id, we.weareremployment_id, p.product_id, s.sizedefinition_id,
                     q.qualitygrade_id, st.stockroom_id
              from   i_outofcirculationhistory io
              join   businessunit procbu
              on     procbu.code = io.processbusinessunit
              join   businessunit forbu
              on     forbu.code = io.forbusinessunit
              join   businessunit invbu
              on     invbu.code = io.invoicebusinessunit
              join   customer c
              on     c.customernumber = io.customernumber
              left   outer join wearer w
              on     w.wearernumber = io.wearernumber
              and    w.customer_id = c.customer_id
              left   outer join weareremployment we
              on     (we.wearer_id = w.wearer_id and we.sequencenumber = io.weareremploymentnumber)
              join   department t
              on     (t.departmentnumber = io.departmentnumber and t.customer_id = c.customer_id)
              join   distributionpoint dp
              on     (dp.distributionpointnumber = io.consumptionpointnumber and
                     dp.department_id = t.department_id)
              join   product p
              on     p.code = io.productcode
              join   sizedefinition s
              on     s.code = io.sizecode
              left   outer join stockroom st
              on     st.code = io.stockroomcode
              left   outer join reasoncode rs
              on     rs.code = io.reasoncode
              left   outer join ragreason rg
              on     rg.code = io.ragreasoncode
              left   outer join currency cy
              on     cy.code = io.currencycode
              left   outer join qualitygrade q
              on     q.code = io.qualitygradecode) loop
      begin
        insert into outofcirculationhistory
          (outofcirculationhistory_id, processbusinessunit_id, forbusinessunit_id,
           uniqueitem_link_id, outofcircdate, incircdate, reasoncode_id, quantity, outofcircyear,
           outofcircweek, outofcircday, weeksinuseprevissue, weeksinusethisissue, normlifetime,
           enddatefullrent, theoreticalpercentage, enteredpercentage, tobechargedpercentage,
           ragreason_id, customer_link_id, status, weareremployment_link_id,
           distributionpoint_link_id, product_link_id, workstationcode, customerowned,
           customerrelated, qualitygrade_id, residualvalue, currency_id, systemuser_id, timestamp,
           invoicebusinessunit_id, invoiceheader_id, primaryid, sizedefinition_link_id, amount,
           stockroom_id, chargetype, rowcode, locationcode, packingnote_id, areacode,
           minimumamountcharged)
        values
          (seq_outofcirculationhistory.nextval, x.procbu_id, x.forbu_id, null, x.outofcircdate,
           x.incircdate, x.reasoncode_id, x.quantity, x.outofcircyear, x.outofcircweek,
           x.outofcircday, x.weeksinuseprevissue, x.weeksinusethisissue, x.normlifetime,
           x.enddatefullrent, x.theoreticalpercentage, x.enteredpercentage, x.tobechargedpercentage,
           x.ragreason_id, x.customer_id, x.status, x.weareremployment_id, x.distributionpoint_id,
           x.product_id, x.workstationcode, x.customerowned, x.customerrelated, x.qualitygrade_id,
           x.residualvalue, x.currency_id, pack_import.lvnsystemuserid, sysdate, x.invbu_id, null,
           x.primaryid, x.sizedefinition_id, x.amount, x.stockroom_id, x.chargetype, x.rowcode,
           x.locationcode, -1, x.areacode, x.minimumamountcharged);
        --count records imported
        lv_counter := lv_counter + 1;
      end;
    end loop; --x
    commit;
    if lv_counter > 0 then
      begin
        pack_import.write_log(to_char(lv_counter) || ' outofcirculationhistory records imported', 1);
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('Error import_outofstockhistory ' || substr(sqlerrm, 1, 512), 3);
      end;
  end import_outofstockhistory;
  procedure import_issuehistory is
    lv_counter number := 0;
    begin
      gv_message := 'import_issuehistory';
      for x in (select ih.*, procbu.businessunit_id procbu_id, forbu.businessunit_id forbu_id,
                invbu.businessunit_id invbu_id, uil.uniqueitem_link_id, rc.reasoncode_id , c.customer_id,
                wel.weareremployment_link_id,dp.distributionpoint_id distribpointlink,
                p.product_id prodid, qg.qualitygrade_id issuegrade_id,qg2.qualitygrade_id requestedgrade_id,
                cy.currency_id, ihd.invoiceheader_id, sd.sizedefinition_id, s.stockroom_id,
                p2.product_id substprodid, sd2.sizedefinition_id substsizeid, wo.workorder_id,
                qg3.qualitygrade_id originalgrade_id, sl.stockroomlocation_id, sdi.stockdefinitionperitem_id originalstockdefperitem_id
                from i_issuehistory ih
                join   businessunit procbu
                 on    procbu.code = ih.processbusinessunitcode
                join   businessunit forbu
                 on    forbu.code = ih.forbusinessunitcode
                join   businessunit invbu
                 on     invbu.code = ih.invoicebusinessunitcode
                left outer join(uniqueitem_link uil
                left outer join uniqueitem ui
                  on uil.uniqueitem_id = ui.uniqueitem_id
                left outer join raggeditem ri
                  on uil.raggeditem_id = ri.raggeditem_id) on ui.primaryid = ih.primaryid
                left outer join reasoncode rc
                  on rc.code = ih.reasoncode
                join customer c
                  on c.customernumber = ih.customernumber
                left outer join wearer w
                  on (w.customer_id = c.customer_id and w.wearernumber = ih.wearernumber)
                left outer join weareremployment we
                  on (we.wearer_id = w.wearer_id and we.sequencenumber = ih.weareremploymentnumber)
                left outer join weareremployment_link wel
                  on wel.weareremployment_id = we.weareremployment_id
                join product p
                  on p.code = ih.productcode
                left outer join qualitygrade qg
                  on qg.code = ih.issuegrade
                left outer join qualitygrade qg2
                  on qg2.code = ih.requestedgrade
                left outer join qualitygrade qg3
                  on qg3.code = ih.originalgrade
                left outer join currency cy
                  on cy.code = ih.currency
                left outer join invoiceheader ihd
                  on (ihd.invoicenumber = ih.invoicenumber and ihd.billtocustomer_link_id = c.customer_id)
                left outer join department d
                  on c.customer_id = d.customer_id
                left outer join distributionpoint dp
                  on (d.department_id = dp.department_id and  dp.distributionpointnumber = ih.distributionpointnumber)
                join sizedefinition sd
                  on sd.code = ih.sizecode
                left outer join stockroom s
                  on s.code = ih.stockroom
                left outer join product p2
                  on p2.code = ih.substituteforproductcode
                left outer join sizedefinition sd2
                  on sd2.code = ih.subforsizecode
               left outer join workorder wo
                  on wo.workordernumber = ih.workordernumber
               left outer join stockroomlocation sl
                  on (s.stockroom_id = sl.stockroom_id and sl.locationcode = ih.stockroomlocation)
               left outer join(stockdefinitionperitem sdi
               left outer join stockroom osr
                   on sdi.stockroom_id = osr.stockroom_id
               left outer join customer cr
                   on cr.customer_id = sdi.customer_id
               left outer join product pr
                   on pr.product_id = sdi.product_id
               left outer join sizedefinition sz
                   on  sz.sizedefinition_id = sdi.sizedefinition_id)
               on (osr.code = ih.originalstockdefperitem
                   and pr.code = ih.productcode
                   and sz.code = ih.sizecode and
                   cr.customernumber = ih.customernumber)
               where not exists (select 1 from emblemhistory e
                                 where e.customer_link_id = c.customer_id
                                 and e.product_link_id = p.product_id
                                 and e.sizedefinition_link_id = sd.sizedefinition_id
                                 and e.weareremployment_link_id = wel.weareremployment_link_id
                                )
               )loop
        begin
    insert into issuehistory
      (issuehistory_id, processbusinessunit_id, forbusinessunit_id, uniqueitem_link_id,
       reasoncode_id, customer_link_id, weareremployment_link_id, distributionpoint_link_id,
       product_link_id, assigndate, incircdate, quantity, assignyear, assignweek, assignday,
       incircyear, incircweek, incircday, issuestatus, workstationcode, customerowned,
       customerrelated, issuegrade_id, requestedgrade_id, prepcharge, currency_id, systemuser_id,
       timestamp, invoicebusinessunit_id, invoiceheader_id, primaryid, amount, sizedefinition_link_id,
       stockroom_id, substituteforproduct_id, substituteforsizedefinition_id, workorder_id, exportdate,
       shipmentlistline_id, originalgrade_id, originalstockdefperitem_id, stockroomlocation_id,
       fromnonuniquestock, specialsizechargestatus, specialsizeprice
       )
     values
       (seq_issuehistory.nextval, x.procbu_id, x.forbu_id, x.uniqueitem_link_id, x.reasoncode_id,
        x.customer_id, x.weareremployment_link_id, x.distribpointlink, x.prodid, x.assigndate,
        x.incircdate, x.quantity, x.assignyear, x.assignweek,x.assignday,x.incircyear, x.incircweek,
        x.incircday, x.issuestatus, x.workstationcode, x.customerowned, x.customerrelated, x.issuegrade_id,
        x.requestedgrade_id, x.prepcharge, x.currency_id, pack_import.lvnsystemuserid, sysdate, x.invbu_id,
        x.invoiceheader_id, x.primaryid, x.amount, x.sizedefinition_id, x.stockroom_id, x.substprodid,
        x.substsizeid, x.workorder_id, x.exportdate, x.shipmentlistline, x.originalgrade_id,
        x.originalstockdefperitem_id, x.stockroomlocation_id, x.fromnonuniquestock, x.specialsizechargestatus,
        x.specialsizeprice );
        --count records imported
        lv_counter := lv_counter + 1;
     end;
     end loop;
     commit;
    if lv_counter > 0 then
      begin
        pack_import.write_log(to_char(lv_counter) || ' issuehistory records imported', 1);
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('Error import_issuehistory ' || substr(sqlerrm, 1, 512), 3);
      end;
  end import_issuehistory;
  procedure import_emblemhistory is
     lv_counter number := 0;
     lv_issuehistoryid issuehistory.issuehistory_id%type;
    begin
        gv_message := 'import_emblemhistory';
        for x in (select i.*, bu.businessunit_id processbuid, forbu.businessunit_id forbuid,
          uil.uniqueitem_link_id, rs.reasoncode_id, c.customer_id, we.weareremployment_id,
          dp.distributionpoint_id, p.product_id, qg.qualitygrade_id issuegradeid,
          qg2.qualitygrade_id requestedgradeid, cy.currency_id currencycodeid, invbu.businessunit_id invbuid,
          sd.sizedefinition_id, s.stockroom_id, substprod.product_id substprodid, substsize.sizedefinition_id substsizeid,
          wo.workorder_id, sl.shipmentlistline_id, qg3.qualitygrade_id origgradeid,
          sdi.stockdefinitionperitem_id, stl.stockroomlocation_id , cy2.currency_id currencyid,
          emblempr.product_id emblemprid, et.emblemtemplate_id
          from i_emblemhistory i
          join businessunit bu
            on bu.code = i.businessunitcode
          join businessunit forbu
            on forbu.code = i.forbusinessunitcode
          join businessunit invbu
            on invbu.code = i.invoicebusinessunitcode
          left outer join(uniqueitem_link uil
          left outer join uniqueitem ui
            on uil.uniqueitem_id = ui.uniqueitem_id
          left outer join raggeditem ri
            on uil.raggeditem_id = ri.raggeditem_id) on ui.primaryid = i.primaryid
          left outer join reasoncode rs
            on  rs.code = i.reasoncode
          join customer c
            on c.customernumber = i.customernumber
          left outer join weareremployment_link wearer
            on (i.wearernumber = wearer.wearernumber and i.weareremploymentnumber = wearer.sequencenumber)
          join weareremployment we
            on wearer.weareremployment_id = we.weareremployment_id
          join wearer w
            on (w.wearer_id = we.wearer_id and w.customer_id = c.customer_id)
          join distributionpoint_link dpl
            on i.distributionpointnumber = dpl.distributionpointnumber
          join distributionpoint dp
            on (dp.distributionpoint_id  = dpl.distributionpoint_link_id and i.distributionpointnumber = dp.distributionpointnumber)
          join department d
            on (d.customer_id = c.customer_id and d.department_id = dp.department_id)
          join product p
            on p.code = i.productcode
          left outer join qualitygrade qg
            on qg.code = i.issuegrade
          left outer join qualitygrade qg2
            on qg2.code = i.issuegrade
          left outer join qualitygrade qg3
            on qg3.code = i.originalgrade
          left outer join currency cy
            on cy.code = i.currencycode
          join sizedefinition sd
            on sd.code = i.sizecode
          left outer join stockroom s
            on s.code = i.stockroomcode
          left outer join product substprod
            on substprod.code = i.substituteforproductcode
          left outer join sizedefinition substsize
            on substsize.code = i.subforsizecode
          left outer join workorder wo
            on wo.workordernumber = i.workordernumber
          left outer join shipmentlistline sl
            on sl.transportunitnumber = i.shipmentlistline
          left outer join stockdefinitionperitem sdi
            on (sdi.product_id = p.product_id
            and sdi.sizedefinition_id = sd.sizedefinition_id
            and sdi.stockroom_id = s.stockroom_id
            and sdi.customer_id = c.customer_id
            )
          left outer join stockroomlocation stl
            on stl.locationcode = i.stockroomlocation
          left outer join currency cy2
            on cy2.code = i.currency
          left outer join product emblempr
            on emblempr.code = i.emblemproductcode
          left outer join emblemtemplate et
            on (et.code = i.emblemtemplate and et.customer_id = c.customer_id)
          )loop
   begin
       insert into issuehistory
         (issuehistory_id, processbusinessunit_id, forbusinessunit_id, uniqueitem_link_id,
          reasoncode_id, customer_link_id, weareremployment_link_id, distributionpoint_link_id,
          product_link_id, assigndate, incircdate, quantity, assignyear, assignweek, assignday,
          incircyear, incircweek, incircday, issuestatus, workstationcode, customerowned,
          customerrelated, issuegrade_id, requestedgrade_id, prepcharge, currency_id, systemuser_id,
          timestamp, invoicebusinessunit_id, invoiceheader_id, primaryid, amount, sizedefinition_link_id,
          stockroom_id, substituteforproduct_id, substituteforsizedefinition_id, workorder_id, exportdate,
          shipmentlistline_id, originalgrade_id, originalstockdefperitem_id, stockroomlocation_id,
          fromnonuniquestock, specialsizechargestatus, specialsizeprice, exchangechargestatus, exchangechargeprice
         )
       values
         (seq_issuehistory.nextval, x.processbuid, x.forbuid, x.uniqueitem_link_id, x.reasoncode_id,
          x.customer_id, x.weareremployment_id, x.distributionpoint_id, x.product_id,
          x.assigndate, x.incircdate, x.issuehistoryquantity, x.assignyear, x.assignweek, x.assignday, x.incircyear,
          x.incircweek, x.incircday, x.issuestatus, x.workstationcode, x.customerowned, x.customerrelated,
          x.issuegradeid, x.requestedgradeid, x.prepcharge, x.currencycodeid, pack_import.lvnsystemuserid,
          sysdate, x.invbuid, null, x.primaryid, x.issuehistoryamount, x.sizedefinition_id, x.stockroom_id, x.substprodid,
          x.substsizeid, x.workorder_id, x.exportdate, x.shipmentlistline_id, x.origgradeid, x.stockdefinitionperitem_id,
          x.stockroomlocation_id, x.fromnonuniquestock, x.specialsizechargestatus, x.specialsizeprice, x.exchangechargestatus,
          x.exchangechargeprice
         )
       returning issuehistory_id into lv_issuehistoryid;
       insert into emblemhistory
         (emblemhistory_id, issuehistory_id, businessunit_id, uniqueitem_link_id,
          issuedate, emblemtype, quantity, year, week, day, customer_link_id,
          status, weareremployment_link_id, distributionpoint_link_id, product_link_id,
          workstationcode, reasoncode_id, emblemcharge, currency_id, systemuser_id,
          timestamp, invoicebusinessunit_id, emblemproduct_id, emblemtemplateline_id,
          invoiceheader_id, primaryid, amount, sizedefinition_link_id, stockroom_id)
       values
        (seq_emblemhistory.nextval, lv_issuehistoryid, x.processbuid, x.uniqueitem_link_id,
         x.issuedate, x.emblemtype, x.quantity, x.year, x.week, x.day, x.customer_id,
         x.status, x.weareremployment_id, x.distributionpoint_id, x.product_id,
         x.workstationcode, x.reasoncode_id, x.emblemcharge, x.currencyid, pack_import.lvnsystemuserid,
         sysdate, x.invbuid, x.emblemprid, x.emblemtemplate_id, null, x.primaryid, x.amount,
         x.sizedefinition_id, x.stockroom_id
          );
    end;
        end loop;
        commit;
          if lv_counter > 0 then
      begin
        pack_import.write_log(to_char(lv_counter) || ' emblemhistory records imported', 1);
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('Error import_emblemhistory ' || substr(sqlerrm, 1, 512), 3);
      end;
    end import_emblemhistory;
  procedure import_allocationtrans is
  begin
     update i_allocationtrans i set i.emergency = 0 where i.emergency is null and i.transactiontype = 2;
     update i_allocationtrans i set i.returned = 0 where i.returned is null and i.transactiontype = 3;
     update i_allocationtrans i set i.returned = null where i.transactiontype != 3;
    insert into allocationtransaction
      (allocationtransaction_id,
       allocationdate,
       todistributionpoint_link_id,
       product_link_id,
       sizedefinition_link_id,
       finishingmethod_id,
       stockcountschedule_link_id,
       fromdistributionpoint_link_id,
       transactiontype,
       parlevel,
       onhand,
       stocked,
       origin,
       EMERGENCY,
       returned,
       webuser_id,
       uploadtimestamp,
       systemuser_id,
       timestamp)
      select seq_allocationtransaction.nextval,
             x.allocationdate,
             x.dpt_id,
             x.product_id,
             x.sizedefinition_id,
             x.finishingmethod_id,
             x.stockcountschedule_id,
             x.dpf_id,
             x.transactiontype,
             x.parlevel,
             x.onhand,
             x.stocked,
             x.origin,
             x.emergency,
             x.returned,
             x.webuser_id,
             x.allocationdate,
             1,
             sysdate
        from (select i.allocationdate,
                     dpt.distributionpoint_id dpt_id,
                     p.product_id,
                     s.sizedefinition_id,
                     f.finishingmethod_id,
                     sc.stockcountschedule_id,
                     dpf.distributionpoint_id dpf_id,
                     i.transactiontype,
                     max(i.parlevel) parlevel,
                     max(i.onhand) onhand,
                     max(i.stocked) stocked,
                     max(i.origin) origin,
                     max(i.emergency) emergency,
                     max(i.returned) returned,
                     max(w.webuser_id) webuser_id
                from i_allocationtrans i
                join customer cf
                  on cf.customernumber = i.fromcustomernumber
                join department df
                  on df.customer_id = cf.customer_id
                 and df.departmentnumber = i.fromdepartmentnumber
                join distributionpoint dpf
                  on dpf.department_id = df.department_id
                 and dpf.distributionpointnumber = i.fromdistribpointnumber
                join customer ct
                  on ct.customernumber = i.tocustomernumber
                join department dt
                  on dt.customer_id = ct.customer_id
                 and dt.departmentnumber = i.todepartmentnumber
                join distributionpoint dpt
                  on dpt.department_id = dt.department_id
                 and dpt.distributionpointnumber = i.todistribpointnumber
                join product p
                  on p.code = i.productcode
                join sizedefinition s
                  on s.code = i.sizecode
                join finishingmethod f
                  on f.code = i.fmcode
                left join customer csc
                  on csc.customernumber = i.cscustomernumber
                left join stockcountschedule sc
                  on sc.customer_id = csc.customer_id
                 and sc.code = i.stockcountcode
                left join webuser w
                  on w.loginname = i.loginname
               where not exists
               (select 1
                        from allocationtransaction a
                       where a.allocationdate = i.allocationdate
                         and a.TODISTRIBUTIONPOINT_LINK_ID =
                             dpt.distributionpoint_id
                         and a.product_link_id = p.product_id
                         and a.sizedefinition_link_id = s.sizedefinition_id
                         and a.finishingmethod_id = f.finishingmethod_id
                         and a.transactiontype = i.transactiontype)
               group by i.ALLOCATIONDATE,
                        dpt.distributionpoint_id,
                        p.product_id,
                        s.sizedefinition_id,
                        f.finishingmethod_id,
                        dpf.distributionpoint_id,
                        sc.stockcountschedule_id,
                        i.TRANSACTIONTYPE) x;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('Error import_allocationtrans ' || substr(sqlerrm, 1, 512), 3);
      end;
  end import_allocationtrans;
end pack_import_history;
/
create or replace package pack_import_invoice is
  -- Author  : CRISTINA
  -- Version : 1.0
  -- Created : 11/06/2002 11:54:03 AM
  -- Changes: TNE order 500468 insert routecontrol
  procedure cfbimportinvoiceheader;
  procedure cfbcreateroutecontrol;
  procedure cfbcreatesoilticketfrominvoice;
  procedure cfbimportinvoiceline;
end pack_import_invoice;
/
create or replace package body pack_import_invoice is
  errormsg varchar2(256);
  procedure add_missing_routes is
    lvndistrict                 route.district_id%type;
    lvndefaultdeliveryscheme_id deliveryscheme.deliveryscheme_id%type;
    lvncounter                  number := 0;
  begin
    --add missing routes
    --get default deliveyscheme
    select min(ds.deliveryscheme_id)
    into   lvndefaultdeliveryscheme_id
    from   deliveryscheme ds
    where  ds.offsetweek = 0
    and    ds.frequency = 1;
    --loop missing routes and add them
    for r in (select pt.plant_id, i.routenumber, getabsdaynumber(i.invoicedate) day_id
              from   i_invoiceheader i, businessunit bu, plant pt
              where  i.routenumber is not null
              and    i.businessunit = bu.code
              and    bu.plant_id = pt.plant_id
              and    not exists (select 1
                      from   route rt
                      where  rt.routenumber = i.routenumber
                      and    rt.drivingday_id = getabsdaynumber(i.invoicedate)
                      and    rt.plant_id = pt.plant_id)
              group  by pt.plant_id, i.routenumber, getabsdaynumber(i.invoicedate)) loop
      begin
        --get district
        select min(dp.district_id)
        into   lvndistrict
        from   districtplant dp
        where  dp.plant_id = r.plant_id;
        --insert route
        insert into route
          (route_id, plant_id, drivingday_id, routenumber, description, depot_id, systemuser_id,
           codeonlabel, timestamp, driver_id, truck_id, starttime, endtime, packingday_id,
           packingdeadline, loadingdock, putupreportpercustomer, putupreportperroute,
           putupreportperdepot, putupreportroutestop, printsoilticket, printorderform,
           bundletagsflatw, bundletagsgarm, deliveryscheme_id, district_id, routemanager_id)
        values
          (seq_route.nextval, r.plant_id, r.day_id, r.routenumber,
           to_char(r.routenumber) || ' CONVERSION ADDED', null, pack_import.lvnsystemuserid, null,
           sysdate, null, null, null, null, null, null, null, 0, 'N', 'N', 0, 'N', 1, 0, 0,
           lvndefaultdeliveryscheme_id, lvndistrict, null);
        --counter
        lvncounter := lvncounter + 1;
      end;
    end loop;
    commit;
    if lvncounter > 0 then
      begin
        pack_import.write_log(to_char(lvncounter) || ' routes added for invoiceheaders.');
      end;
    end if;
  end add_missing_routes;
  procedure cfbimportinvoiceheader is
    ncountrows          integer;
    routeid             route.route_id%type;
    nstartyear          integer;
    nendyear            integer;
    statesid            states.states_id%type;
    cityid              citycounty.citycounty_id%type;
    countyid            citycounty.citycounty_id%type;
    lvnstatusid         status.status_id%type;
    fpninvoiceheader_id invoiceheader.invoiceheader_id%type;
    fpnreasoncode_id    reasoncode.reasoncode_id%type;
  begin
    --execute immediate 'alter session set nls_territory = FRANCE';
    --PVD added to check status for invoiceheaderus..
    select s.status_id
    into   lvnstatusid
    from   status s
    where  s.statustype = 'IN'
    and    s.code = 1;
    -- trim
    begin
      update i_invoiceheader set zipcode = ltrim(rtrim(zipcode)), city = ltrim(rtrim(city));
    exception
      when others then
        null;
    end;
    begin
      -- pvd added to import route 0 as null for it does not exist.
      update i_invoiceheader set routenumber = null where routenumber = 0;
    exception
      when others then
        null;
    end;
    begin
      update i_invoiceheader
      set    street = ltrim(rtrim(street)), street2 = ltrim(rtrim(street2)), street3 = ltrim(rtrim(street3)),
             county = ltrim(rtrim(county)), state = ltrim(rtrim(state)),
             contactpersonname = ltrim(rtrim(contactpersonname)),
             emailaddress = ltrim(rtrim(emailaddress)),
             contactpersonphone = ltrim(rtrim(contactpersonphone)),
             adjustmentreasoncode = ltrim(rtrim(adjustmentreasoncode)),
             invoicecomments = ltrim(rtrim(invoicecomments)),
             deliverinstructions = ltrim(rtrim(deliverinstructions)),
             purchaseorder = ltrim(rtrim(purchaseorder)), driverremark = ltrim(rtrim(driverremark));
    exception
      when others then
        null;
    end;
    update i_invoiceheader h
    set    h.deliverinstructions = replace(h.deliverinstructions, '|', chr(10))
    where  h.deliverinstructions <> replace(h.deliverinstructions, '|', chr(10));
    update i_invoiceheader z
    set    z.driverremark = replace(z.driverremark, '|', chr(10))
    where  z.driverremark <> replace(z.driverremark, '|', chr(10));
    commit;
    -- reason code
    for vcursor in (select distinct x.adjustmentreasoncode
                    from   i_invoiceheader x
                    where  x.adjustmentreasoncode is not null
                    and    not exists (select a.reasoncode_id
                            from   reasoncode a
                            where  a.code = x.adjustmentreasoncode)) loop
      begin
        pack_import.cfbcreate_reasoncode(fpnreasoncode_id, vcursor.adjustmentreasoncode, 'N', 'Y',
                                         'Y', 'Y', 'N', 0, 'N', 'N', 1, 'N', 0, 'Y', 'N');
        pack_import.cfbcreate_reasoncode_desc(fpnreasoncode_id, vcursor.adjustmentreasoncode);
      exception
        when others then
          pack_import.write_log('Error adding reasoncode: ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    commit;
    --add missing routes
    add_missing_routes;
    -- invoice header
    ncountrows := 0;
    for vcursor in (select x.invoiceheader_id, b.customer_id billtoid, b.customernumber billtonumber,
                           b.name billtoname, delt.customer_id deltoid,
                           delt.customernumber deltonumber, delt.name deltoname, r.route_id,
                           (select e.status_id
                             from   status e
                             where  a.status = e.code
                             and    e.statustype = 'IN') status_id, f.reasoncode_id, g.code,
                           g.businessunit_id, a.*, b.extraname1, b.extraname2 ,b.currency_id
                    from   i_invoiceheader a
                    join   customer b
                    on     b.customernumber = a.billtocustomernumber
                    join   businessunit g
                    on     a.businessunit = g.code
                    left   outer join customer delt
                    on     delt.customernumber = a.deltocustomernumber
                    left   outer join route r
                    on     (r.routenumber = a.routenumber and r.plant_id = g.plant_id and
                           r.drivingday_id = getabsdaynumber(a.invoicedate))
                    left   outer join reasoncode f
                    on     f.code = a.adjustmentreasoncode
                    left   outer join invoiceheader x
                    on     (x.invoicenumber = a.invoicenumber and x.documenttype = a.documenttype)) loop
      -- routeID
      if (vcursor.route_id = -1) then
        routeid := null;
      else
        routeid := vcursor.route_id;
      end if;
      -- start year, end year
      if (vcursor.startmonth is not null or vcursor.startweek is not null) then
        nstartyear := to_char(vcursor.invoicedate, 'yyyy');
        nendyear   := to_char(vcursor.invoicedate, 'yyyy');
        -- to do: nEndYear
      else
        nstartyear := 0;
        nendyear   := 0;
      end if;
      -- statesID
      statesid := null;
      if (vcursor.statestaxrate is not null and vcursor.statestaxrate != 0) then
        begin
          select min(b.states_id)
          into   statesid
          from   customer_link a, customer b
          where  a.customer_id = b.customer_id
          and    b.states_id is not null
          and    b.customernumber = vcursor.deltonumber; --added to return only one row?????????????must be added also for city, county?
        exception
          when no_data_found then
            null;
        end;
      end if;
      -- cityID
      cityid := null;
      if (vcursor.citytaxrate is not null and vcursor.citytaxrate != 0) then
        begin
          select min(b.citytaxauthority_id)
          into   cityid
          from   customer_link a, customer b
          where  a.customer_id = b.customer_id
          and    b.citytaxauthority_id is not null
          and    b.customernumber = vcursor.deltonumber;
        exception
          when no_data_found then
            null;
        end;
      end if;
      -- countyID
      countyid := null;
      if (vcursor.countytaxrate is not null and vcursor.countytaxrate != 0) then
        begin
          select min(b.countytaxauthority_id)
          into   countyid
          from   customer_link a, customer b
          where  a.customer_id = b.customer_id
          and    b.countytaxauthority_id is not null
          and    b.customernumber = vcursor.deltonumber;
        exception
          when no_data_found then
            null;
        end;
      end if;
      begin
        if (vcursor.invoiceheader_id is null) then
          pack_import.cfbcreate_invoiceheader(fpninvoiceheader_id,
                                              --fpninvoiceheader_id,
                                              vcursor.invoicedate,
                                              --fpdtinvoicedate,
                                              vcursor.invoicenumber,
                                              --fpninvoicenumber,
                                              vcursor.documenttype,
                                              --fpndocumenttype,
                                              vcursor.businessunit_id,
                                              --fpninvoicebusinessunit_id,
                                              vcursor.billtoid,
                                              --fpnbilltocustomer_link_id,
                                              vcursor.deltoid,
                                              --fpndeltocustomer_link_id,
                                              nvl(vcursor.endweek, 0),
                                              --fpnendweek,
                                              nvl(vcursor.startweek, 0),
                                              --fpnstartweek,
                                              nvl(vcursor.endmonth, 0),
                                              --fpnendmonth,
                                              nvl(vcursor.startmonth, 0),
                                              --fpnstartmonth,
                                              vcursor.county,
                                              --fpscounty,
                                              vcursor.state,
                                              --fpsstate,
                                              vcursor.city,
                                              --fpscity,
                                              vcursor.zipcode,
                                              --fpszipcode,
                                              vcursor.street2,
                                              --fpsstreet2,
                                              vcursor.street,
                                              --fpsstreet,
                                              vcursor.deltoname,
                                              --fpsdeltocustomername,
                                              vcursor.deltonumber,
                                              --fpndeltocustomernumber,
                                              vcursor.billtoname,
                                              --fpsbilltocustomername,
                                              vcursor.billtonumber,
                                              --fpnbilltocustomernumber,
                                              null,
                                              --fpnroutecontrol_id,
                                              routeid,
                                              --fpnroute_id,
                                              vcursor.contactpersonphone,
                                              --fpscontactpersonphone,
                                              vcursor.emailstatus,
                                              --fpsemailstatus,
                                              vcursor.emailaddress,
                                              --fpsemailaddress,
                                              vcursor.contactpersonname,
                                              --fpscontactpersonname,
                                              vcursor.stopnumber,
                                              --fpnstopnumber,
                                              vcursor.status_id,
                                              --fpnstatus_id,
                                              vcursor.realcollectiontype,
                                              --fpnrealcollectiontype,
                                              vcursor.originalcollectiontype,
                                              --fpnoriginalcollectiontype,
                                              vcursor.invoicetype,
                                              --fpninvoicetype,
                                              vcursor.reasoncode_id,
                                              --fpnadjustmentreason_id,
                                              vcursor.exported,
                                              --fpsexported,
                                              vcursor.purchaseorder,
                                              --fpspurchaseorder,
                                              vcursor.deliverinstructions,
                                              --fpsdeliverinstructions,
                                              vcursor.invoicecomments,
                                              --fpsinvoicecomments,
                                              vcursor.totalminusadjustment,
                                              --fpntotalminusadjustment,
                                              vcursor.totalplusadjustment,
                                              --fpntotalplusadjustment,
                                              vcursor.cashcollected,
                                              --fpncashcollected,
                                              vcursor.paythisamount,
                                              --fpnpaythisamount,
                                              vcursor.prebillamount,
                                              --fpnprebillamount,
                                              vcursor.frequency,
                                              --fpninvoicefrequency_id,
                                              vcursor.currency_id,
                                              --fpncurrency_id,
                                              vcursor.routenumber,
                                              --fpnroutenumber,
                                              nstartyear,
                                              --fpnstartyear,
                                              nendyear,
                                              --fpnendyear,
                                              null,
                                              --fpscontractcode,
                                              null,
                                              --fpsdepotcode,
                                              vcursor.startdate,
                                              --fpdtstartdate,
                                              vcursor.enddate,
                                              --fpdtenddate,
                                              vcursor.creditsqueezeperc,
                                              --fpncreditsqueezeperc,
                                              'Y',
                                              --fpsconvertedfromlegacy,
                                              vcursor.totalamountexclvat,
                                              --fpntotalamontexclvat,
                                              null,
                                              --fpnclusterid,
                                              vcursor.creditsqueeze,
                                              --fpncreditsqueezeamount,
                                              null,
                                              --fpnsplitupcode,
                                              null,
                                              --fpnsplitupdesc,
                                              null,
                                              --fpnstop_id,
                                              to_char(vcursor.invoicedate, 'iyyy'),
                                              --fpninvoiceyear,
                                              to_char(vcursor.invoicedate, 'iw'),
                                              --fpninvoiceweek,
                                              getabsdaynumber(vcursor.invoicedate),
                                              --fpninvoicedaynumber);
                                              vcursor.extraname1,
                                              --fpsextraname1,
                                              vcursor.extraname2,
                                              --fpsextraname2,
                                              null,
                                              --fpnparentinvoiceheaderid)
                                              null,
                                              --fpdtcontractstartdate,
                                              null,
                                              --fpdtcontractenddate,
                                              0,
                                              --fpnpaymentdiscountdays,
                                              0,
                                              --fpnnetpaymentdays,
                                              vcursor.street,
                                              --fpsdeltostreet,
                                              vcursor.street2,
                                              --fpsdeltostreet2,
                                              vcursor.county,
                                              --fpsdeltocounty,
                                              vcursor.state,
                                              --fpsdeltostate,
                                              nvl(vcursor.city, '-'),
                                              --fpsdeltocity,
                                              nvl(vcursor.zipcode, '-'),
                                               --fpsdeltozipcode
                                              vcursor.street3);
          --PVD added the adding to invoiceheaderus..
          if vcursor.status_id = lvnstatusid then
            begin
              pack_import.cfbcreate_invoiceheaderus(fpninvoiceheader_id,
                                                    --fpninvoiceheader_id,
                                                    statesid,
                                                    --fpntaxstates_id,
                                                    vcursor.statestaxrate,
                                                    --fpnstatestaxrate,
                                                    cityid,
                                                    --fpntaxcity_id,
                                                    vcursor.citytaxrate,
                                                    --fpncitytaxrate,
                                                    countyid,
                                                    --fpntaxcounty_id,
                                                    vcursor.countytaxrate
                                                    --fpncountytaxrate,
                                                    );
            exception
              when dup_val_on_index then
                null; --PVD no problem they were already there...
              when others then
                errormsg := 'Error creating invoiceheaderus: for invoicenumber ' ||
                            to_char(vcursor.invoicenumber);
                pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
            end;
          end if; --end added the adding to invoiceheaderus..
        else
          -- update
          update invoiceheader
          set    realcollectiontype = vcursor.realcollectiontype, status_id = vcursor.status_id,
                 adjustmentreason_id = vcursor.reasoncode_id,
                 totalminusadjustment = vcursor.totalminusadjustment,
                 totalplusadjustment = vcursor.totalplusadjustment,
                 cashcollected = vcursor.cashcollected, paythisamount = vcursor.paythisamount,
                 prebillamount = vcursor.prebillamount, exported = vcursor.exported,
                 purchaseorder = vcursor.purchaseorder,
                 deliverinstructions = vcursor.deliverinstructions,
                 invoicecomments = vcursor.invoicecomments
          where  invoiceheader_id = vcursor.invoiceheader_id;
          --PVD added the adding to invoiceheaderus..
          if vcursor.status_id = lvnstatusid then
            begin
              pack_import.cfbcreate_invoiceheaderus(fpninvoiceheader_id,
                                                    --fpninvoiceheader_id,
                                                    statesid,
                                                    --fpntaxstates_id,
                                                    vcursor.statestaxrate,
                                                    --fpnstatestaxrate,
                                                    cityid,
                                                    --fpntaxcity_id,
                                                    vcursor.citytaxrate,
                                                    --fpncitytaxrate,
                                                    countyid,
                                                    --fpntaxcounty_id,
                                                    vcursor.countytaxrate
                                                    --fpncountytaxrate,
                                                    );
            exception
              when others then
                errormsg := 'Error updating invoiceheaderus: for invoicenumber ' ||
                            to_char(vcursor.invoicenumber);
                pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
            end;
          end if; --end added the adding to invoiceheaderus..
        end if;
        ncountrows := ncountrows + 1;
      exception
        when others then
          errormsg := 'CFbImportInvoiceHeader: Fail to import invoice header number/date ' ||
                      vcursor.invoicenumber || '/' || vcursor.invoicedate;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    begin
      -- insert into invoiceheaderextrainfo
      insert into invoiceheaderextrainfo
        (invoiceheader_id, formlayoutcode, billtocountrydescription, deltocountrydescription,
         bankinstitution_id, laundrybankinstitution_id, bankaccount, ibanno, deltocustvatnumber,
         invoicecopies, customermarkinggarment, taxable, siccode, attachinvoicecopies,
         paymenttermsdescription, acceptgiroreference, acceptgirocodeline, paymenttype, discountdays,
         paymentdiscount, discountdays2, paymentdiscount2, checknumber, paymenttermsduedate,
         paymenttermstype, paybycustomer_link_id)
        select
        /* 10/09/2008/HVH Solved issues in filling invoiceheaderextrainfo
           paymenttermsdescription, acceptgirocodeline, paymenttype, paymentdiscount and
           paymenttermstype were filled incorrect.
        */
        --        invoiceheader_id,
         ih.invoiceheader_id,
         --        formlayoutcode,
         (select min(b.code)
           from   customer a, formlayout b
           where  a.invoicelayout_id = b.formlayout_id
           and    a.customer_id = ih.deltocustomer_link_id),
         --        billtocountrydescription,
         (select nvl(b.description, '-')
           from   customer a, country b
           where  a.country_id = b.country_id
           and    a.customer_id = ih.billtocustomer_link_id),
         --        deltocountrydescription,
         (select nvl(b.description, '-')
           from   customer a, country b
           where  a.country_id = b.country_id
           and    a.customer_id = ih.deltocustomer_link_id),
         --         bankinstitution_id,
         (select c.bankinstitution_id
           from   customerbillinginfo c
           where  c.customer_id = ih.billtocustomer_link_id),
         --         laundrybankinstitution_id,
         null,
         --         bankaccount,
         (select c.bankaccount
           from   customerbillinginfo c
           where  c.customer_id = ih.billtocustomer_link_id),
         --         ibanno,
         (select c.ibanno from customerbillinginfo c where c.customer_id = ih.billtocustomer_link_id),
         --         deltocustvatnumber,
         null,
         --         invoicecopies,
         1,
         --         customermarkinggarment,
         null,
         --         taxable,
         'Y',
         --         siccode,
         null,
         --         attachinvoicecopies,
         nvl((select c.attachinvoicecopies
              from   customerbillinginfo c
              where  c.customer_id = ih.billtocustomer_link_id), 'N'),
         --         paymenttermsdescription
         (select p.description
           from   customer c, customerbillinginfo cbi, paymentterms_desc p
           where  c.customer_id = ih.billtocustomer_link_id
           and    c.customer_id = cbi.customer_id
           and    cbi.paymentterms_id = p.paymentterms_id
           and    c.language_id = p.language_id),
         --        acceptgiroreference,
         null,
         --        acceptgirocodeline
         null,
         --        paymenttype,
         (select c.paymenttype
           from   customer c
           where  c.customer_id = ih.billtocustomer_link_id
           and    c.paymenttype is not null),
         --        discountdays,
         -- HVH 12/09/2008 Corrected position of NVL to prevent null values.
         nvl((select p.discountdays
              from   customerbillinginfo c, paymentterms p
              where  c.customer_id = ih.billtocustomer_link_id
              and    c.paymentterms_id = p.paymentterms_id
              and    p.discountdays != 0), 0),
         --         paymentdiscount,
         nvl((select p.paymentdiscount
              from   customerbillinginfo c, paymentterms p
              where  c.customer_id = ih.billtocustomer_link_id
              and    c.paymentterms_id = p.paymentterms_id
              and    p.paymentdiscount != 0), 0),
         --         discountdays2,
         nvl((select p.discountdays2
              from   customerbillinginfo c, paymentterms p
              where  c.customer_id = ih.billtocustomer_link_id
              and    c.paymentterms_id = p.paymentterms_id
              and    p.discountdays2 != 0), 0),
         --         paymentdiscount2,
         nvl((select p.paymentdiscount2
              from   customerbillinginfo c, paymentterms p
              where  c.customer_id = ih.billtocustomer_link_id
              and    c.paymentterms_id = p.paymentterms_id
              and    p.paymentdiscount2 != 0), 0),
         --         checknumber,
         null,
         --         paymenttermsduedate,
         nvl((select i.paymenttermsduedate
              from   i_invoiceheader i
              where  i.invoicenumber = ih.invoicenumber), ih.invoicedate),
         --         paymenttermstype
         nvl((select p.paymenttermtype
              from   customerbillinginfo c, paymentterms p
              where  c.customer_id = ih.billtocustomer_link_id
              and    c.paymentterms_id = p.paymentterms_id
              and    p.paymenttermtype != 0), 0),
         --        paybycustomer_link_id
         (select a.paybycustomer_link_id
           from   customerbillinginfo a
           where  a.customer_id = ih.billtocustomer_link_id)
        from   invoiceheader ih
        where  ih.documenttype = 1
        and    not exists (select o.invoiceheader_id
                from   invoiceheaderextrainfo o
                where  o.invoiceheader_id = ih.invoiceheader_id);
    exception
      when others then
        begin
          errormsg := 'CFbImportInvoiceHeader: Fail to import invoiceheaderextrainfo!';
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
        end;
    end; --invoiceheaderextrainfo
    commit;
    if ncountrows > 0 then
      pack_import.write_log(ncountrows || ' invoice header rows imported.');
    end if;
  end cfbimportinvoiceheader;
  --insert routecontrol
  procedure cfbcreateroutecontrol is
    routecontrolid      routecontrol.routecontrol_id%type;
    totalcodprebill     routecontrol.totalcodprebilled%type := 0;
    totalcodpaythis     routecontrol.totalcodpaythisamnt%type := 0;
    totalcodundeliv     routecontrol.totalcodundelivered%type := 0;
    totalcodminusadj    routecontrol.totalcodminusadj%type := 0;
    totalcodplusadj     routecontrol.totalcodplusadj%type := 0;
    totalcoddelay       routecontrol.totalcoddelayed%type := 0;
    totalcashcollect    routecontrol.totalcashcollected%type := 0;
    totalchargeprebill  routecontrol.totalchargeprebilled%type := 0;
    totalchargepaythis  routecontrol.totalchargepaythisamnt%type := 0;
    totalchargeundeliv  routecontrol.totalchargeundelivered%type := 0;
    totalchargeminusadj routecontrol.totalchargeminusadj%type := 0;
    totalchargeplusadj  routecontrol.totalchargeplusadj%type := 0;
    totalchargecollect  routecontrol.totalchargecollections%type := 0;
    statusid            status.status_id%type;
    countrows           integer;
    countrowsu          integer;
    npackingstatus      routecontrol.packingstatus%type := 2;
    ninvoicesgenerated  routecontrol.invoicesgenerated%type := 3;
  begin
    countrows  := 0;
    countrowsu := 0;
		for vcursor in (select i.routenumber,
		   ih.invoicedate,
		   ih.originalcollectiontype,
		   r.route_id,
		   b.plant_id,
		   rc.routecontrol_id,
		   nvl(sum(ih.prebillamount), 0) totalprebill,
		   nvl(sum(ih.paythisamount), 0) totalpaythis,
		   nvl(sum(ih.totalminusadjustment), 0) minusadjustment,
		   nvl(sum(ih.totalplusadjustment), 0) plusadjustment,
		   nvl(sum(ih.cashcollected), 0) cashcolect,
		   sum(case
				 when ih.adjustmentreason_id is not null then
				  ih.paythisamount
				 else
				  0
			   end) totalundeliv,
		   sum(case
				 when s.statustype = 'IN' and s.code = 2 then
				  1
				 else
				  0
			   end) s_status
	  from invoiceheader ih
	  join i_invoiceheader i
		on i.invoicedate = ih.invoicedate
	   and i.documenttype = ih.documenttype
	   and i.invoicenumber = ih.invoicenumber
	  join route r
		on r.routenumber = i.routenumber
	   and r.route_id = ih.route_id
	  join businessunit b
		on b.businessunit_id = ih.invoicebusinessunit_id
	   and b.code = i.businessunit
	   and b.plant_id = r.plant_id
	  left join status s
		on s.status_id = ih.status_id
	  left join routecontrol rc
		on rc.routecontrol_id = ih.routecontrol_id
	 where i.routenumber is not null
	 group by i.routenumber,
			  ih.invoicedate,
			  ih.originalcollectiontype,
			  r.route_id,
			  b.plant_id,
			  rc.routecontrol_id
		) loop
      begin
        if vcursor.originalcollectiontype = 1 then
          totalcodprebill  := nvl(vcursor.totalprebill, 0);
          totalcodpaythis  := nvl(vcursor.totalpaythis, 0);
          totalcodundeliv  := nvl(vcursor.totalundeliv, 0);
          totalcodminusadj := nvl(vcursor.minusadjustment, 0);
          totalcodplusadj  := nvl(vcursor.plusadjustment, 0);
          totalcashcollect := nvl(vcursor.cashcolect, 0);
          totalcoddelay    := totalcodpaythis - totalcashcollect;
        else
          totalchargeprebill  := nvl(vcursor.totalprebill, 0);
          totalchargepaythis  := nvl(vcursor.totalpaythis, 0);
          totalchargeundeliv  := nvl(vcursor.totalundeliv, 0);
          totalchargeminusadj := nvl(vcursor.minusadjustment, 0);
          totalchargeplusadj  := nvl(vcursor.plusadjustment, 0);
          totalchargecollect  := nvl(vcursor.cashcolect, 0);
        end if;
        if vcursor.s_status > 0 then
          statusid := 3;
        else
          statusid := 1;
        end if;
        begin
          insert into routecontrol
            (routecontrol_id, route_id, routelistprinted, soilticketsprinted, invoicesgenerated,
             soilcountstatus, settlementstatus, packingstatus, originaldrivingdate, drivingdate,
             drivernumber, packingday_id, overageamount, voucheramount, totalcashcollected,
             totalcoddelayed, totalcodpaythisamnt, totalcodundelivered, totalcodplusadj,
             totalcodminusadj, totalcodprebilled, totalchargecollections, totalchargepaythisamnt,
             totalchargeundelivered, totalchargeplusadj, totalchargeminusadj, totalchargeprebilled,
             returntime, returndate, starttime, loadingdock, packingdeadline, truckcode, plant_id,
             systemuser_id, timestamp, arbalance_id, pocketpcstatus, startmileage, endmileage,
             straightevenreturnstatus, routesettlementprinted, activestockcompleted,
             bulkputuproutecompleted)
          values
            (seq_routecontrol.nextval, vcursor.route_id, 'Y', 'Y', 3,
             --INVOICESGENERATED
             statusid,
             --SOILCOUNTSTATUS
             statusid,
             --SETTLEMENTSTATUS
             2,
             --PACKINGSTATUS
             vcursor.invoicedate,
             --ORIGINALDRIVINGDATE,
             vcursor.invoicedate,
             --.DRIVINGDATE
             null,
             --DRIVERNUMBER
             null,
             --.PACKINGDAY_ID
             0,
             --.OVERAGEAMOUNT
             0,
             --.VOUCHERAMOUNT
             nvl(totalcashcollect, 0), nvl(totalcoddelay, 0), nvl(totalcodpaythis, 0),
             nvl(totalcodundeliv, 0), nvl(totalcodplusadj, 0), nvl(totalcodminusadj, 0),
             nvl(totalcodprebill, 0), nvl(totalchargecollect, 0), nvl(totalchargepaythis, 0),
             nvl(totalchargeundeliv, 0), nvl(totalchargeplusadj, 0), nvl(totalchargeminusadj, 0),
             nvl(totalchargeprebill, 0), null,
             --RETURNTIME
             null,
             --RETURNDATE
             null,
             --STARTTIME
             null,
             --LOADINGDOCK
             null,
             --PACKINGDEADLINE
             null,
             --TRUCKCODE
             vcursor.plant_id, pack_import.lvnsystemuserid, sysdate, null,
             -- arbalance_id
             0,
             --fpnpocketpcstatus,
             0,
             --fpnstartmileage,
             0,
             --fpnendmileage,
             0,
             --fpnstraightevenreturnstatus);
             'N',
             --fpsroutesettlementprinted
             'Y', 'N'
             --FPsBULKPUTUPROUTECOMPLETED
             )
          returning routecontrol_id into routecontrolid;
          countrows := countrows + 1;
        exception
          when dup_val_on_index then
            begin
              select r.routecontrol_id
              into   routecontrolid
              from   routecontrol r
              where  r.route_id = vcursor.route_id
              and    r.drivingdate = vcursor.invoicedate;
              update routecontrol
              set    route_id = vcursor.route_id, invoicesgenerated = ninvoicesgenerated,
                     soilcountstatus = statusid, settlementstatus = statusid,
                     packingstatus = npackingstatus, originaldrivingdate = vcursor.invoicedate,
                     drivingdate = vcursor.invoicedate, totalcashcollected = totalcashcollect,
                     totalcoddelayed = totalcoddelay, totalcodpaythisamnt = totalcodpaythis,
                     totalcodundelivered = totalcodundeliv, totalcodplusadj = totalcodplusadj,
                     totalcodminusadj = totalcodminusadj, totalcodprebilled = totalcodprebill,
                     totalchargecollections = totalchargecollect,
                     totalchargepaythisamnt = totalchargepaythis,
                     totalchargeundelivered = totalchargeundeliv,
                     totalchargeplusadj = totalchargeplusadj,
                     totalchargeminusadj = totalchargeminusadj,
                     totalchargeprebilled = totalchargeprebill, plant_id = vcursor.plant_id,
                     systemuser_id = pack_import.lvnsystemuserid, timestamp = sysdate
              where  routecontrol_id = routecontrolid;
              countrowsu := countrowsu + 1;
            exception
              when dup_val_on_index then
                null; --PVD no problem they were already there...
              when others then
                errormsg := 'CFbCreateRouteControl: Fail to update routecontrol for route/date ' ||
                            vcursor.routenumber || '/' || vcursor.invoicedate;
                pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
            end;
          when others then
            errormsg := 'CFbCreateRouteControl: Fail to import/update routecontrol for route/date ' ||
                        vcursor.routenumber || '/' || vcursor.invoicedate;
            pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
        end;
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(countrows || ' routecontrol rows imported.');
    end if;
    if countrowsu > 0 then
      pack_import.write_log(countrowsu || ' routecontrol rows updated.');
    end if;
    --update invoiceheader for routecontrol_id
    countrows := 0;
    for vcursor in (select ih.invoiceheader_id, ih.invoicenumber, rt.routecontrol_id
                    from   invoiceheader ih, routecontrol rt
                    where  ih.invoicedate = rt.originaldrivingdate
                    and    exists (select 1
                            from   i_invoiceheader i
                            where  i.invoicedate = ih.invoicedate
                            and    i.invoicenumber = ih.invoicenumber)
                    and    ih.route_id = rt.route_id
                    and    ih.routecontrol_id is null) loop
      begin
        update invoiceheader
        set    routecontrol_id = vcursor.routecontrol_id
        where  invoiceheader_id = vcursor.invoiceheader_id;
        countrows := countrows + 1;
      exception
        when others then
          errormsg := 'CFbCreateRouteControl: Fail to update routecontrol for invoicenumber ' ||
                      vcursor.invoicenumber;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    if countrows > 0 then
      commit;
      pack_import.write_log(countrows || ' invoiceheader rows updated.');
    end if;
  end; --CFbCreateRouteControl
  procedure cfbcreatesoilticketfrominvoice is
    lvncountrows         integer := 0;
    fpnsoilticket_id     soilticket.soilticket_id%type;
    fpssoilticketnumber  soilticket.soilticketnumber%type := 0;
    fpnsoilticketline_id soilticketline.soilticketline_id%type;
    processed            soilticket.processed%type;
    error_sequence       exception;
  begin
    for x in (select h.invoicenumber, h.invoiceheader_id, h.invoicedate, h.deltocustomer_link_id,
                     h.invoicebusinessunit_id, h.stopnumber, rc.routecontrol_id, rc.soilcountstatus,
                     bu.code bu_code
              from   i_invoiceheader i, invoiceheader h, routecontrol rc, businessunit bu
              where  h.routecontrol_id = rc.routecontrol_id
              and    i.invoicenumber = h.invoicenumber
              and    i.status = '1'
              and    h.invoicebusinessunit_id = bu.businessunit_id
              and    i.businessunit = bu.code
              and    h.invoicedate = i.invoicedate
              and    h.documenttype = i.documenttype
              and    h.status_id = (select s.status_id
                                    from   status s
                                    where  s.statustype = 'IN'
                                    and    s.code = '1')
              and    not exists (select 1
                      from   i_soilticket st, route r
                      where  st.businessunitnumber = bu.code
                      and    st.routenumber = r.routenumber
                      and    r.route_id = h.route_id
                      and    st.customernumber = i.deltocustomernumber)) loop
      begin
        begin
          errormsg := 'creating sequence seq_soilticket_' || x.bu_code;
          execute immediate 'select seq_soilticket_' || x.bu_code || '.nextval from dual'
            into fpssoilticketnumber;
        exception when others then
          raise error_sequence;
        end;
        if (x.soilcountstatus = 3) then
          processed := 'Y';
        else
          processed := 'N';
        end if;
        insert into soilticket
          (soilticket_id, soilticketnumber, customer_id, routecontrol_id, processbusinessunit_id,
           routestopnumber, invoicenumber, invoicedate, countdate, importdate, exportdate,
           employee_id, systemuser_id, timestamp, processed, stop_id)
        values
          (seq_soilticket.nextval, fpssoilticketnumber, x.deltocustomer_link_id, x.routecontrol_id,
           x.invoicebusinessunit_id, x.stopnumber, x.invoicenumber, x.invoicedate,
           to_date('31-12-2099', 'DD-MM-YYYY'), to_date('31-12-2099', 'DD-MM-YYYY'),
           to_date('31-12-2099', 'DD-MM-YYYY'), null, pack_import.lvnsystemuserid, sysdate,
           processed, null)
        returning soilticket_id into fpnsoilticket_id;
        for y in (select l.invoiceheader_id, p.product_link_id, p.sizedefinition_link_id,
                         p.finishingmethod_id, min(l.linenumber) linenumber,
                         min(p.delayedevenexchange) delayedevenexchange,
                         sum(p.inventoryqty) inventoryqty
                  from   invoiceline l, invoicelineproduct p
                  where  l.invoiceheader_id = x.invoiceheader_id
                  and    l.invoiceline_id = p.invoiceline_id
                  and    p.product_link_id is not null
                  and    p.soilcountmethod > 0
                  group  by l.invoiceheader_id, p.product_link_id, p.sizedefinition_link_id,
                            p.finishingmethod_id) loop
          begin
            insert into soilticketline
              (soilticketline_id, soilticket_id, product_id, sizedefinition_id, finishingmethod_id,
               countlightframe, countkeypad, countconverted, countabused, delayedevenexchange,
               inventory, invoicelinenumber, soilweight, systemuser_id, timestamp, unrelatedloan)
            values
              (seq_soilticketline.nextval, fpnsoilticket_id, y.product_link_id,
               y.sizedefinition_link_id, y.finishingmethod_id, null, null, null, 0,
               y.delayedevenexchange, y.inventoryqty, y.linenumber, 0, pack_import.lvnsystemuserid,
               sysdate, 'N')
            returning soilticketline_id into fpnsoilticketline_id;
          exception
            when dup_val_on_index then
              null; --PVD no problem they were already there...
            when others then
              errormsg := 'Error creating soilticketline: for invoicenumber ' ||
                          fpssoilticketnumber;
              pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
          end;
        end loop;
        lvncountrows := lvncountrows + 1;
      exception
        when dup_val_on_index then
          null; --PVD no problem they were already there...
        when error_sequence then
           pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
        when others then
          errormsg := 'Error creating soilticket: for invoicenumber ' || fpssoilticketnumber;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    commit;
    if lvncountrows > 0 then
      begin
        pack_import.write_log('Create Soil Ticket From Invoice.');
        pack_import.write_log(to_char(lvncountrows) || ' soiltickets entered.');
      end;
    end if;
  end; --CFbCreateSoilTicketFromInvoice;
    -- Invoiceline
  procedure cfbimportinvoiceline is
    ncountrows          integer;
  begin
    ncountrows := 0;
    for vcursor in (select ih.invoiceheader_id, a.invoicenumber, a.linenumber,
                            a.code, a.description, a.extend, a.amount, a.price, a.billedqty,
                            a.taxtype, a.taxgroupcode, it.invoicelinetype_id, a.subtype
                    from   i_invoiceline a
                           join invoiceheader ih on ih.invoicenumber = a.invoicenumber
                           join invoicelinetype it on it.type = a.linetype
                           where a.invoicenumber <> 0
                    ) loop
      begin
        if (vcursor.invoiceheader_id is not null) then
       insert into invoiceline
         (invoiceline_id,
          invoiceheader_id,
          linenumber,
          code,
          description,
          extend,
          amount,
          price,
          billedqty,
          taxtype,
          taxgroupcode, ADJUSTEDAMOUNT,ADJUSTEDPRICE,DISCOUNTPERCENTAGE,SUBJECTTOMINIMUM,
          systemuser_id, timestamp, generated, invoicelinesubtype, INVOICELINETYPE_ID, ADJUSTMENTBILLEDQTY)
       values
         (seq_invoiceline.nextval,
          vcursor.invoiceheader_id,
          vcursor.linenumber,
          vcursor.code,
          vcursor.description,
          vcursor.extend,
          vcursor.amount,
          vcursor.price,
          vcursor.billedqty,
          vcursor.taxtype,
          vcursor.taxgroupcode, 0, 0, 0, 'N', 1, sysdate, 'N', vcursor.subtype,  vcursor.invoicelinetype_id, 0 );
       ncountrows := ncountrows + 1;
       end if;
      exception
        when others then
          errormsg := 'cfbimportinvoiceline: Fail to import invoiceline ' ||
                      vcursor.invoicenumber || '/' || vcursor.code;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    commit;
    if ncountrows > 0 then
      pack_import.write_log(ncountrows || ' invoicelines imported.');
    end if;
  end cfbimportinvoiceline;
end pack_import_invoice;
/
create or replace package pack_import_packingnote is
  -- Author  : ABS
  -- Created : 18-02-2015
  -- Version : 1.0
  -- Purpose : Convert packingnotes from legacy systems into ABSSolute
  procedure import_packingnote;
  procedure import_packingnotecontainer;
end pack_import_packingnote;
/
create or replace package body pack_import_packingnote is
  gv_message abslog.message%type;
  procedure import_packingnote is
    lv_processingbusinessunitid businessunit.businessunit_id%type;
    lv_plantid                  plant.plant_id%type;
    lv_internalprocessingbuid   businessunit.businessunit_id%type;
    lv_invoicebusinessunitid    businessunit.businessunit_id%type;
    lv_statusid                 status.status_id%type;
    lv_distributionpointid      distributionpoint.distributionpoint_id%type;
    lv_deliverypointid          deliverypoint.deliverypoint_id%type;
    lv_plantdepartmentid        plantdepartment.plantdepartment_id%type;
    lv_transportarticleid       transportarticle.transportarticle_id%type;
    lv_routeid                  route.route_id%type;
    lv_packingnoteid            packingnote.packingnote_id%type;
    lv_freeofchargereasoncodeid reasoncode.reasoncode_id%type;
    lv_productid                product.product_id%type;
    lv_sizeid                   sizedefinition.sizedefinition_id%type;
    lv_finishingmethodid        finishingmethod.finishingmethod_id%type;
    lv_packingnotelineid        packingnoteline.packingnoteline_id%type;
    lv_containertypeid          containertype.containertype_id%type;
    lv_weighingcategoryid       weighingcategory.weighingcategory_id%type;
    lv_externalsterilizationlotid externalsterilizationlot.externalsterilizationlot_id%type;
    lv_cleanroombatchId          cleanroombatch.cleanroombatch_id%type;
    lv_cont_productid           product.product_id%type;
    lv_cont_sizeid              sizedefinition.sizedefinition_id%type;
    lv_cont_finishingmethodid   finishingmethod.finishingmethod_id%type;
    lv_count_pn                 number := 0;
    lv_count_pnl                number := 0;
    lv_count_pnc                number := 0;
    lv_count_pnlc               number := 0;
    lv_count_clpn               number :=0;
 function get_cleanroombatchid(fp_cleanroombatchnumber in cleanroombatch.cleanroombatchnumber%type) return number is
     lvcleanroombatchId cleanroombatch.cleanroombatch_id%type;
      lv_workstation_id workstation.workstation_id%type;
  begin
    -- determine the cleanroombatch
    if fp_cleanroombatchnumber is null then
      return null;
    else
      begin
        select crb.cleanroombatch_id
              into lvcleanroombatchId
              from cleanroombatch crb
              where crb.cleanroombatchnumber = fp_cleanroombatchnumber;
        return lvcleanroombatchId;
      end;
    end if;
    return  lvcleanroombatchId;
  end get_cleanroombatchid;
  begin
    pack_import_sterilizationlot.cfbimport_sterilizationlot;
  pack_import_sterilizationlot.cfbimport_cleanroombatch;
  pack_import.write_log('Imported cleanroombatch and  sterilizationlots.');
  commit;
    gv_message := 'import_packingnote';
    --get containertype
    select min(ct.containertype_id)
    into   lv_containertypeid
    from   containertype ct
    where  ct.active = 'Y';
    --convert packingnotes
    for x in (select ipk.*
              from   i_packingnote ipk
              where  not exists (select 1 from packingnote pk where pk.notenumber = ipk.notenumber)) loop
      begin
        --processingbusinessunit
        gv_message := 'processingbusinessunit ' || x.processingbusinessunit;
        select bu.businessunit_id, bu.plant_id
        into   lv_processingbusinessunitid, lv_plantid
        from   businessunit bu
        where  bu.code = x.processingbusinessunit;
        --internalprocessingbu
        gv_message := 'internalprocessingbu ' || x.internalprocessingbu;
        select bu.businessunit_id
        into   lv_internalprocessingbuid
        from   businessunit bu
        where  bu.code = x.internalprocessingbu;
        --invoicebusinessunit
        gv_message := 'invoicebusinessunit ' || x.invoicebusinessunit;
        select bu.businessunit_id
        into   lv_invoicebusinessunitid
        from   businessunit bu
        where  bu.code = x.invoicebusinessunit;
        --get status
        gv_message := 'status ' || x.status;
        select st.status_id
        into   lv_statusid
        from   status st
        where  st.code = x.status
        and    st.statustype = 'PN';
        --get distributionpoint
        gv_message := ' consumptionnumber ' || x.consumptionpointnumber || ' for customer ' ||
                      x.customernumber || ' deparment ' || x.departmentnumber;
        select dp.distributionpoint_id
        into   lv_distributionpointid
        from   customer c
        join   department t
        on     t.customer_id = c.customer_id
        join   distributionpoint dp
        on     dp.department_id = t.department_id
        where  c.customernumber = x.customernumber
        and    t.departmentnumber = x.departmentnumber
        and    dp.distributionpointnumber = x.consumptionpointnumber;
        --get deliverypoint
        gv_message := 'deliverypoint ' || x.deliverypoint || ' for customer ' || x.customernumber;
        select dt.deliverypoint_id
        into   lv_deliverypointid
        from   deliverypoint dt
        join   customer c
        on     c.customer_id = dt.customer_id
        where  c.customernumber = x.customernumber
        and    dt.code = x.deliverypoint;
        --get plantdepartment
        gv_message := 'plant department ' || x.plantdepartmentcode || ' for bu ' ||
                      x.processingbusinessunit;
        select dp.plantdepartment_id
        into   lv_plantdepartmentid
        from   plantdepartment dp
        where  dp.code = x.plantdepartmentcode
        and    dp.plant_id =
               (select bu.plant_id
                 from   businessunit bu
                 where  bu.businessunit_id = lv_processingbusinessunitid);
        begin
          --get transport article
          gv_message := 'transport article ' || x.transportarticle;
          select ta.transportarticle_id
          into   lv_transportarticleid
          from   transportarticle ta
          where  ta.code = x.transportarticle;
        exception
          when no_data_found then
            begin
              pack_import.cfbcreate_transportarticle(lv_transportarticleid, x.transportarticle, 'N',
                                                     x.transportarticle);
            end;
        end;
        begin
          --get route
          gv_message := 'route ' || x.routenumber;
          select r.route_id
          into   lv_routeid
          from   route r
          where  r.routenumber = x.routenumber
          and    r.drivingday_id = getabsdaynumber(x.deliverydate)
          and    r.plant_id = lv_plantid;
        exception
          when no_data_found then
            begin
              lv_routeid := null;
            end;
        end;
        if x.freeofchargereasoncode is null then
          begin
            lv_freeofchargereasoncodeid := null;
          end;
        else
          begin
            --get reasoncode free of charge
            gv_message := 'free of charge reasoncode ' || x.freeofchargereasoncode;
            select rs.reasoncode_id
            into   lv_freeofchargereasoncodeid
            from   reasoncode rs
            where  rs.code = x.freeofchargereasoncode;
          end;
        end if;
         --get externalsterilizationlot_id
          if x.externalsterilizationlot is  null then
            begin
               lv_externalsterilizationlotid := null;
             end;
             else
               begin
                gv_message := 'externalsterilisationlotnumber  ' ||  x.externalsterilizationlot;
                select e.externalsterilizationlot_id
                into lv_externalsterilizationlotid
                from externalsterilizationlot e
                where e.lotnumber = x.externalsterilizationlot;
            end;
          end if;
          --get cleanroombatch_id
          gv_message         := 'clean room batch number ' ||  x.cleanroombatchnumber;
          lv_cleanroombatchId := get_cleanroombatchid(x.cleanroombatchnumber);
        --insert into packingnote
        gv_message := 'insert into packingnote';
        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,
           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, exported, finishedpacking, picklistprinted,
           invoicestatus, numberofcolli, emailstatus, emailmaybesent, processedtimestamp,
           processedsystemuser_id, signed, internalprocessingbu_id, creationsystemuser_id,
           salesnote_id, parceltracecode, calculatetransportcosts, pdfarchived, correctionfornote_id,
           correctconsignmentnote, pnremark)
        values
          (null /*employee_id*/, seq_packingnote.nextval, x.notenumber, x.productiondate,
           trunc(x.deliverydate), lv_statusid, x.remark, lv_distributionpointid, lv_deliverypointid,
           lv_plantdepartmentid, lv_transportarticleid, pack_import.lvnsystemuserid /*systemuser_id*/,
           lv_processingbusinessunitid, lv_routeid, sysdate, 'N' /*cleanreturn*/, 1
           /*sequencenumber*/, null /*deadline*/, 100 /*occupancy*/, lv_invoicebusinessunitid, null
           /*routecontrol_id*/, trunc(x.deliverydate) /*originaldeliverydate*/,
           trunc(x.deliverydate) /*enddateforuse*/, 1 /*origin*/, x.stopnumber,
           getabsdaynumber(x.deliverydate) /*daynumber*/, 0 /*correctednotenumber*/, sysdate
           /*creationtimestamp*/, x.referencenumber, null /*returndateloan*/, null /*stop_id*/, null
           /*consignmentnote_id*/, x.straightevenreturn, 0 /*numberofgarmentsinlocker*/, 0
           /*numberoflockers*/, null /*bulkpackingnote_id*/, lv_freeofchargereasoncodeid,
           getisoweek(x.deliverydate) /*week*/, getyearofweek(x.deliverydate) /*year*/, null
           /*weighingticket_id*/, 0 /*totalamount*/, 0 /*totalamountexcludingvat*/, 'N'
           /*pricescalculated*/, x.showoninvoiceappendix,
           case when x.remark is not null then 'Y' else 'N' end /*deliveryremark*/, 'N'
           /*exported*/, 0 /*finishedpacking*/, 'N' /*picklistprinted*/, 0 /*invoicestatus*/, 1
           /*numberofcolli*/, 0 /*emailstatus*/, 'Y' /*emailmaybesent*/, sysdate
           /*processedtimestamp*/, pack_import.lvnsystemuserid /* processedsystemuser_id*/, 'N'
           /*signed*/, lv_internalprocessingbuid, pack_import.lvnsystemuserid
           /*creationsystemuser_id*/, null /*salesnote_id*/, null /*parceltracecode*/, 'N'
           /*calculatetransportcosts*/, 'N' /*pdfarchived*/, null /* correctionfornote_id*/, 0
            /*correctconsignmentnote*/, x.pnremark)
        returning packingnote_id into lv_packingnoteid;
        if lv_cleanroombatchId is not null then
         begin
         gv_message := 'insert into cleanroombatchpackingnote';
          insert into cleanroombatchpackingnote
              (cleanroombatchpackingnote_id,
               cleanroombatch_id,
               packingnote_id,
               systemuser_id,
               timestamp,
               externalsterilizationlot_id)
            values
              (seq_cleanroombatchpackingnote.nextval,
               lv_cleanroombatchId,
               lv_packingnoteid,
               pack_import.lvnsystemuserid,
               sysdate,
               lv_externalsterilizationlotId);
             lv_count_clpn := lv_count_clpn + 1; --cleanroombatchpacking note counter
             if sql%rowcount > 0 then
              begin
                update packingnote pn
                   set pn.cleanroombatch = 'Y'
                 where pn.packingnote_id = lv_packingnoteid;
              end;
            end if;
          end;
         end if;
        lv_count_pn := lv_count_pn + 1;
        for pc in (select pnc.* from i_packingnotecontainer pnc where pnc.notenumber = x.notenumber) loop
        begin
            --get weighingcategory
            gv_message := 'weighingcategory code ' || pc.weighingcategorycode;
      if pc.weighingcategorycode is null then
        begin
        lv_weighingcategoryid := null;
           end;
      else
            select wc.weighingcategory_id
            into   lv_weighingcategoryid
            from   weighingcategory wc
            where  wc.code = pc.weighingcategorycode;
      end if;
            --insert into packingnotecontainer
            gv_message := 'insert into packingnotecontainer';
            insert into packingnotecontainer
              (packingnotecontainer_id, packingnote_id, sequencenumber, containertype_id,
               container_id, weighingcategory_id, tareweight, grossweight, soilportion,
               weightdecimals, weighingsequencenr, weighingtimestamp, systemuser_id, timestamp,
               amount, price, taxgroupcode, invoiceheader_id, specialquantity, speciallength,
               specialwidth, weightoverrride_id, internalcalcprice, fixedinternalcalcprice,
               baglabelidcode, deliveryscantimestamp)
            values
              (seq_packingnotecontainer.nextval, lv_packingnoteid, pc.sequencenumber,
               lv_containertypeid, null /*container_id*/, lv_weighingcategoryid, pc.tareweight,
               pc.grossweight, 0 /*soilportion*/, pc.weightdecimals, null /*weighingsequencenr*/,
               sysdate /*weighingtimestamp*/, pack_import.lvnsystemuserid /*systemuser_id*/, sysdate
               /*timestamp*/, 0 /*amount*/, 0 /*price*/, null /*taxgroupcode*/, null
               /*invoiceheader_id*/, pc.specialquantity, pc.speciallength, pc.specialwidth, null
               /*weightoverrride_id*/, 0
               /*internalcalcprice*/, 'N' /*fixedinternalcalcprice*/, null /*baglabelidcode*/, null
               /*deliveryscantimestamp*/);
            lv_count_pnc := lv_count_pnc + 1;
          end;
        end loop; --pc i_packingnotecontainer
        for y in (select pkl.* from i_packingnoteline pkl where pkl.notenumber = x.notenumber) loop
          begin
            --get product
            gv_message := 'productcode ' || y.productcode;
            select p.product_id into lv_productid from product p where p.code = y.productcode;
            --get size
            gv_message := 'size ' || y.sizecode;
            select s.sizedefinition_id
            into   lv_sizeid
            from   sizedefinition s
            where  s.code = y.sizecode;
            --get finishingmethod
            gv_message := 'finishingmethod ' || y.finishingmethod;
            select f.finishingmethod_id
            into   lv_finishingmethodid
            from   finishingmethod f
            where  f.code = y.finishingmethod;
            --insert packingnoteline
            gv_message := 'insert into packingnoteline';
            insert into packingnoteline
              (packingnoteline_id, product_id, packingsequence, standardamount, variationamount,
               finishingmethod_id, deliveredamount, price, discount, packingnote_id,
               sizedefinition_id, systemuser_id, location, timestamp, remarkforpackinginstructions,
               tobedeliveredamount, customcode, customdescription, replacementqty,
               autoreplacementqty, updaterentqty, adjustmentreason_id, origin, putuptype,
               freeofchargereason_id, nochargefirstissue, nochargeactiveseason, auxiliarystatus,
               deliveredcogqty, amount, taxgroupcode, bundleqty, nochargefirstissuecog,
               scannedbundles, pricecog, mountingorderline_id, invoiceheader_id, nodeliveryamount,
               nochargeprevrejected, nochargeprevshortage, deliveredamountnopickup,
               creationtimestamp, creationsystemuser_id, stockcountqty, normstocklevel,
               prevdeliveredqty, prevstandardqty, internalcalcpricelog, internalcalcpricecog,
               fixedinternalcalcprice, deliveredexclexcessqty, heavysoilqty, replacementlossqty,
               qtysold, receivedqty, assembledquantity)
            values
              (seq_packingnoteline.nextval, lv_productid, y.packingsequence, y.standardamount,
               y.variationamount, lv_finishingmethodid, y.deliveredamount, 0 /*price*/, 0
               /*discount*/, lv_packingnoteid, lv_sizeid, pack_import.lvnsystemuserid
               /*systemuser_id*/, null /*location*/, sysdate /*timestamp*/,
               y.remarkforpackinginstructions, y.tobedeliveredamount, y.customcode,
               y.customdescription, 0 /*replacementqty*/, 0 /*autoreplacementqty*/, 0
               /*updaterentqty*/, null /*adjustmentreason_id*/, 1 /*origin*/, y.putuptype,
               lv_freeofchargereasoncodeid, y.nochargefirstissue, 0 /*nochargeactiveseason*/, 0
               /*auxiliarystatus*/, y.deliveredcogqty, 0 /*amount*/, null /*taxgroupcode*/, 0
               /*bundleqty*/, y.nochargefirstissuecog, 0 /*scannedbundles*/, 0 /*pricecog*/, null
               /*mountingorderline_id*/, null /*invoiceheader_id*/, 0 /*nodeliveryamount*/, 0
               /*nochargeprevrejected*/, 0 /*nochargeprevshortage*/, 0 /*deliveredamountnopickup*/,
               sysdate /*creationtimestamp*/, pack_import.lvnsystemuserid /*creationsystemuser_id*/,
               0 /*stockcountqty*/, 0 /*normstocklevel*/, 0 /*prevdeliveredqty*/, 0
               /*prevstandardqty*/, 0 /*internalcalcpricelog*/, 0 /*internalcalcpricecog*/, 'N'
               /*fixedinternalcalcprice*/, 0 /*deliveredexclexcessqty*/, 0 /*heavysoilqty*/, 0
               /*replacementlossqty*/, 0 /*qtysold*/, 0 /*receivedqty*/, 0 /*assembledquantity*/)
            returning packingnoteline_id into lv_packingnotelineid;
            lv_count_pnl := lv_count_pnl + 1;
            for yc in (select pnlc.*
                       from   i_packingnotelinecontent pnlc
                       where  pnlc.notenumber = x.notenumber
                       and    pnlc.productcode = y.productcode
                       and    pnlc.sizecode = y.sizecode
                       and    pnlc.finishingmethod = y.finishingmethod) loop
              begin
                --get product
                gv_message := 'content productcode ' || yc.contentproductcode;
                select p.product_id
                into   lv_cont_productid
                from   product p
                where  p.code = yc.contentproductcode;
                --get size
                gv_message := 'content size ' || yc.contentsizecode;
                select s.sizedefinition_id
                into   lv_cont_sizeid
                from   sizedefinition s
                where  s.code = yc.contentsizecode;
                --get finishingmethod
                gv_message := 'content finishingmethod ' || yc.contentfinishingmethod;
                select f.finishingmethod_id
                into   lv_cont_finishingmethodid
                from   finishingmethod f
                where  f.code = yc.contentfinishingmethod;
                --insert into packingnoteline
                gv_message := 'insert into packingnoteline';
                insert into packingnotelinecontent
                  (packingnoteline_id, product_id, sizedefinition_id, finishingmethod_id, quantity,
                   systemuser_id, timestamp, auxiliarystatus, scannedqty)
                values
                  (lv_packingnotelineid, lv_cont_productid, lv_cont_sizeid,
                   lv_cont_finishingmethodid, yc.quantity, pack_import.lvnsystemuserid, sysdate, 0
                   /*auxiliarystatus*/, null /*scannedqty*/);
                lv_count_pnlc := lv_count_pnlc + 1;
              end;
            end loop;
          end;
        end loop; --y
        commit;
      exception
        when no_data_found then
          begin
            rollback;
            pack_import.write_log('No data found ' || gv_message || ' for packing note ' ||
                                  x.notenumber || ' customer ' || to_char(x.customernumber), 3);
          end;
        when others then
          begin
            rollback;
            pack_import.write_log('import_packingnote: Fail to import ' || gv_message ||
                                  ' packing note ' || x.notenumber || ' customer ' ||
                                  to_char(x.customernumber) || ' ' || substr(sqlerrm, 1, 512), 3);
          end;
      end;
    end loop;
    commit;
    if lv_count_pn > 0 then
        pack_import.write_log('pack_import_packingnote imported ' || lv_count_pn ||
                            ' packingnotes, ' || lv_count_pnc || ' packingnotecontainers, ' ||
                            lv_count_pnl || ' packingnotelines, ' || lv_count_pnlc ||
                            ' packingnotelinecontent lines,' ||lv_count_clpn || ' cleanroombatchpackingnote lines ');
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 3);
      end;
  end import_packingnote;
  procedure import_packingnotecontainer is
  begin
  insert into packingnotecontainer
    (packingnotecontainer_id,
     packingnote_id,
     sequencenumber,
     containertype_id,
     container_id,
     weighingcategory_id,
     tareweight,
     grossweight,
     soilportion,
     weightdecimals,
     weighingsequencenr,
     weighingtimestamp,
     systemuser_id,
     timestamp,
     amount,
     price,
     taxgroupcode,
     invoiceheader_id,
     specialquantity,
     speciallength,
     specialwidth,
     weightoverrride_id,
     internalcalcprice,
     fixedinternalcalcprice,
     baglabelidcode,
     deliveryscantimestamp)
    select seq_packingnotecontainer.nextval,
           pn.packingnote_id,
           pc.sequencenumber,
           c.containertype_id,
           c.container_id,
           wc.weighingcategory_id,
           pc.tareweight,
           pc.grossweight,
           0 /*soilportion*/,
           pc.weightdecimals,
           null /*weighingsequencenr*/,
           pc.weighingtimestamp /*weighingtimestamp*/,
           1 /*systemuser_id*/,
           sysdate,
           0 /*amount*/,
           0 /*price*/,
           null /*taxgroupcode*/,
           i.invoiceheader_id,
           pc.specialquantity,
           pc.speciallength,
           pc.specialwidth,
           null
           /*weightoverrride_id*/,
           0
           /*internalcalcprice*/,
           'N' /*fixedinternalcalcprice*/,
           null /*baglabelidcode*/,
           null
    /*deliveryscantimestamp*/
      from i_packingnotecontainer pc
      join packingnote pn
        on pc.notenumber = pn.notenumber
      left join container c
        on c.primaryid = pc.containerprimaryid_id
      left join invoiceheader i
        on i.invoicenumber = pc.invoicenumber
      left join weighingcategory wc
        on wc.code = pc.weighingcategorycode
     where not exists (select 1
              from packingnotecontainer pac
             where pac.packingnote_id = pn.packingnote_id);
  exception
    when others then
      begin
        rollback;
        pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 3);
      end;
  end import_packingnotecontainer;
end pack_import_packingnote;
/
create or replace package pack_import_plcustomer is
  -- Author  : TATIANA
  -- Created : 6/6/2002 5:00:42 PM
  -- Version : 1.0
  -- Changes :TNE order 500468
  --           14-Dec-2018 ABS-73322 Extend Conversion with MBYO options ABS-76341
  --           10-Jan-2018 ABS-76181 extend PLPC conversion with season fields
  --           23-May-2019 ABS-83932 Add Default Supplier on PLPC to the Conversion
  --           01-Aug-2019 ABS-87460 conversion issue auto soil
  --           29-Jul-2020 ABS-99217 First Aid Kit (Cabinet Service)
  --           28-Jul-2021 ABS-122625 also add plpc extra info
  procedure cfbaddcustomeractivities;
  procedure cfbaddproductgrouppercustomer;
  procedure imp_plpcbudgetprotection;
  procedure import_plpctemprentstop;
  procedure cfbimportplcust;
  procedure cfbimportinventoryadjustment;
  procedure cfbimportturnoverplpc;
end pack_import_plcustomer;
/
create or replace package body pack_import_plcustomer is
  errormsg                     varchar2(512);
  countrows                    integer;
  distributionpointid          distributionpoint.distributionpoint_id%type;
  standarddeliveryid           standarddelivery.standarddelivery_id%type;
  plpdpsequence                productlistperdistribpoint.countsequence%type;
  reasoncodeid                 reasoncode.reasoncode_id%type;
  renttype                     customerrentprice.typeofrent%type;
  nchangesperweek              customerrentprice.changesperweek%type;
  productlistperdistribpointid productlistperdistribpoint.productlistperdistribpoint_id%type;
  standarddeliverylineid       standarddeliveryline.standarddeliveryline_id%type;
  billmethod                   productlistpercustomer.billingmethod%type;
  procedure cfbaddcustomeractivities is
    lvncounter number := 0;
  begin
    insert into businessunitactivities
      (businessunit_id, activity_id, systemuser_id, timestamp, invoicedbybusinessunit_id)
      select c.defaultbusinessunit_id, g.activity_id, pack_import.lvnsystemuserid, sysdate,
             max(c.defaultinvoicebusinessunit_id)
      from   customer c, productgroup g, productgrouppercustomer y
      where  g.productgroup_id = y.productgroup_id
      and    y.customer_id = c.customer_id
      and    not exists (select 1
              from   businessunitactivities x
              where  x.businessunit_id = c.defaultbusinessunit_id
              and    x.activity_id = g.activity_id)
      group  by c.defaultbusinessunit_id, g.activity_id;
    lvncounter := sql%rowcount;
    if lvncounter > 0 then
      begin
        commit;
        pack_import.write_log(to_char(lvncounter) ||
                              ' missing businessunitactivities added (based on productgrouppercustomer)');
      end;
    end if;
    insert into customeractivities
      (customer_id, processbusinessunit_id, activity_id, invoicebusinessunit_id, systemuser_id,
       timestamp, cutoffdate, finalinvoicecreated, invoicefrequency_id)
      select c.customer_id, max(c.defaultbusinessunit_id), g.activity_id,
             max(c.defaultinvoicebusinessunit_id), pack_import.lvnsystemuserid, sysdate,
             max(i.cutoffdate), 'N', max(c.invoicefrequency_id)
      from   customer c, productgroup g, productgrouppercustomer y, i_customer i
      where  g.productgroup_id = y.productgroup_id
      and    y.customer_id = c.customer_id
      and    i.customernumber = c.customernumber
      and    not exists (select x.customer_id, x.activity_id
              from   customeractivities x
              where  x.customer_id = c.customer_id
              and    x.activity_id = g.activity_id)
      group  by c.customer_id, g.activity_id;
    lvncounter := sql%rowcount;
    if lvncounter > 0 then
      begin
        commit;
        pack_import.write_log(to_char(lvncounter) ||
                              ' missing customeractivities added (based on productgrouppercustomer)');
      end;
    end if;
  exception
    when others then
      pack_import.write_log('cfbaddcustomeractivities (plcustomer) error: ' ||
                            substr(sqlerrm, 1, 512), 3);
  end cfbaddcustomeractivities;
  procedure cfbaddproductgrouppercustomer is
    lvncounter number := 0;
  begin
    insert into productgrouppercustomer
      (productgroup_id, customer_id, invoicegroupingcode, customcode, customdescritpion,
       systemuser_id, timestamp, active)
      select p.productgroup_id, l.customer_id, null, null, null, 1, sysdate, 'Y'
      from   productlistpercustomer l
      join   product p
      on     p.product_id = l.product_id
      where  not exists (select x.productgroup_id, x.customer_id
              from   productgrouppercustomer x
              where  x.productgroup_id = p.productgroup_id
              and    x.customer_id = l.customer_id)
      and    exists (select i.customernumber
              from   i_customer i, customer c
              where  i.customernumber = c.customernumber
              and    c.customer_id = l.customer_id)
      group  by p.productgroup_id, l.customer_id;
    lvncounter := sql%rowcount;
    commit;
    if lvncounter > 0 then
      pack_import.write_log(to_char(lvncounter) || ' productgroups for cust.added ');
    end if;
  exception
    when others then
      pack_import.write_log('cfbaddproductgrouppercustomer error: ' || substr(sqlerrm, 1, 512), 3);
  end cfbaddproductgrouppercustomer;
  procedure cfbimportplcust_relatedinfo is
    fpndeliveryscheme_id deliveryscheme.deliveryscheme_id%type;
    fpnemployee_id       employee.employee_id%type;
    fpnsizeid            sizedefinition.sizedefinition_id%type;
    lv_seasontypeid      seasontype.seasontype_id%type;
  begin
    pack_import.write_log('Start import productlistpercustomer: ' ||
                          to_char(sysdate, 'dd-mm-yyyy hh24:mi:ss'));
    pack_import_emblem.cfbimport_emblemtemplate;
    -- update to prevent errors.
    update i_productlistpercustomer l
    set    l.residualvalueschemecode = '-'
    where  l.residualvalueschemecode is null;
    --season type
    countrows := 0;
    begin
      for x in (select upper(trim(ip.seasontypecode)) seasontypecode
                from   i_productlistpercustomer ip
                where  ip.seasontypecode is not null
                and    not exists
                 (select 1 from seasontype st where st.code = upper(trim(ip.seasontypecode)))
                group  by upper(trim(ip.seasontypecode))) loop
        begin
          errormsg := 'seasontypecode ' || x.seasontypecode;
          pack_import.cfbcreate_seasontype(lv_seasontypeid, x.seasontypecode);
          countrows := countrows + 1;
        exception
          when dup_val_on_index then
            null;
        end;
      end loop; --x season type
    exception
      when others then
        begin
          errormsg := 'CFbImportPLCust: During adding of season types';
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
        end;
    end;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' seasontypes imported.');
      end;
    end if;
    --delivery label layout
    countrows := 0;
    begin
      for x in (select ip.deliverylabellayout, 0 sterile
                from   i_productlistpercustomer ip
                where  ip.deliverylabellayout is not null
                and    not exists (select 1
                        from   labellayout ll
                        where  ll.code = ip.deliverylabellayout
                        and    ll.labeltype = 4)
                group  by ip.deliverylabellayout) loop
        begin
          insert into labellayout
            (labellayout_id, code, description, labeltype, defaultlayout, systemuser_id, timestamp,
             layoutreceiveonstock, sterile)
          values
            (seq_labellayout.nextval, x.deliverylabellayout, x.deliverylabellayout, 5, 'N',
             pack_import.lvnsystemuserid, sysdate, 'N', x.sterile);
          countrows := countrows + 1;
        exception
          when dup_val_on_index then
            null;
        end;
      end loop;
    exception
      when others then
        begin
          errormsg := 'CFbImportPLCust: During adding of all delivery label layout';
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
        end;
    end;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' labellayouts imported.');
      end;
    end if;
    --sizedefinition
    countrows := 0;
    for x in (select sizecode, max(sizedescription) sizedescription
              from   i_productlistpercustomer
              where  sizecode is not null
              and    not exists (select code from sizedefinition where code = sizecode)
              group  by sizecode) loop
      begin
        pack_import.cfbcreate_sizedefinition(fpnsizeid, x.sizecode, 'N', null, null, null, 'N');
        pack_import.cfbcreate_sizedefinition_desc(fpnsizeid, nvl(x.sizedescription, x.sizecode));
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportPLCust: Fail to import sizecode/sizedescription ' || x.sizecode || '/' ||
                      x.sizedescription;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' sizes imported.');
      end;
    end if;
    -- sizes per size type, product size
    for vcursor in (select b.product_id, max(b.sizetype_id) sizetype_id,
                           max(b.packingamount) packingamount,
                           max(b.theoreticalweight) theoreticalweight, c.sizedefinition_id
                    from   i_productlistpercustomer a, product b, sizedefinition c
                    where  a.productcode = b.code
                    and    a.sizecode = c.code
                    and    not exists
                     (select t.code from databasesettings t where t.code = 'SMG')
                    and    not exists
                     (select ps.product_id, ps.sizedefinition_id
                            from   productsize ps
                            where  ps.product_id = b.product_id
                            and    ps.sizedefinition_id = c.sizedefinition_id)
                    group  by b.product_id, c.sizedefinition_id) loop
      begin
        -- sizespersizetype
        pack_import.cfbcreate_sizespersizetype(vcursor.sizedefinition_id, vcursor.sizetype_id);
        -- product size
        pack_import.cfbcreate_productsize(vcursor.product_id, vcursor.sizedefinition_id, 'N',
                                          vcursor.packingamount, vcursor.theoreticalweight, null);
      end;
    end loop;
    -- finishing method
    countrows := 0;
    for vcursor in (select distinct finishingmethodcode, finishingmethoddescription
                    from   i_productlistpercustomer
                    where  not exists
                     (select code from finishingmethod where code = finishingmethodcode)) loop
      begin
        insert into finishingmethod
          (finishingmethod_id, code, active, systemuser_id, timestamp)
        values
          (seq_finishingmethod.nextval, vcursor.finishingmethodcode, 'Y',
           pack_import.lvnsystemuserid, sysdate);
        insert into finishingmethod_desc
          (finishingmethod_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_finishingmethod.currval, pack_import.lvnlanguageid,
           vcursor.finishingmethoddescription, pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportPLCust: Fail to import finishing method code/description ' ||
                      vcursor.finishingmethodcode || '/' || vcursor.finishingmethoddescription;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' finishing methods imported.');
      end;
    end if;
    -- insert product finishing method
    countrows := 0;
    for x in (select p.product_id, f.finishingmethod_id
              from   i_productlistpercustomer l, product p, finishingmethod f
              where  p.code = l.productcode
              and    f.code = l.finishingmethodcode
              and    not exists (select pf.product_id, pf.finishingmethod_id
                      from   productfinishingmethod pf
                      where  pf.product_id = p.product_id
                      and    pf.finishingmethod_id = f.finishingmethod_id)
              group  by p.product_id, f.finishingmethod_id) loop
      begin
        pack_import.cfbcreate_prodfinishingmethod(x.product_id, x.finishingmethod_id);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportPLCust: Fail to import product-finishing method ';
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' product-finishingmethods imported.');
      end;
    end if;
    -- gainreason
    countrows := 0;
    for vcursor in (select distinct gainreasoncode, gainreasondescription
                    from   i_productlistpercustomer
                    where  gainreasoncode is not null
                    and    not exists
                     (select code from gainlostreason where code = gainreasoncode)) loop
      begin
        insert into gainlostreason
          (gainlostreason_id, code, systemuser_id, gainreason, timestamp, lostreason)
        values
          (seq_gainlostreason.nextval, vcursor.gainreasoncode, pack_import.lvnsystemuserid, 'Y',
           sysdate, 'N');
        insert into gainlostreason_desc
          (gainlostreason_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_gainlostreason.currval, pack_import.lvnlanguageid, vcursor.gainreasondescription,
           pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportPLCust: Fail to import gainreasoncode/gainreasondesc ' ||
                      vcursor.gainreasoncode || '/' || vcursor.gainreasondescription;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' gainreasons imported.');
      end;
    end if;
    -- lostreason
    countrows := 0;
    for vcursor in (select distinct lostreasoncode, lostreasondescription
                    from   i_productlistpercustomer
                    where  lostreasoncode is not null
                    and    not exists
                     (select code from gainlostreason where code = lostreasoncode)) loop
      begin
        insert into gainlostreason
          (gainlostreason_id, code, systemuser_id, gainreason, timestamp, lostreason)
        values
          (seq_gainlostreason.nextval, vcursor.lostreasoncode, pack_import.lvnsystemuserid, 'N',
           sysdate, 'Y');
        insert into gainlostreason_desc
          (gainlostreason_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_gainlostreason.currval, pack_import.lvnlanguageid, vcursor.lostreasondescription,
           pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportPLCust: Fail to import lostreasoncode/lostreasondesc ' ||
                      vcursor.lostreasoncode || '/' || vcursor.lostreasondescription;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' lostreasons imported.');
      end;
    end if;
    -- gaincompetitor
    countrows := 0;
    for vcursor in (select distinct gaincompetitorcode, gaincompetitorname
                    from   i_productlistpercustomer
                    where  gaincompetitorcode is not null
                    and    not exists
                     (select code from competitor where code = gaincompetitorcode)) loop
      begin
        insert into competitor
          (competitor_id, code, name, systemuser_id, timestamp)
        values
          (seq_competitor.nextval, vcursor.gaincompetitorcode,
           nvl(vcursor.gaincompetitorname, vcursor.gaincompetitorcode), pack_import.lvnsystemuserid,
           sysdate);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportPLCust: Fail to import gaincompetitorcode/gaincompetitorname ' ||
                      vcursor.gaincompetitorcode || '/' || vcursor.gaincompetitorname;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' gaincompetitors imported.');
      end;
    end if;
    -- lostcompetitor
    countrows := 0;
    for vcursor in (select distinct lostcompetitorcode, lostcompetitorname
                    from   i_productlistpercustomer
                    where  lostcompetitorcode is not null
                    and    not exists
                     (select code from competitor where code = lostcompetitorcode)) loop
      begin
        insert into competitor
          (competitor_id, code, name, systemuser_id, timestamp)
        values
          (seq_competitor.nextval, vcursor.lostcompetitorcode, vcursor.lostcompetitorname,
           pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportPLCust: Fail to import lostcompetitorcode/lostcompetitorname ' ||
                      vcursor.lostcompetitorcode || '/' || vcursor.lostcompetitorname;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' lostcompetitors imported.');
      end;
    end if;
    --residualvalue
    countrows := 0;
    for vcursor in (select distinct residualvalueschemecode
                    from   i_productlistpercustomer
                    where  not exists
                     (select code from residualvaluescheme where code = residualvalueschemecode)) loop
      begin
        insert into residualvaluescheme
          (residualvaluescheme_id, code, calculationweeks, systemuser_id, timestamp,
           calculationbasis)
        values
          (seq_residualvaluescheme.nextval, vcursor.residualvalueschemecode, 0,
           pack_import.lvnsystemuserid, sysdate, 1);
        insert into residualvaluescheme_desc
          (residualvaluescheme_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_residualvaluescheme.currval, pack_import.lvnlanguageid, '-',
           pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportPLCust: Fail to import residualvaluescheme ' ||
                      vcursor.residualvalueschemecode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' residualvalueschemecodes imported.');
      end;
    end if;
    --deliveryscheme
    countrows := 0;
    for x in (select upper(trim(a.deliveryschedulecode)) deliveryschemecode
              from   i_productlistpercustomer a
              where  upper(trim(a.deliveryschedulecode)) is not null
              and    not exists (select code
                      from   deliveryscheme b
                      where  b.code = upper(trim(a.deliveryschedulecode)))
              group  by upper(trim(a.deliveryschedulecode))) loop
      begin
        pack_import.cfbcreate_deliveryscheme(fpndeliveryscheme_id, x.deliveryschemecode, 'N', null,
                                             null);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportPLCust_relatedinfo: Fail to insert deliveryschemecode ' ||
                      x.deliveryschemecode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    --DEE deliveryscheme
    for x in (select distinct a.ddedeliveryschemecode deliveryschemecode
              from   i_productlistpercustomer a
              where  ddedeliveryschemecode is not null
              and    not exists
               (select code from deliveryscheme b where b.code = a.ddedeliveryschemecode)) loop
      begin
        pack_import.cfbcreate_deliveryscheme(fpndeliveryscheme_id, x.deliveryschemecode, 'N', null,
                                             null);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportPLCust_relatedinfo: Fail to insert DDE deliveryschemecode ' ||
                      x.deliveryschemecode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' deliveryschemes imported.');
      end;
    end if;
    --customerdeliveryscheme
    countrows := 0;
    for vcursor in (select a.deliverydaymo, a.deliverydaytu, a.deliverydaywe, a.deliverydayth,
                           a.deliverydayfr, a.deliverydaysa, a.deliverydaysu, b.deliveryscheme_id,
                           a.customernumber, c.customer_id, b.code
                    from   i_productlistpercustomer a, deliveryscheme b, customer c
                    where  a.customernumber = c.customernumber
                    and    a.deliveryschedulecode = b.code) loop
      begin
        if vcursor.deliverydaymo is not null then
          begin
            pack_import.cfbcreate_customerdelscheme(vcursor.customer_id, vcursor.deliveryscheme_id,
                                                    1);
            countrows := countrows + 1;
          exception
            when dup_val_on_index then
              null;
            when others then
              errormsg := 'CFbImportPLCust_relatedinfo: Fail to import customer delivery scheme for customernumber/deliveryschemecode/day ' ||
                          vcursor.customernumber || '/' || vcursor.code || '/1';
              pack_import.write_log(errormsg, -3);
          end;
        end if;
        if vcursor.deliverydaytu is not null then
          begin
            pack_import.cfbcreate_customerdelscheme(vcursor.customer_id, vcursor.deliveryscheme_id,
                                                    2);
            countrows := countrows + 1;
          exception
            when dup_val_on_index then
              null;
            when others then
              errormsg := 'CFbImportPLCust_relatedinfo: Fail to import customer delivery scheme for customernumber/deliveryschemecode/day ' ||
                          vcursor.customernumber || '/' || vcursor.code || '/2';
              pack_import.write_log(errormsg, -3);
          end;
        end if;
        if vcursor.deliverydaywe is not null then
          begin
            pack_import.cfbcreate_customerdelscheme(vcursor.customer_id, vcursor.deliveryscheme_id,
                                                    3);
            countrows := countrows + 1;
          exception
            when dup_val_on_index then
              null;
            when others then
              errormsg := 'CFbImportPLCust_relatedinfo: Fail to import customer delivery scheme for customernumber/deliveryschemecode/day ' ||
                          vcursor.customernumber || '/' || vcursor.code || '/3';
              pack_import.write_log(errormsg, -3);
          end;
        end if;
        if vcursor.deliverydayth is not null then
          begin
            pack_import.cfbcreate_customerdelscheme(vcursor.customer_id, vcursor.deliveryscheme_id,
                                                    4);
            countrows := countrows + 1;
          exception
            when dup_val_on_index then
              null;
            when others then
              errormsg := 'CFbImportPLCust_relatedinfo: Fail to import customer delivery scheme for customernumber/deliveryschemecode/day ' ||
                          vcursor.customernumber || '/' || vcursor.code || '/4';
              pack_import.write_log(errormsg, -3);
          end;
        end if;
        if vcursor.deliverydayfr is not null then
          begin
            pack_import.cfbcreate_customerdelscheme(vcursor.customer_id, vcursor.deliveryscheme_id,
                                                    5);
            countrows := countrows + 1;
          exception
            when dup_val_on_index then
              null;
            when others then
              errormsg := 'CFbImportPLCust_relatedinfo: Fail to import customer delivery scheme for customernumber/deliveryschemecode/day ' ||
                          vcursor.customernumber || '/' || vcursor.code || '/5';
              pack_import.write_log(errormsg, -3);
          end;
        end if;
        if vcursor.deliverydaysa is not null then
          begin
            pack_import.cfbcreate_customerdelscheme(vcursor.customer_id, vcursor.deliveryscheme_id,
                                                    6);
            countrows := countrows + 1;
          exception
            when dup_val_on_index then
              null;
            when others then
              errormsg := 'CFbImportPLCust_relatedinfo: Fail to import customer delivery scheme for customernumber/deliveryschemecode/day ' ||
                          vcursor.customernumber || '/' || vcursor.code || '/6';
              pack_import.write_log(errormsg, -3);
          end;
        end if;
        if vcursor.deliverydaysu is not null then
          begin
            pack_import.cfbcreate_customerdelscheme(vcursor.customer_id, vcursor.deliveryscheme_id,
                                                    7);
            countrows := countrows + 1;
          exception
            when dup_val_on_index then
              null;
            when others then
              errormsg := 'CFbImportPLCust_relatedinfo: Fail to import customer delivery scheme for customernumber/deliveryschemecode/day ' ||
                          vcursor.customernumber || '/' || vcursor.code || '/7';
              pack_import.write_log(errormsg, -3);
          end;
        end if;
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' customerdeliveryschemes imported.');
      end;
    end if;
    -- adding salesemployee,1,2
    for x in (select c.salesemployeenumber, max(c.salesemployeename) salesemployeename,
                     max(b.plant_id) plant_id
              from   i_productlistpercustomer c, businessunit b, customer z
              where  b.businessunit_id = z.defaultbusinessunit_id
              and    c.customernumber = z.customernumber
              and    c.salesemployeenumber is not null
              and    not exists (select e.employee_id
                      from   employee e
                      where  e.employeenumber = c.salesemployeenumber)
              group  by c.salesemployeenumber
              union
              select c.salesemployeenumber2, max(c.salesemployeename2) salesemployeename,
                     max(b.plant_id) plant_id
              from   i_productlistpercustomer c, businessunit b, customer z
              where  b.businessunit_id = z.defaultbusinessunit_id
              and    c.customernumber = z.customernumber
              and    c.salesemployeenumber2 is not null
              and    not exists (select e.employee_id
                      from   employee e
                      where  e.employeenumber = c.salesemployeenumber2)
              group  by c.salesemployeenumber2) loop
      begin
        pack_import.cfbgetcreate_employee(x.plant_id, fpnemployee_id, x.salesemployeenumber,
                                          x.salesemployeename, null, null, null, null, null, null,
                                          null);
      exception
        when dup_val_on_index then
          null;
      end;
    end loop;
    begin
      --add discountlistpercustomer WASH list if needed
      insert into discountlistpercustomer
        (discountlistpercustomer_id, customer_id, pricetype, generaldiscountlist_id, timestamp,
         systemuser_id, dateinactive, dateactive, priority)
        select seq_discountlistpercustomer.nextval, c.customer_id, 1, null, sysdate,
               pack_import.lvnsystemuserid, to_date('31-12-2099', 'DD-MM-YYYY'), trunc(sysdate) - 1,
               1
        from   customer c
        where  exists (select i.customernumber
                from   i_productlistpercustomer i
                where  i.discountpercentagewash <> 0
                and    i.customernumber = c.customernumber)
        and    not exists (select x.discountlistpercustomer_id
                from   discountlistpercustomer x
                where  x.customer_id = c.customer_id
                and    x.pricetype = 1
                and    x.priority = 1);
    exception
      when others then
        null;
    end;
    begin
      --add discountlistpercustomer RENT list if needed
      insert into discountlistpercustomer
        (discountlistpercustomer_id, customer_id, pricetype, generaldiscountlist_id, timestamp,
         systemuser_id, dateinactive, dateactive, priority)
        select seq_discountlistpercustomer.nextval, c.customer_id, 2, null, sysdate,
               pack_import.lvnsystemuserid, to_date('31-12-2099', 'DD-MM-YYYY'), trunc(sysdate) - 1,
               1
        from   customer c
        where  exists (select i.customernumber
                from   i_productlistpercustomer i
                where  i.discountpercentagerent <> 0
                and    i.customernumber = c.customernumber)
        and    not exists (select x.discountlistpercustomer_id
                from   discountlistpercustomer x
                where  x.customer_id = c.customer_id
                and    x.pricetype = 2
                and    x.priority = 1);
    exception
      when others then
        null;
    end;
  end cfbimportplcust_relatedinfo;
  procedure cfbimportmatorderinginfo is
    -- pvd added 26-july-2005
    counter           number := 0;
    customerid        customer.customer_id%type;
    productid         product.product_id%type;
    sizedefinitionid  sizedefinition.sizedefinition_id%type;
    finishingmethodid finishingmethod.finishingmethod_id%type;
    plpcid            productlistpercustomer.productlistpercustomer_id%type;
    supplierid        supplier.supplier_id%type;
    qualitygradeid    qualitygrade.qualitygrade_id%type;
  begin
    for x in (select i.* from i_matorderinginfo i) loop
      begin
        errormsg := 'customer ' || x.customernumber;
        select c.customer_id
        into   customerid
        from   customer c
        where  c.customernumber = x.customernumber;
        errormsg := 'product ' || x.productcode;
        select p.product_id into productid from product p where p.code = x.productcode;
        errormsg := 'size ' || x.sizecode;
        select s.sizedefinition_id
        into   sizedefinitionid
        from   sizedefinition s
        where  s.code = x.sizecode;
        errormsg := 'finishingmethodcode ' || x.finishingmethodcode;
        select f.finishingmethod_id
        into   finishingmethodid
        from   finishingmethod f
        where  f.code = x.finishingmethodcode;
        errormsg := 'productlistpercustomer customer/product/size/finishingmethod' ||
                    x.customernumber || '/' || x.productcode || '/' || x.sizecode || '/' ||
                    x.finishingmethodcode || ' active from ' || to_char(sysdate, 'dd-mon-yyyy');
        select l.productlistpercustomer_id
        into   plpcid
        from   productlistpercustomer l
        where  l.customer_id = customerid
        and    l.product_id = productid
        and    l.sizedefinition_id = sizedefinitionid
        and    l.finishingmethod_id = finishingmethodid
        and    sysdate between l.dateactive and l.dateinactive;
        errormsg       := 'qualitygrade ' || x.qualitygradecode;
        qualitygradeid := pack_import.getqualitygradeid(x.qualitygradecode);
        errormsg       := 'supplier ' || x.suppliernumber;
        select s.supplier_id
        into   supplierid
        from   supplier s
        where  s.suppliernumber = x.suppliernumber;
        errormsg := 'cfbimportmatorderinginfo: fail to insert into matorderinginfo for customer/product/size ' ||
                    x.customernumber || '/' || x.productcode || '/' || x.sizecode;
        insert into matorderinginfo
          (productlistpercustomer_id, matorderinginfotype, customizationreason, qualitygrade_id,
           supplier_id, backing, borderwidth, bordermaterial, thickness, actualwidth, actuallength,
           shape, customcut, logofilepathoriginal, logofilepathproduction, direction,
           colorpalettelogo, colorpalettebackground, systemuser_id, timestamp)
        values
          (plpcid, x.matorderinginfotype, x.customizationreason, qualitygradeid, supplierid,
           x.backing, x.borderwidth, x.bordermaterial, x.thickness, x.actualwidth, x.actuallength,
           x.shape, x.customcut, x.logofilepathoriginal, x.logofilepathproduction, x.direction,
           x.colorpalettelogo, x.colorpalettebackground, pack_import.lvnsystemuserid, sysdate);
        counter := counter + 1;
      exception
        when dup_val_on_index then
          null; --no problem when it already exists!
        when no_data_found then
          pack_import.write_log('error ' || errormsg || ' not found.', -3);
        when others then
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    commit;
    if counter > 0 then
      pack_import.write_log(counter || ' matorderinginfo rows imported.');
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('cfbimportinventoryadjustment error: ' || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimportmatorderinginfo;
  procedure cfbfixedwearers is
    lv_counter           number := 0;
    lv_customerid        customer.customer_id%type;
    lv_productid         product.product_id%type;
    lv_sizeid            sizedefinition.sizedefinition_id%type;
    lv_finishingmethodid finishingmethod.finishingmethod_id%type;
    lv_costcenterid      costcenter.costcenter_id%type;
    lv_plpcid            productlistpercustomer.productlistpercustomer_id%type;
  begin
    --cfbfixedwearers
    for wx in (select * from i_fixedwearers) loop
      begin
        --customer
        errormsg := 'Customer ' || wx.customernumber;
        select c.customer_id
        into   lv_customerid
        from   customer c
        where  c.customernumber = wx.customernumber;
        --product
        errormsg := 'Product ' || wx.productcode;
        select p.product_id into lv_productid from product p where p.code = wx.productcode;
        --size
        errormsg := 'Size ' || wx.sizecode;
        select s.sizedefinition_id into lv_sizeid from sizedefinition s where s.code = wx.sizecode;
        --finishingmethod
        errormsg := 'Finishingmethod ' || wx.finishingmethodcode;
        select f.finishingmethod_id
        into   lv_finishingmethodid
        from   finishingmethod f
        where  f.code = wx.finishingmethodcode;
        --costcenter
        errormsg := 'Costcenter ' || wx.costcentercode || ' for customer ' || wx.customernumber;
        select cc.costcenter_id
        into   lv_costcenterid
        from   costcenter cc
        where  cc.customer_id = lv_customerid
        and    cc.code = wx.costcentercode;
        --PLPC
        errormsg := 'Customer ' || wx.customernumber || ' Product ' || wx.productcode || ' Size ' ||
                    wx.sizecode || ' Finishingmethod ' || wx.finishingmethodcode;
        select l.productlistpercustomer_id
        into   lv_plpcid
        from   productlistpercustomer l
        where  l.customer_id = lv_customerid
        and    l.product_id = lv_productid
        and    l.sizedefinition_id = lv_sizeid
        and    l.finishingmethod_id = lv_finishingmethodid
        and    wx.startdate between l.dateactive and l.dateinactive;
        --insert into plpcfixedwearer
        errormsg := 'Insert PLPCFixedwearers for ' || errormsg;
        insert into plpcfixedwearers
          (plpcfixedwearers_id, productlistpercustomer_id, costcenter_id, nrofwearers, nrofchanges,
           systemuser_id, timestamp, startdate, enddate)
        values
          (seq_plpcfixedwearers.nextval, lv_plpcid, lv_costcenterid, wx.nrofwearers, wx.nrofchanges,
           pack_import.lvnsystemuserid, sysdate, wx.startdate, wx.enddate);
        --update plpc set fixed wearers
        update productlistpercustomer l
        set    l.bm1fixedwearers = 'Y'
        where  l.productlistpercustomer_id = lv_plpcid;
        --count records imported
        lv_counter := lv_counter + 1;
      exception
        when no_data_found then
          begin
            pack_import.write_log('Fixedwearers Import; No data found ' || errormsg, 3);
          end;
        when dup_val_on_index then
          null; --no problem when it already exists!
      end;
    end loop; --wx fixedwearers
    commit;
    if lv_counter > 0 then
      pack_import.write_log(lv_counter || ' fixedwearers rows imported.');
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('cfbfixedwearers error: ' || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbfixedwearers;
  procedure imp_plpcbudgetprotection is
    lvcounter number := 0;
  begin
    --imp_plpcbudgetprotection
    errormsg := 'imp_plpcbudgetprotection';
    for pp in (select l.productlistpercustomer_id, l.customer_id,
                      case
                        when p.typeofmerchandise = 1 and p.materialmaintenanceprotection = 1 then
                         nvl(lp.mmpspecificpercentage,
                             (select cbp.materialmaintenancepercentage
                               from   customerbudgetprotection cbp
                               where  cbp.customer_id = c.customer_id))
                        else
                         0
                      end mmpspecificpercentage, lp.garmentsetup, lp.garmentmaintenance,
                      lp.garmentloss, lp.garmentrepair, lp.mbyoppercentage, lp.garmentlosspercentage,
                      lp.garmentemblem
               from   i_productlistpercustomer lp
               join   customer c
               on     c.customernumber = lp.customernumber
               join   product p
               on     p.code = lp.productcode
               join   sizedefinition s
               on     s.code = lp.sizecode
               join   finishingmethod f
               on     f.code = lp.finishingmethodcode
               join   productlistpercustomer l
               on     (l.customer_id = c.customer_id and l.product_id = p.product_id and
                      l.sizedefinition_id = s.sizedefinition_id and
                      l.finishingmethod_id = f.finishingmethod_id)
               where  not exists
                (select 1
                       from   plpcbudgetprotection b
                       where  b.productlistpercustomer_id = l.productlistpercustomer_id)) loop
      begin
        insert into plpcbudgetprotection
          (productlistpercustomer_id, mmpspecificpercentage, garmentsetup, garmentmaintenance,
           garmentloss, garmentrepair, systemuser_id, timestamp, mbyoppercentage,
           garmentlosspercentage, garmentemblem)
        values
          (pp.productlistpercustomer_id, pp.mmpspecificpercentage, nvl(pp.garmentsetup, 'N'),
           nvl(pp.garmentmaintenance, 'N'), nvl(pp.garmentloss, 'N'), nvl(pp.garmentrepair, 'N'),
           pack_import.lvnsystemuserid, sysdate, pp.mbyoppercentage,
           nvl(pp.garmentlosspercentage, 100), nvl(pp.garmentemblem, 'N'));
        --count rows inserted
        lvcounter := lvcounter + 1;
      exception
        when dup_val_on_index then
          null; --no problem if it is already there
      end;
    end loop; --pp
    commit;
    if lvcounter > 0 then
      pack_import.write_log(lvcounter || ' PLPC Budget Protection rows imported.');
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('imp_plpcbudgetprotection: Failed to import ' ||
                              substr(sqlerrm, 1, 512), 3);
      end;
  end imp_plpcbudgetprotection;
 procedure import_plpctemprentstop is
    lv_countrows number := 0;
  begin
    --import_plpctemprentstop
    insert into plpctemprentstop
      (productlistpercustomer_id,
       temporaryrentstopstartdate,
       temporaryrentstopenddate,
       systemuser_id,
       timestamp)
      select plpc.productlistpercustomer_id,
             ipt.temporaryrentstopstartdate,
             ipt.temporaryrentstopenddate,
             pack_import.lvnsystemuserid,
             sysdate
        from i_plpctemprentstop ipt
        join customer c
          on c.customernumber = ipt.customernumber
        join product p
          on p.code = ipt.productcode
        join sizedefinition s
          on s.code = ipt.sizecode
        join finishingmethod f
          on f.code = ipt.finishingmethodcode
        join productlistpercustomer plpc
          on (plpc.customer_Id = c.customer_id and
             plpc.product_id = p.product_id and
             plpc.sizedefinition_id = s.sizedefinition_id and
             plpc.finishingmethod_id = f.finishingmethod_id)
       where not exists (select 1
                from plpctemprentstop pt
               where pt.productlistpercustomer_id =
                     plpc.productlistpercustomer_id);
    --count rows processed
    lv_countrows := sql%rowcount;
    if lv_countrows > 0 then
      begin
        commit;
        pack_import.write_log(to_char(lv_countrows) ||
                              'Plpc temp rent stop charges rows imported.');
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('Error import plpctemprentstop.' ||
                              substr(sqlerrm, 1, 512),
                              3);
      end;
  end import_plpctemprentstop;

  procedure cfbimportplcust is
    countrowsdd                   integer := 0;
    countrowsstdl                 integer := 0;
    countrowsstda                 integer := 0;
    countrowscrpn                 integer := 0;
    countrowscrpo                 integer := 0;
    countrowscwpn                 integer := 0;
    countrowscwpo                 integer := 0;
    countrowscrepn                integer := 0;
    countrowscrepo                integer := 0;
    countplpc                     integer := 0;
    lv_cnt_contract_plpc_link     number := 0;
    fpninventorybillingtype       productlistpercustomer.inventorybillingtype%type;
    countrowscspn                 integer := 0;
    countrowscspo                 integer := 0;
    countrowsplpdp                integer := 0;
    countrowsrqa                  integer := 0;
    countrowspgpc                 integer := 0;
    import                        varchar(1);
    employeeid                    employee.employee_id%type;
    salesemployee2id              employee.employee_id%type;
    plpcid                        productlistpercustomer.productlistpercustomer_id%type;
    del_scheme_id                 deliveryscheme.deliveryscheme_id%type;
    dee_del_scheme_id             deliveryscheme.deliveryscheme_id%type;
    customerrentpriceid           customerrentprice.customerrentprice_id%type;
    pricelistpercustomerid        pricelistpercustomer.pricelistpercustomer_id%type;
    lvnemblemtemplateid           emblemtemplate.emblemtemplate_id%type;
    lvntreatmentcheckscheme_id    treatmentcheckscheme.treatmentcheckscheme_id%type := null;
    lvndeliverylabellayout_id     labellayout.labellayout_id%type := null;
    lv_underuse_systemsetting     systemsetting.value%type;
    lv_autosoil_systemsetting     systemsetting.value%type;
    lv_customerbudgetdefinitionid customerbudgetdefinition.customerbudgetdefinition_id%type;
    lv_contractpurchaseorder_id   contractpurchaseorder.contractpurchaseorder_id%type;
    lv_checkextra                 number;
    lv_contractid                 contract.contract_id%type;
    lv_contractproductid          contractproduct.contractproduct_id%type;
    lv_err_plpc_bm4               number := 0;
    lsizebillinggroupid           sizebillinggroup.sizebillinggroup_id%type;
    procedure get_systemesettings(fp_plantid in plant.plant_id%type) is
    begin
      begin
        --get system setting UNDERUSEMETHOD
        select st.value
        into   lv_underuse_systemsetting
        from   systemsetting st
        where  st.name = 'UNDERUSEMETHOD'
        and    st.plant_id = fp_plantid;
      exception
        when no_data_found then
          lv_underuse_systemsetting := '0';
      end;
      begin
        --get system setting AUTOSOIL
        select st.value
        into   lv_autosoil_systemsetting
        from   systemsetting st
        where  st.name = 'AUTOSOIL'
        and    st.plant_id = fp_plantid;
      exception
        when no_data_found then
          lv_autosoil_systemsetting := '0';
      end;
    end get_systemesettings;
    procedure cfbcreate_productdeliveryday(fpnplpcid               in productdeliveryday.productlistpercustomer_id%type,
                                           fpndayid                in productdeliveryday.day_id%type,
                                           fpsdeliverytype         in productdeliveryday.deliverytype%type,
                                           fpncustomerid           in productlistpercustomer.customer_id%type,
                                           fpntypeofmerchandise    in product.typeofmerchandise%type,
                                           fp_circulatinginventory in i_productlistpercustomer.circulatinginventory%type,
                                           fp_percentage           in i_productlistpercustomer.srcpercentagesoilcount%type) is
      procedure add_autosoil is
      begin
        --add_autosoil
        if lv_autosoil_systemsetting = '1' then
          begin
            insert into autosoilquantity
              (autosoilquantity_id, productlistpercustomer_id, day_id, quantity, systemuser_id,
               timestamp)
            values
              (seq_autosoilquantity.nextval, fpnplpcid, fpndayid,
               round((fp_percentage * nvl(fp_circulatinginventory, 0) / 100)),
               pack_import.lvnsystemuserid, sysdate);
          end;
        end if;
        if lv_autosoil_systemsetting = '2' then
          begin
            insert into autosoilquantity
              (autosoilquantity_id, productlistpercustomer_id, day_id, quantity, systemuser_id,
               timestamp)
            values
              (seq_autosoilquantity.nextval, fpnplpcid, fpndayid, nvl(fp_circulatinginventory, 0),
               pack_import.lvnsystemuserid, sysdate);
          end;
        end if;
      end add_autosoil;
    begin
      --cfbcreate_productdeliveryday
      insert into productdeliveryday
        (productlistpercustomer_id, day_id, timestamp, systemuser_id, deliverytype)
      values
        (fpnplpcid, fpndayid, sysdate, pack_import.lvnsystemuserid, fpsdeliverytype);
      --add_check_customerdeliveryday
      pack_import.add_check_customerdeliveryday(fpncustomerid, fpndayid, fpsdeliverytype,
                                                fpntypeofmerchandise);
      --add_autosoil
      add_autosoil;
    end cfbcreate_productdeliveryday;
  begin
    --cfbimportplcust_relatedinfo
    cfbimportplcust_relatedinfo;
    pack_import.write_log('Imported ProductListPerCustomer related info.');
    --first import the default price list records
    pack_import_pricestructure.cfbimport_pricelist;
    pack_import_pricestructure.cfbimport_pricelistpercustomer;
    --Count already existing PLPC lines
    select count(l.productlistpercustomer_id) into countplpc from productlistpercustomer l;
    --insert productlistpercustomer -----------------------------------------------------------------------------------------------------------
    countrows := 0;
    begin
      for vcursor in (select a.*, b.customer_id, b.dateactive customerdateactive,
                             b.dateinactive customerdateinactive, c.product_id, e.sizedefinition_id,
                             f.finishingmethod_id, g.gainlostreason_id gainreason_id,
                             h.gainlostreason_id lostreason_id, i.competitor_id gaincompetitor_id,
                             j.competitor_id lostcompetitor_id, k.residualvaluescheme_id,
                             bus.plant_id, c.salesonly, c.productgroup_id,
                             (select count(1)
                               from   i_onsiteinvadjustment io
                               where  io.customernumber = a.customernumber
                               and    io.productcode = a.productcode
                               and    io.sizecode = a.sizecode
                               and    io.finishingmethodcode = a.finishingmethodcode) onsitecount,
                             (select sea.seasontype_id
                               from   seasontype sea
                               where  sea.code = upper(trim(a.seasontypecode))) seasontype_id,
                             (select s.supplier_id
                               from   supplier s
                               where  s.suppliernumber = a.default_suppliernumber) defaultsupplier_id
                      from   i_productlistpercustomer a, customer b, product c, sizedefinition e,
                             finishingmethod f, gainlostreason g, gainlostreason h, competitor i,
                             competitor j, residualvaluescheme k, businessunit bus
                      where  a.customernumber = b.customernumber(+)
                      and    a.productcode = c.code(+)
                      and    a.sizecode = e.code(+)
                      and    a.finishingmethodcode = f.code(+)
                      and    bus.businessunit_id = b.defaultbusinessunit_id
                      and    a.gainreasoncode = g.code(+)
                      and    a.lostreasoncode = h.code(+)
                      and    a.gaincompetitorcode = i.code(+)
                      and    a.lostcompetitorcode = j.code(+)
                      and    a.residualvalueschemecode = k.code
                      and    not exists
                       (select productlistpercustomer_id
                              from   productlistpercustomer
                              where  customer_id = b.customer_id
                              and    product_id = c.product_id
                              and    sizedefinition_id = e.sizedefinition_id
                              and    finishingmethod_id = f.finishingmethod_id)) loop
        begin
          -- set variables.
          fpninventorybillingtype := vcursor.inventorybillingtype;
          billmethod              := vcursor.billingmethod;
          import                  := 'Y';
          --get_systemesettings
          get_systemesettings(vcursor.plant_id);
          --get lvntreatmentcheckscheme_id
          if vcursor.treatmentcheckschemecode is not null then
            begin
              select tcs.treatmentcheckscheme_id
              into   lvntreatmentcheckscheme_id
              from   treatmentcheckscheme tcs
              where  tcs.code = vcursor.treatmentcheckschemecode;
            exception
              when others then
                begin
                  -- this code must already exist in DB will not be created during conversion!
                  import := 'N';
                  pack_import.write_log(' treatmentcheck code ' ||
                                        vcursor.treatmentcheckschemecode || ' does not exist.', 3);
                end;
            end;
          else
            lvntreatmentcheckscheme_id := null;
          end if;
          begin
            --get lv_customerbudgetdefinitionid
            if vcursor.budgetcode is null then
              lv_customerbudgetdefinitionid := null;
            else
              begin
                select cbd.customerbudgetdefinition_id
                into   lv_customerbudgetdefinitionid
                from   customerbudgetdefinition cbd
                where  cbd.customer_id = vcursor.customer_id
                and    cbd.code = vcursor.budgetcode;
              exception
                when no_data_found then
                  begin
                    lv_customerbudgetdefinitionid := null;
                    pack_import.write_log(' customerbudgetdefinition code ' || vcursor.budgetcode ||
                                          ' for customer ' || vcursor.customernumber ||
                                          ' does not exist.', 3);
                  end;
              end;
            end if; --lv_customerbudgetdefinitionid
            -- get lv_contractpurchaseorder_id
            if vcursor.contractcode is null then
              lv_contractpurchaseorder_id := null;
            else
              begin
                select cpo.contractpurchaseorder_id
                into   lv_contractpurchaseorder_id
                from   contractpurchaseorder cpo
                join   contract contr
                on     cpo.contract_id = contr.contract_id
                where  contr.code = vcursor.contractcode
                and    contr.customer_link_id = vcursor.customer_id;
              exception
                when no_data_found then
                  begin
                    lv_contractpurchaseorder_id := null;
                  end;
              end;
            end if; --lv_contractpurchaseorder_id
          end;
          --get delivery layout
          if vcursor.deliverylabellayout is not null then
            begin
              select lb.labellayout_id
              into   lvndeliverylabellayout_id
              from   labellayout lb
              where  lb.labeltype = 5
              and    lb.code = vcursor.deliverylabellayout;
            exception
              when others then
                begin
                  -- this code must already exist in DB will not be created during conversion!
                  import := 'N';
                  pack_import.write_log(' deliverylabellayout code (labeltype 5) ' ||
                                        vcursor.deliverylabellayout || ' does not exist.', 3);
                end;
            end;
          else
            lvndeliverylabellayout_id := null;
          end if;
          if vcursor.salesemployeenumber is null then
            employeeid := null;
          else
            begin
              pack_import.cfbgetcreate_employee(vcursor.plant_id, employeeid,
                                                vcursor.salesemployeenumber,
                                                vcursor.salesemployeename, null, null, null, null,
                                                null, null, null);
            end;
          end if;
          if vcursor.salesemployeenumber2 is null then
            salesemployee2id := null;
          else
            begin
              pack_import.cfbgetcreate_employee(vcursor.plant_id, salesemployee2id,
                                                vcursor.salesemployeenumber2,
                                                vcursor.salesemployeename2, null, null, null, null,
                                                null, null, null);
            end;
          end if;
          -- check if customer exists
          if vcursor.customer_id is null then
            begin
              import := 'N';
              pack_import.write_log(' Error customer ' || to_char(vcursor.customernumber) ||
                                    ' does not exist.', -3);
            end;
          end if;
          -- check if product exists
          if vcursor.product_id is null then
            begin
              import := 'N';
              pack_import.write_log(' Error product ' || vcursor.productcode || ' does not exist.',
                                    -3);
            end;
          end if;
          -- check if size exists
          if vcursor.sizedefinition_id is null then
            begin
              import := 'N';
              pack_import.write_log(' Error size ' || vcursor.sizecode || ' does not exist.', -3);
            end;
          end if;
          -- check if finishingmethod exists
          if vcursor.finishingmethod_id is null then
            begin
              import := 'N';
              pack_import.write_log(' Error finishingmethod ' || vcursor.finishingmethodcode ||
                                    ' does not exist.', -3);
            end;
          end if;
          -- check emblemtemplate code
          if vcursor.emblemtemplate is null then
            lvnemblemtemplateid := null;
          else
            begin
              select t.emblemtemplate_id
              into   lvnemblemtemplateid
              from   emblemtemplate t
              where  t.customer_id = vcursor.customer_id
              and    t.code = vcursor.emblemtemplate;
            exception
              when no_data_found then
                begin
                  pack_import.cfbcreate_emblemtemplate(lvnemblemtemplateid, vcursor.customer_id,
                                                       vcursor.emblemtemplate,
                                                       vcursor.emblemtemplate, 'Y', 'Y', 'Y');
                end;
            end;
          end if;
          -- DEE deliveryschemecode
          if vcursor.ddedeliveryschemecode is null then
            dee_del_scheme_id := null;
          else
            begin
              select d.deliveryscheme_id
              into   dee_del_scheme_id
              from   deliveryscheme d
              where  d.code = vcursor.ddedeliveryschemecode;
            exception
              when no_data_found then
                begin
                  import := 'N';
                  pack_import.write_log(' Error ddedeliveryschemecode ' ||
                                        vcursor.ddedeliveryschemecode || ' does not exist.', -3);
                end;
              when others then
                begin
                  import := 'N';
                  pack_import.write_log(' Error reading ddedeliveryschemecode ' ||
                                        vcursor.ddedeliveryschemecode || ' error: ' ||
                                        substr(sqlerrm, 1, 512), -3);
                end;
            end;
          end if;
          -----rules for combinations in plpc!-----
          -- for type of merchandise 3 insert always billigmethod 4
          if (vcursor.typeofmerchandise = 3 and billmethod <> 4) then
            begin
              billmethod      := 4;
              lv_err_plpc_bm4 := lv_err_plpc_bm4 + 1;
            end;
          end if;
          if (vcursor.salesonly = 'Y' and billmethod <> 4) then
            begin
              if nvl(pack_import.lvdbcustomercode, 'ABS') <> 'UNF' then
                begin
                  billmethod      := 4;
                  lv_err_plpc_bm4 := lv_err_plpc_bm4 + 1;
                end;
              end if;
            end;
          end if;
          if (vcursor.sizecode = '*' and vcursor.changesperweek = 'N' and vcursor.billingmethod = 1) then
            begin
              import := 'N';
              pack_import.write_log(' For customer ' || to_char(vcursor.customernumber) ||
                                    ' product ' || vcursor.productcode ||
                                    ' the combination of size * and changesperweek N is not allowed!.',
                                    3);
            end;
          end if;
          if (vcursor.sizecode = '*' and vcursor.billingmethod = 2 and
             lv_underuse_systemsetting <> '4') then
            begin
              import := 'N';
              pack_import.write_log(' For customer ' || to_char(vcursor.customernumber) ||
                                    ' product ' || vcursor.productcode ||
                                    ' the combination of size * and billingmethod 2 is not allowed!.',
                                    3);
            end;
          end if;
          if (vcursor.typeofmerchandise = 1 and vcursor.billingmethod = 1 and
             vcursor.changesperweek = 'Y') then
            begin
              import := 'N';
              pack_import.write_log(' For customer ' || to_char(vcursor.customernumber) ||
                                    ' product ' || vcursor.productcode ||
                                    ' the combination of typeofmerchandise 1 and billingmethod 1 and changesperweek  Y is not allowed!',
                                    3);
            end;
          end if;
          if (vcursor.typeofmerchandise = 1 and vcursor.billingmethod = 5 and
             vcursor.changesperweek = 'Y') then
            begin
              import := 'N';
              pack_import.write_log(' For customer ' || to_char(vcursor.customernumber) ||
                                    ' product ' || vcursor.productcode ||
                                    ' the combination of typeofmerchandise 1 and billingmethod 5 and changesperweek  Y is not allowed!',
                                    3);
            end;
          end if;
          -- only import if its allowed --
          if import = 'Y' then
            begin
              pack_import.cfbcreate_productlistpercust(plpcid,
                                                       --fpnproductlistpercustomer_id,
                                                       vcursor.product_id,
                                                       --fpnproduct_id,
                                                       vcursor.dateactive,
                                                       --fpdtdateactive,
                                                       vcursor.dateinactive,
                                                       --fpdtdateinactive,
                                                       vcursor.finishingmethod_id,
                                                       --fpnfinishingmethod_id,
                                                       vcursor.codeuniquely,
                                                       --fpscodeuniquely,
                                                       vcursor.soilweight,
                                                       --fpnsoilweight,
                                                       vcursor.customer_id,
                                                       --fpncustomer_id,
                                                       nvl(vcursor.onsiteinventorycount, 1),
                                                       --fpsonsiteinventorycount,
                                                       vcursor.sizedefinition_id,
                                                       --fpnsizedefinition_id,
                                                       vcursor.rentpriceperfrequency,
                                                       --fpnrentpricefrequency,
                                                       vcursor.changesperweek,
                                                       --fpnchangesperweek,
                                                       vcursor.percentafterdepreciation,
                                                       --fpnpercentageafterdepreciation,
                                                       billmethod,
                                                       --fpnbillingmethod,
                                                       vcursor.soilcountmethod,
                                                       --fpnsoilcountmethod,
                                                       vcursor.srcmethod,
                                                       --fpnsrcmethod,
                                                       vcursor.cleancount,
                                                       --fpscleancount,
                                                       vcursor.srcpercentagesoilcount,
                                                       --fpnsrcpercentagesoilcount,
                                                       vcursor.srcpercentageinventory,
                                                       --fpnsrcpercentageinventory,
                                                       vcursor.srcquantity,
                                                       --fpnsrcquantity,
                                                       vcursor.srcfrequency,
                                                       --fpnsrcfrequency,
                                                       nvl(vcursor.chargeoveruse, 'N'),
                                                       --fpnchargeoveruse,
                                                       vcursor.chargestockroominventory,
                                                       --fpschargestockroominventory,
                                                       vcursor.minimumturnaround,
                                                       --fpnminimumturnaround,
                                                       vcursor.minimumquantity,
                                                       --fpnminimumquantity,
                                                       vcursor.qtyfreeofcharge,
                                                       --fpnqtyfreeofcharge,
                                                       vcursor.customcode,
                                                       --fpscustomcode,
                                                       vcursor.customdescription,
                                                       --fpscustomdescription,
                                                       vcursor.custombundlesize,
                                                       --fpncustombundlesize,
                                                       vcursor.gaincompetitor_id,
                                                       --fpngaincompetitor_id,
                                                       vcursor.gainreason_id,
                                                       --fpngainreason_id,
                                                       vcursor.lostreason_id,
                                                       --fpnlostreason_id,
                                                       vcursor.lostcompetitor_id,
                                                       --fpnlostcompetitor_id,
                                                       vcursor.residualvaluescheme_id,
                                                       --fpnresidualvaluescheme_id,
                                                       vcursor.delayevenexchange,
                                                       --fpndelayedevenexchange,
                                                       nvl(fpninventorybillingtype, 1),
                                                       --fpninventorybillingtype,
                                                       vcursor.minimumfrequency,
                                                       --fpnminimumfrequency,
                                                       vcursor.deliverreplacementqty,
                                                       --fpsdeliverreplacementqty,
                                                       lvnemblemtemplateid,
                                                       --fpnemblemtemplate,
                                                       null,
                                                       --fpnwashprocess,
                                                       case when vcursor.chargewashesonlyforcog = 4 and
                                                        vcursor.billingmethod = 4 then 'Y' else 'N' end,
                                                       --fpsautomaticsales,
                                                       vcursor.customerrelated,
                                                       --fpscustomerrelated,
                                                       'N',
                                                       --fpsautoreplafterlifetime,
                                                       nvl(vcursor.chargewashinactiveseason, 'N'),
                                                       --fpnchargerentinactiveseason,
                                                       vcursor.seasontype_id,
                                                       --fpnseasontypeid,
                                                       1,
                                                       --fpnchargewashespack,
                                                       vcursor.specificputuptype,
                                                       --fpsspecificputuptype,
                                                       vcursor.quantityreturned,
                                                       --fpnquantityreturned,
                                                       vcursor.straightevenexchange,
                                                       --fpsstraightevenexchange,
                                                       vcursor.plpceannumber,
                                                       --fpneannumber,
                                                       null,
                                                       --fpnfinishingcode_id,
                                                       vcursor.freeqtyfrequency,
                                                       --fpnfreeqtyfrequency
                                                       employeeid,
                                                       --salesemployee_id
                                                       vcursor.returnstockallowed, dee_del_scheme_id,
                                                       vcursor.remark, vcursor.location,
                                                       vcursor.chargewashesonlyforcog,
                                                       vcursor.priceusage, vcursor.srcchargerent,
                                                       lvntreatmentcheckscheme_id,
                                                       lvndeliverylabellayout_id, salesemployee2id,
                                                       pack_import_stock.get_stockroomid(vcursor.defaultstockroom),
                                                       vcursor.fixedstockroom, vcursor.orderviaweb,
                                                       vcursor.internalcalcpercentagelog,
                                                       vcursor.internalcalcpercentagecog,
                                                       vcursor.chargeexcess, vcursor.budgetusage,
                                                       lv_customerbudgetdefinitionid,
                                                       vcursor.depositstockallowed,
                                                       vcursor.depositstockchargepercentage,
                                                       vcursor.bm1fixedwearers,
                                                       vcursor.sterilisationrequired,
                                                       vcursor.imagecare, vcursor.allowreturntostock,
                                                       nvl(vcursor.seasonalrent, 0),
                                                       lv_autosoil_systemsetting,
                                                       nvl(vcursor.autosoilpercentage, 0),
                                                       vcursor.defaultsupplier_id,
                                                       --contractpurchaseorder_id
                                                       lv_contractpurchaseorder_id,
                                                      nvl(vcursor.bm1rentcpwmax,0),
                            vcursor.depositstocklocation);
              --insert plpcextrainfo
              errormsg := 'insert into plpcextrainfo ';
              insert into plpcextrainfo
                (productlistpercustomer_id, systemuser_id, timestamp, specificbulkpackingtype,
                 servicebilling)
              values
                (plpcid, pack_import.lvnsystemuserid, sysdate,
                 nvl(vcursor.specificbulkpackingtype, 0), nvl(vcursor.servicebilling, 'N'));
              --insert into plpcchargepercentage
              if (vcursor.losschargepercentage is not null or
                 vcursor.srchargepercentage is not null) then
                begin
                  errormsg := 'insert into plpcchargepercentage ';
                  insert into plpcchargepercentage
                    (productlistpercustomer_id, losschargepercentage, srchargepercentage,
                     systemuser_id, timestamp)
                  values
                    (plpcid, nvl(vcursor.losschargepercentage, 100),
                     nvl(vcursor.srchargepercentage, 100), pack_import.lvnsystemuserid, sysdate);
                end;
              end if;
              -- check contract
              if vcursor.contractcode is not null then
                begin
                  begin
                    --get contract id for code
                    select ct.contract_id
                    into   lv_contractid
                    from   contract ct
                    where  ct.code = vcursor.contractcode;
                  exception
                    when no_data_found then
                      begin
                        pack_import.write_log('Cannot link plpc id ' || to_char(plpcid) ||
                                              ' to contract ' || vcursor.contractcode ||
                                              ' because it does not exist!', -3);
                      end;
                  end;
                  if lv_contractid is not null then
                    begin
                      begin
                        --unique key, we will not use start date!
                        --CONTRACT_ID, PRODUCT_ID, SIZEDEFINITION_ID, FINISHINGMETHOD_ID, STARTDATE
                        select max(cp.contractproduct_id)
                        into   lv_contractproductid
                        from   contractproduct cp
                        where  cp.contract_id = lv_contractid
                        and    cp.product_id = vcursor.product_id
                        and    cp.sizedefinition_id = vcursor.sizedefinition_id
                        and    cp.finishingmethod_id = vcursor.finishingmethod_id;
                        if lv_contractproductid is null then
                          begin
                            insert into contractproduct
                              (contractproduct_id, contract_id, finishingmethod_id, startdate,
                               enddate, systemuser_id, timestamp, product_id, sizedefinition_id)
                            values
                              (seq_contractproduct.nextval, lv_contractid,
                               vcursor.finishingmethod_id, vcursor.dateactive, vcursor.dateinactive,
                               pack_import.lvnsystemuserid, sysdate, vcursor.product_id,
                               vcursor.sizedefinition_id)
                            returning contractproduct_id into lv_contractproductid;
                          end;
                        end if;
                      end;
                      --link contract to plpc
                      insert into contractproductplpc
                        (contractproduct_id, productlistpercustomer_id, systemuser_id, timestamp)
                      values
                        (lv_contractproductid, plpcid, pack_import.lvnsystemuserid, sysdate);
                      --count records converted
                      lv_cnt_contract_plpc_link := lv_cnt_contract_plpc_link + 1;
                    exception
                      when others then
                        begin
                          pack_import.write_log('Error linking plpc id ' || to_char(plpcid) ||
                                                ' to contract ' || vcursor.contractcode || ' ' ||
                                                sqlerrm, -3);
                        end;
                    end;
                  end if;
                end;
              end if; --contract code
              --get_sizebillinggroup
             lsizebillinggroupid := pack_import.get_sizebillinggroup(vcursor.sizebillinggroupcode, null);
              -- insert customerrentprice
              if vcursor.rentpricestartdate is not null and vcursor.rentpricenew is not null then
                begin
                  if vcursor.changesperweek = 'Y' then
                    renttype        := 2;
                    nchangesperweek := 5;
                    select count(1)
                    into   lv_checkextra
                    from   i_changesperweekrentprice icp
                    where  icp.customernumber = vcursor.customernumber
                    and    icp.productcode = vcursor.productcode
                    and    icp.sizecode = vcursor.sizecode
                    and    icp.finishingmethodcode = vcursor.finishingmethodcode;
                  else
                    lv_checkextra   := 0;
                    nchangesperweek := 0;
                    if lv_underuse_systemsetting in('4','5') and vcursor.billingmethod = 2 and
                       nvl(pack_import.lvdbcustomercode, 'ABS') <> 'AUS' and
                       nvl(pack_import.lvdbcustomercode, 'ABS') <> 'AMM' then
                      renttype := 5; --underuse
                    elsif vcursor.priceusage = 1 and vcursor.billingmethod = 3 then
                      renttype := 7;
                    elsif vcursor.rentpriceperfrequency = 'Y' then
                      renttype := 4;
                    else
                      renttype := 1;
                    end if;
                  end if;
                  if vcursor.changesperweek <> 'Y' or
                     (vcursor.changesperweek = 'Y' and lv_checkextra = 0) then
                    begin
                      pack_import.cfbcreate_customerrentprice(customerrentpriceid, plpcid,
                                                              vcursor.rentpricenew,
                                                              vcursor.rentpricestartdate,
                                                              nchangesperweek, renttype,null,0,lsizebillinggroupid);
                      pack_import.cfbcreate_pricelistpercustomer(pricelistpercustomerid,
                                                                 vcursor.customer_id, 2, null, null,
                                                                 vcursor.customerdateactive,
                                                                 vcursor.customerdateinactive, null,
                                                                 null, 2);
                      countrowscrpn := countrowscrpn + 1;
                    exception
                      when dup_val_on_index then
                        null;
                      when others then
                        errormsg := 'CFbImportPLCust: Fail to import customerrentprice new for customernumber ' ||
                                    vcursor.customernumber || ' ,productcode:' ||
                                    vcursor.productcode || ' ,size: ' || vcursor.sizecode ||
                                    ' ,finishingmethod: ' || vcursor.finishingmethodcode;
                        pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                    end;
                    if vcursor.rentpriceold > 0 then
                      begin
                        pack_import.cfbcreate_customerrentprice(customerrentpriceid, plpcid,
                                                                vcursor.rentpriceold,
                                                                vcursor.rentpricestartdate - 1,
                                                                nchangesperweek, renttype,null,0,lsizebillinggroupid);
                        countrowscrpo := countrowscrpo + 1;
                      exception
                        when dup_val_on_index then
                          null;
                        when others then
                          errormsg := 'CFbImportPLCust: Fail to import old customerrentprice for customernumber ' ||
                                      vcursor.customernumber || ' ,productcode:' ||
                                      vcursor.productcode || ' ,size: ' || vcursor.sizecode ||
                                      ' ,finishingmethod: ' || vcursor.finishingmethodcode;
                          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                      end;
                    end if;
                  end if;
                end;
              end if;
              if vcursor.loanprice is not null then
                begin
                  begin
                    pack_import.cfbcreate_customerrentprice(customerrentpriceid, plpcid,
                                                            vcursor.loanprice, vcursor.dateactive, 0,
                                                            10,null,0,lsizebillinggroupid);
                    pack_import.cfbcreate_pricelistpercustomer(pricelistpercustomerid,
                                                               vcursor.customer_id, 10, null, null,
                                                               vcursor.customerdateactive,
                                                               vcursor.customerdateinactive, null,
                                                               null, 2);
                    countrowscrpn := countrowscrpn + 1;
                  exception
                    when dup_val_on_index then
                      null;
                    when others then
                      errormsg := 'CFbImportPLCust: Fail to import customerloanprice new for customernumber ' ||
                                  vcursor.customernumber || ' ,productcode:' || vcursor.productcode ||
                                  ' ,size: ' || vcursor.sizecode || ' ,finishingmethod: ' ||
                                  vcursor.finishingmethodcode;
                      pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                  end;
                end;
              end if;
              -- insert customerwashprice
              if vcursor.washpricestartdate is not null and vcursor.washpricenew is not null then
                begin
                  begin
                    insert into customerwashprice
                      (customerwashprice_id, productlistpercustomer_id, timestamp, systemuser_id,
                       price, startdate)
                    values
                      (seq_customerwashprice.nextval, plpcid, sysdate, pack_import.lvnsystemuserid,
                       vcursor.washpricenew, vcursor.washpricestartdate);
                    --pricelistpercustomer
                    pack_import.cfbcreate_pricelistpercustomer(pricelistpercustomerid,
                                                               vcursor.customer_id, 1, null, null,
                                                               vcursor.customerdateactive,
                                                               vcursor.customerdateinactive, null,
                                                               null, 2);
                    countrowscwpn := countrowscwpn + 1;
                  exception
                    when dup_val_on_index then
                      null;
                    when others then
                      errormsg := 'CFbImportPLCust: Fail to import customerwashprice for customernumber ' ||
                                  vcursor.customernumber || ' ,productcode:' || vcursor.productcode ||
                                  ' ,size: ' || vcursor.sizecode || ' ,finishingmethod: ' ||
                                  vcursor.finishingmethodcode;
                      pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                  end;
                  if vcursor.washpriceold > 0 then
                    begin
                      insert into customerwashprice
                        (customerwashprice_id, productlistpercustomer_id, timestamp, systemuser_id,
                         price, startdate)
                      values
                        (seq_customerwashprice.nextval, plpcid, sysdate,
                         pack_import.lvnsystemuserid, vcursor.washpriceold,
                         vcursor.washpricestartdate - 1);
                      countrowscwpo := countrowscwpo + 1;
                    exception
                      when dup_val_on_index then
                        null;
                      when others then
                        errormsg := 'CFbImportPLCust: Fail to import old customerwashprice for customernumber ' ||
                                    vcursor.customernumber || ' ,productcode:' ||
                                    vcursor.productcode || ' ,size: ' || vcursor.sizecode ||
                                    ' ,finishingmethod: ' || vcursor.finishingmethodcode;
                        pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                    end;
                  end if;
                end;
              end if;
              --insert wash price instead of rent price if billingmethod=4
              if (vcursor.rentpricestartdate is not null and vcursor.rentpricenew is not null and
                 vcursor.billingmethod = 4) then
                begin
                  insert into customerwashprice
                    (customerwashprice_id, productlistpercustomer_id, timestamp, systemuser_id,
                     price, startdate)
                  values
                    (seq_customerwashprice.nextval, plpcid, sysdate, pack_import.lvnsystemuserid,
                     vcursor.rentpricenew, vcursor.rentpricestartdate);
                  --pricelistpercustomer
                  pack_import.cfbcreate_pricelistpercustomer(pricelistpercustomerid,
                                                             vcursor.customer_id, 1, null, null,
                                                             vcursor.customerdateactive,
                                                             vcursor.customerdateinactive, null,
                                                             null, 2);
                  countrowscwpn := countrowscwpn + 1;
                  countrowscwpn := countrowscwpn + 1;
                exception
                  when dup_val_on_index then
                    null;
                  when others then
                    errormsg := 'CFbImportPLCust: Fail to import customerwashprice instead of customerrentprice(billingmethod4) for customernumber ' ||
                                vcursor.customernumber || ' ,productcode:' || vcursor.productcode ||
                                ' ,size: ' || vcursor.sizecode || ' ,finishingmethod: ' ||
                                vcursor.finishingmethodcode;
                    pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                end;
                if vcursor.rentpriceold > 0 then
                  begin
                    insert into customerwashprice
                      (customerwashprice_id, productlistpercustomer_id, timestamp, systemuser_id,
                       price, startdate)
                    values
                      (seq_customerwashprice.nextval, plpcid, sysdate, pack_import.lvnsystemuserid,
                       vcursor.rentpriceold, vcursor.rentpricestartdate - 1);
                    countrowscwpo := countrowscwpo + 1;
                  exception
                    when dup_val_on_index then
                      null;
                    when others then
                      errormsg := 'CFbImportPLCust: Fail to import old customerwashprice instead of customerrentprice(billingmethod4) for customernumber ' ||
                                  vcursor.customernumber || ' ,productcode:' || vcursor.productcode ||
                                  ' ,size: ' || vcursor.sizecode || ' ,finishingmethod: ' ||
                                  vcursor.finishingmethodcode;
                      pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                  end;
                end if;
              end if;
              -- insert customerreplacementprice
              if vcursor.replacementpricestartdate is not null and
                 vcursor.replacementpricenew is not null then
                begin
                  begin
                    insert into customerreplacementprice
                      (customerreplacementprice_id, product_id, sizedefinition_id, customer_id,
                       startdate, price, systemuser_id, timestamp,sizebillinggroup_id)
                    values
                      (seq_customerreplacementprice.nextval, vcursor.product_id,
                       vcursor.sizedefinition_id, vcursor.customer_id,
                       vcursor.replacementpricestartdate, vcursor.replacementpricenew,
                       pack_import.lvnsystemuserid, sysdate,lsizebillinggroupid);
                    --pricelistpercustomer
                    pack_import.cfbcreate_pricelistpercustomer(pricelistpercustomerid,
                                                               vcursor.customer_id, 3, null, null,
                                                               vcursor.customerdateactive,
                                                               vcursor.customerdateinactive, null,
                                                               null, 2);
                    countrowscwpn  := countrowscwpn + 1;
                    countrowscrepn := countrowscrepn + 1;
                  exception
                    when dup_val_on_index then
                      null;
                    when others then
                      errormsg := 'CFbImportPLCust: Fail to import customerreplacementprice for customernumber ' ||
                                  vcursor.customernumber || ' ,productcode:' || vcursor.productcode ||
                                  ' ,size: ' || vcursor.sizecode || ' ,finishingmethod: ' ||
                                  vcursor.finishingmethodcode;
                      pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                  end;
                  if vcursor.replacementpriceold > 0 then
                    begin
                      insert into customerreplacementprice
                        (customerreplacementprice_id, product_id, sizedefinition_id, customer_id,
                         startdate, price, systemuser_id, timestamp)
                      values
                        (seq_customerreplacementprice.nextval, vcursor.product_id,
                         vcursor.sizedefinition_id, vcursor.customer_id,
                         vcursor.replacementpricestartdate - 1, vcursor.replacementpriceold,
                         pack_import.lvnsystemuserid, sysdate);
                      countrowscrepo := countrowscrepo + 1;
                    exception
                      when dup_val_on_index then
                        null;
                      when others then
                        errormsg := 'CFbImportPLCust: Fail to import old customerreplacementprice for customernumber ' ||
                                    vcursor.customernumber || ' ,productcode:' ||
                                    vcursor.productcode || ' ,size: ' || vcursor.sizecode ||
                                    ' ,finishingmethod: ' || vcursor.finishingmethodcode;
                        pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                    end;
                  end if;
                end;
              end if;
              -- insert customersalesprice
              if vcursor.salespricestartdate is not null and vcursor.salespricenew is not null then
                begin
                  begin
                    insert into customersalesprice
                      (customersalesprice_id, product_id, sizedefinition_id, customer_id, startdate,
                       price, systemuser_id, timestamp, volumeprice,sizebillinggroup_id)
                    values
                      (seq_customersalesprice.nextval, vcursor.product_id,
                       vcursor.sizedefinition_id, vcursor.customer_id, vcursor.salespricestartdate,
                       vcursor.salespricenew, pack_import.lvnsystemuserid, sysdate,
                       nvl(vcursor.volumeprice, 1),lsizebillinggroupid);
                    --pricelistpercustomer
                    pack_import.cfbcreate_pricelistpercustomer(pricelistpercustomerid,
                                                               vcursor.customer_id, 4, null, null,
                                                               vcursor.customerdateactive,
                                                               vcursor.customerdateinactive, null,
                                                               null, 2);
                    countrowscwpn := countrowscwpn + 1;
                    countrowscspn := countrowscspn + 1;
                  exception
                    when dup_val_on_index then
                      null;
                    when others then
                      errormsg := 'CFbImportPLCust: Fail to import customersalesprice for customernumber ' ||
                                  vcursor.customernumber || ' ,productcode:' || vcursor.productcode ||
                                  ' ,size: ' || vcursor.sizecode || ' ,finishingmethod: ' ||
                                  vcursor.finishingmethodcode;
                      pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                  end;
                  --salespriceold
                  if vcursor.salespriceold > 0 then
                    begin
                      insert into customersalesprice
                        (customersalesprice_id, product_id, sizedefinition_id, customer_id,
                         startdate, price, systemuser_id, timestamp)
                      values
                        (seq_customersalesprice.nextval, vcursor.product_id,
                         vcursor.sizedefinition_id, vcursor.customer_id,
                         vcursor.salespricestartdate - 1, vcursor.salespriceold,
                         pack_import.lvnsystemuserid, sysdate);
                      countrowscspo := countrowscspo + 1;
                    exception
                      when dup_val_on_index then
                        null;
                      when others then
                        errormsg := 'CFbImportPLCust: Fail to import old customersalesprice for customernumber ' ||
                                    vcursor.customernumber || ' ,productcode:' ||
                                    vcursor.productcode || ' ,size: ' || vcursor.sizecode ||
                                    ' ,finishingmethod: ' || vcursor.finishingmethodcode;
                        pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                    end;
                  end if;
                end;
              end if;
              --insert washpricecog if provided correctly
              if vcursor.washpricecognew is not null and vcursor.washpricecogstartdate is not null then
                begin
                  insert into customerwashprice
                    (customerwashprice_id, productlistpercustomer_id, timestamp, systemuser_id,
                     price, startdate, pricetype)
                  values
                    (seq_customerwashprice.nextval, plpcid, sysdate, pack_import.lvnsystemuserid,
                     vcursor.washpricecognew, vcursor.washpricecogstartdate, 2);
                  --pricelistpercustomer
                  pack_import.cfbcreate_pricelistpercustomer(pricelistpercustomerid,
                                                             vcursor.customer_id, 1, null, null,
                                                             vcursor.customerdateactive,
                                                             vcursor.customerdateinactive, null,
                                                             null, 2);
                exception
                  when dup_val_on_index then
                    null;
                  when others then
                    errormsg := 'CFbImportPLCust: Fail to import new customerwashpricecog for customernumber ' ||
                                vcursor.customernumber || ' ,productcode:' || vcursor.productcode ||
                                ' ,size: ' || vcursor.sizecode || ' ,finishingmethod: ' ||
                                vcursor.finishingmethodcode;
                    pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                end;
              end if;
              --insert washpricecog OLD if provided correctly
              if vcursor.washpricecogold is not null and vcursor.washpricecogstartdate is not null then
                begin
                  insert into customerwashprice
                    (customerwashprice_id, productlistpercustomer_id, timestamp, systemuser_id,
                     price, startdate, pricetype)
                  values
                    (seq_customerwashprice.nextval, plpcid, sysdate, pack_import.lvnsystemuserid,
                     vcursor.washpricecogold, vcursor.washpricecogstartdate - 1, 2);
                exception
                  when dup_val_on_index then
                    null;
                  when others then
                    errormsg := 'CFbImportPLCust: Fail to import old customerwashpricecog for customernumber ' ||
                                vcursor.customernumber || ' ,productcode:' || vcursor.productcode ||
                                ' ,size: ' || vcursor.sizecode || ' ,finishingmethod: ' ||
                                vcursor.finishingmethodcode;
                    pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                end;
              end if;
              --PVD insert discounts.
              if vcursor.discountpercentagewash is not null then
                begin
                  insert into customerwashdiscount
                    (customerwashdiscount_id, productlistpercustomer_id, timestamp, systemuser_id,
                     discount, startdate)
                  values
                    (seq_customerwashdiscount.nextval, plpcid, sysdate, pack_import.lvnsystemuserid,
                     vcursor.discountpercentagewash, vcursor.dateactive);
                exception
                  when others then
                    begin
                      errormsg := 'CFbImportPLCust: Fail to import customerwashdiscount for customernumber ' ||
                                  vcursor.customernumber || ' ,productcode:' || vcursor.productcode;
                      pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                    end;
                end;
              end if;
              if vcursor.discountpercentagerent is not null then
                begin
                  if vcursor.changesperweek = 'Y' then
                    renttype := 2;
                  else
                    renttype := 1;
                  end if;
                  insert into customerrentdiscount
                    (customerrentdiscount_id, productlistpercustomer_id, timestamp, systemuser_id,
                     discount, startdate, typeofrent)
                  values
                    (seq_customerrentdiscount.nextval, plpcid, sysdate, pack_import.lvnsystemuserid,
                     vcursor.discountpercentagerent, vcursor.dateactive, renttype);
                exception
                  when others then
                    begin
                      errormsg := 'CFbImportPLCust: Fail to import discountpercentagerent for customernumber ' ||
                                  vcursor.customernumber || ' ,productcode:' || vcursor.productcode;
                      pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                    end;
                end;
              end if;
              --end insert discounts.
              -- insert productgrouppercustomer
              begin
                insert into productgrouppercustomer
                  (productgroup_id, customer_id, invoicegroupingcode, customcode, customdescritpion,
                   systemuser_id, timestamp, active)
                values
                  (vcursor.productgroup_id, vcursor.customer_id, null, null, null, 1, sysdate, 'Y');
                countrowspgpc := countrowspgpc + 1;
              exception
                when dup_val_on_index then
                  null;
                when others then
                  errormsg := 'CFbImportPLCust: Fail to import productgrouppercustomer for customernumber ' ||
                              vcursor.customernumber || ' ,productcode:' || vcursor.productcode;
                  pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
              end;
              -- insert productdeliveryday
              begin
                if vcursor.deliverydaymo is not null then
                  cfbcreate_productdeliveryday(plpcid, 1, vcursor.deliverydaymo,
                                               vcursor.customer_id, vcursor.typeofmerchandise,
                                               vcursor.circulatinginventory,
                                               vcursor.autosoilpercentage);
                  countrowsdd := countrowsdd + 1;
                end if;
                if vcursor.deliverydaytu is not null then
                  cfbcreate_productdeliveryday(plpcid, 2, vcursor.deliverydaytu,
                                               vcursor.customer_id, vcursor.typeofmerchandise,
                                               vcursor.circulatinginventory,
                                               vcursor.autosoilpercentage);
                  countrowsdd := countrowsdd + 1;
                end if;
                if vcursor.deliverydaywe is not null then
                  cfbcreate_productdeliveryday(plpcid, 3, vcursor.deliverydaywe,
                                               vcursor.customer_id, vcursor.typeofmerchandise,
                                               vcursor.circulatinginventory,
                                               vcursor.autosoilpercentage);
                  countrowsdd := countrowsdd + 1;
                end if;
                if vcursor.deliverydayth is not null then
                  cfbcreate_productdeliveryday(plpcid, 4, vcursor.deliverydayth,
                                               vcursor.customer_id, vcursor.typeofmerchandise,
                                               vcursor.circulatinginventory,
                                               vcursor.autosoilpercentage);
                  countrowsdd := countrowsdd + 1;
                end if;
                if vcursor.deliverydayfr is not null then
                  cfbcreate_productdeliveryday(plpcid, 5, vcursor.deliverydayfr,
                                               vcursor.customer_id, vcursor.typeofmerchandise,
                                               vcursor.circulatinginventory,
                                               vcursor.autosoilpercentage);
                  countrowsdd := countrowsdd + 1;
                end if;
                if vcursor.deliverydaysa is not null then
                  cfbcreate_productdeliveryday(plpcid, 6, vcursor.deliverydaysa,
                                               vcursor.customer_id, vcursor.typeofmerchandise,
                                               vcursor.circulatinginventory,
                                               vcursor.autosoilpercentage);
                  countrowsdd := countrowsdd + 1;
                end if;
                if vcursor.deliverydaysu is not null then
                  cfbcreate_productdeliveryday(plpcid, 7, vcursor.deliverydaysu,
                                               vcursor.customer_id, vcursor.typeofmerchandise,
                                               vcursor.circulatinginventory,
                                               vcursor.autosoilpercentage);
                  countrowsdd := countrowsdd + 1;
                end if;
              exception
                when dup_val_on_index then
                  null;
                when others then
                  null;
              end;
              -- insert productlistperdistribpoint
              --ONLY when needed when there are NO corresponding I_DELIVERYSTANDARD records!
              select count(1)
              into   plpdpsequence
              from   i_deliverystandards s
              where  s.customernumber = vcursor.customernumber
              and    s.productcode = vcursor.productcode;
              --#502807 and    s.productcode = vcursor.productcode;
              --only continue when its not size * and there are no records in i_deliverystandards
              if (vcursor.sizecode != '*' and plpdpsequence = 0 and
                 (vcursor.stddeliveryqtymo >= 0 or vcursor.stddeliveryqtytu >= 0 or
                 vcursor.stddeliveryqtywe >= 0 or vcursor.stddeliveryqtyth >= 0 or
                 vcursor.stddeliveryqtyfr >= 0 or vcursor.stddeliveryqtysa >= 0 or
                 vcursor.stddeliveryqtysu >= 0 or vcursor.circulatinginventory > 0 or
                 vcursor.fixedquantity > 0 or vcursor.onsitecount > 0)) then
                begin
                  select min(distributionpoint_id)
                  into   distributionpointid
                  from   distributionpoint
                  where  department_id = (select min(department_id)
                                          from   department
                                          where  customer_id = vcursor.customer_id);
                  select min(productlistperdistribpoint_id)
                  into   productlistperdistribpointid
                  from   productlistperdistribpoint
                  where  distributionpoint_id = distributionpointid
                  and    product_id = vcursor.product_id
                  and    sizedefinition_id = vcursor.sizedefinition_id
                  and    finishingmethod_id = vcursor.finishingmethod_id;
                  if productlistperdistribpointid is null then
                    begin
                      select max(countsequence) + 1
                      into   plpdpsequence
                      from   productlistperdistribpoint
                      where  distributionpoint_id = distributionpointid;
                      if plpdpsequence is null then
                        plpdpsequence := 1;
                      end if;
                      insert into productlistperdistribpoint
                        (productlistperdistribpoint_id, distributionpoint_id, product_id,
                         sizedefinition_id, finishingmethod_id, countsequence, orderingmethod,
                         holidayusagefactor, systemuser_id, timestamp)
                      values
                        (seq_productlistperdistribpoint.nextval, distributionpointid,
                         vcursor.product_id, vcursor.sizedefinition_id, vcursor.finishingmethod_id,
                         plpdpsequence, 2, 100, pack_import.lvnsystemuserid, sysdate)
                      returning productlistperdistribpoint_id into productlistperdistribpointid;
                      countrowsplpdp := countrowsplpdp + 1;
                    end;
                  end if;
                exception
                  when others then
                    errormsg := 'CFbImportPLCust: Fail to import productlistperdistribpoint  for customernumber ' ||
                                vcursor.customernumber || ' ,productcode:' || vcursor.productcode ||
                                ' ,size: ' || vcursor.sizecode || ' ,finishingmethod: ' ||
                                vcursor.finishingmethodcode;
                    pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                end;
                -- insert standarddeliveryline
                begin
                  select min(standarddelivery_id)
                  into   standarddeliveryid
                  from   standarddelivery
                  where  standarddelivery.distributionpoint_id = distributionpointid;
                  if vcursor.delayevenexchange in (0, 7) and
                     vcursor.deliveryschedulecode is not null then
                    begin
                      select min(cs.deliveryscheme_id)
                      into   del_scheme_id
                      from   customerdeliveryscheme cs, deliveryscheme ds
                      where  cs.deliveryscheme_id = ds.deliveryscheme_id
                      and    ds.code = upper(trim(vcursor.deliveryschedulecode))
                      and    cs.customer_id = vcursor.customer_id;
                      if del_scheme_id is null then
                        begin
                          select s.deliveryscheme_id
                          into   del_scheme_id
                          from   deliveryscheme s
                          where  s.code = vcursor.deliveryschedulecode;
                          pack_import.cfbcreate_customerdelscheme(vcursor.customer_id,
                                                                  del_scheme_id, 1);
                        exception
                          when others then
                            begin
                              del_scheme_id := null;
                              errormsg      := 'CFbImportPLCust: Fail to import deliveryscheme ' ||
                                               vcursor.deliveryschedulecode ||
                                               ' for customernumber ' || vcursor.customernumber ||
                                               ' ,productcode:' || vcursor.productcode ||
                                               ' ,size: ' || vcursor.sizecode ||
                                               ' deliveryscheme does not exists.';
                              pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                            end;
                        end;
                      end if;
                    end;
                  else
                    begin
                      select min(cs.deliveryscheme_id)
                      into   del_scheme_id
                      from   customerdeliveryscheme cs, deliveryscheme ds
                      where  cs.deliveryscheme_id = ds.deliveryscheme_id
                      and    cs.customer_id = vcursor.customer_id;
                    end;
                  end if;
                  pack_import.cfbcreate_standarddeliveryline(standarddeliverylineid,
                                                             standarddeliveryid,
                                                             productlistperdistribpointid, null,
                                                             null, null, vcursor.fixedquantity,
                                                             vcursor.dateactive,
                                                             vcursor.dateinactive, del_scheme_id,
                                                             plpcid, null, null, 0);
                  countrowsstdl := countrowsstdl + 1;
                exception
                  when dup_val_on_index then
                    null;
                  when others then
                    errormsg := 'CFbImportPLCust: Fail to import standarddeliveryline for customernumber ' ||
                                vcursor.customernumber || ' ,productcode:' || vcursor.productcode ||
                                ' ,size: ' || vcursor.sizecode || ' ,finishingmethod: ' ||
                                vcursor.finishingmethodcode;
                    pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                end;
                -- insert standarddeliveryamount
                begin
                  if vcursor.stddeliveryqtymo is not null then
                    begin
                      pack_import.cfbstorecreate_stddelamount(standarddeliverylineid, 1,
                                                              vcursor.stddeliveryqtymo);
                      countrowsstda := countrowsstda + 1;
                    end;
                  end if;
                  if vcursor.stddeliveryqtytu >= 0 then
                    pack_import.cfbstorecreate_stddelamount(standarddeliverylineid, 2,
                                                            vcursor.stddeliveryqtytu);
                    countrowsstda := countrowsstda + 1;
                  end if;
                  if vcursor.stddeliveryqtywe >= 0 then
                    pack_import.cfbstorecreate_stddelamount(standarddeliverylineid, 3,
                                                            vcursor.stddeliveryqtywe);
                    countrowsstda := countrowsstda + 1;
                  end if;
                  if vcursor.stddeliveryqtyth >= 0 then
                    pack_import.cfbstorecreate_stddelamount(standarddeliverylineid, 4,
                                                            vcursor.stddeliveryqtyth);
                    countrowsstda := countrowsstda + 1;
                  end if;
                  if vcursor.stddeliveryqtyfr >= 0 then
                    pack_import.cfbstorecreate_stddelamount(standarddeliverylineid, 5,
                                                            vcursor.stddeliveryqtyfr);
                    countrowsstda := countrowsstda + 1;
                  end if;
                  if vcursor.stddeliveryqtysa >= 0 then
                    pack_import.cfbstorecreate_stddelamount(standarddeliverylineid, 6,
                                                            vcursor.stddeliveryqtysa);
                    countrowsstda := countrowsstda + 1;
                  end if;
                  if vcursor.stddeliveryqtysu >= 0 then
                    pack_import.cfbstorecreate_stddelamount(standarddeliverylineid, 7,
                                                            vcursor.stddeliveryqtysu);
                    countrowsstda := countrowsstda + 1;
                  end if;
                exception
                  when dup_val_on_index then
                    null;
                  when others then
                    errormsg := 'CFbImportPLCust: Fail to import standarddeliveryamount for customernumber ' ||
                                vcursor.customernumber || ' ,productcode:' || vcursor.productcode ||
                                ' ,size: ' || vcursor.sizecode || ' ,finishingmethod: ' ||
                                vcursor.finishingmethodcode;
                    pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                end;
                -- insert rentalqtyadjustment
                if vcursor.circulatinginventory > 0 then
                  begin
                    select reasoncode_id
                    into   reasoncodeid
                    from   reasoncode
                    where  reasoncode.code = '-';
                    insert into rentalqtyadjustment
                      (rentalqtyadjustment_id, productlistperdistribpoint_id, remark, quantity,
                       adjustmentdate, reasoncode_id, timestamp, systemuser_id, qualitygrade_id,
                       quantityfirstdelivery)
                    values
                      (seq_rentalqtyadjustment.nextval, productlistperdistribpointid, null,
                       vcursor.circulatinginventory, vcursor.dateactive, reasoncodeid, sysdate,
                       pack_import.lvnsystemuserid, pack_import.lvndefaultqualitygradeid,
                       vcursor.circulatinginventory);
                    countrowsrqa := countrowsrqa + 1;
                  exception
                    when dup_val_on_index then
                      null;
                    when others then
                      errormsg := 'CFbImportPLCust: Fail to import rentalqtyadjustment for customernumber ' ||
                                  vcursor.customernumber || ' ,productcode:' || vcursor.productcode ||
                                  ' ,size: ' || vcursor.sizecode || ' ,finishingmethod: ' ||
                                  vcursor.finishingmethodcode;
                      pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                  end;
                end if;
              end if; -- for productlistperdistribpoint
              --count plpc records imported
              countrows := countrows + 1;
              commit;
            exception
              when others then
                errormsg := 'CFbImportPLCust: Fail to import productlistpercustomer line for customernumber ' ||
                            vcursor.customernumber || ' ,productcode:' || vcursor.productcode ||
                            ' ,size: ' || vcursor.sizecode || ' ,finishingmethod: ' ||
                            vcursor.finishingmethodcode;
                pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
            end;
          end if; --- import ='Y'
        end;
      end loop;
      --extra checks
      update customer c
      set    c.customerrelated = 1
      where  c.customerrelated = 0
      and    exists (select 1 from i_customer ic where ic.customernumber = c.customernumber)
      and    exists (select 1
              from   i_productlistpercustomer il
              where  il.customernumber = c.customernumber
              and    il.customerrelated = 'Y');
      commit;
      --
      pack_import.write_log(countplpc || ' already exist in productlistpercustomer.');
      select count(*) into countplpc from i_productlistpercustomer;
      pack_import.write_log(countplpc || ' in i_productlistpercustomer.');
      pack_import.write_log(countrows || ' productlistpercustomer rows imported.');
      select count(*) into countplpc from productlistpercustomer;
      pack_import.write_log(countplpc || ' now in productlistpercustomer.');
      if lv_cnt_contract_plpc_link > 0 then
        pack_import.write_log(lv_cnt_contract_plpc_link || ' plpc records linked to contracts.');
      end if;
      if countrowscrpn > 0 then
        pack_import.write_log(countrowscrpn || ' customerrentpricenew rows imported.');
      end if;
      if countrowscrpo > 0 then
        pack_import.write_log(countrowscrpo || ' customerrentpriceold rows imported.');
      end if;
      if countrowscwpn > 0 then
        pack_import.write_log(countrowscwpn || ' customerwashpricenew rows imported.');
      end if;
      if countrowscwpo > 0 then
        pack_import.write_log(countrowscwpo || ' customerwashpriceold rows imported.');
      end if;
      if countrowscrepn > 0 then
        pack_import.write_log(countrowscrepn || ' customerreplacementpricenew rows imported.');
      end if;
      if countrowscrepo > 0 then
        pack_import.write_log(countrowscrepo || ' customerreplacementpricenew rows imported.');
      end if;
      if countrowscspn > 0 then
        pack_import.write_log(countrowscspn || ' customersalespricenew rows imported.');
      end if;
      if countrowscspo > 0 then
        pack_import.write_log(countrowscspo || ' customersalespricenew rows imported.');
      end if;
      if countrowsdd > 0 then
        pack_import.write_log(countrowsdd || ' productdeliveryday rows imported.');
      end if;
      if countrowsstdl > 0 then
        pack_import.write_log(countrowsstdl || ' standarddeliveryline rows imported.');
      end if;
      if countrowsstda > 0 then
        pack_import.write_log(countrowsstda || ' standarddeliveryamount rows imported.');
      end if;
      if countrowsplpdp > 0 then
        pack_import.write_log(countrowsplpdp || ' productlistperdistributionpoint rows imported.');
      end if;
      if countrowsrqa > 0 then
        pack_import.write_log(countrowsrqa || ' rentalqtyadjustment rows imported.');
      end if;
      if countrowspgpc > 0 then
        pack_import.write_log(countrowspgpc || ' productgrouppercustomer rows imported.');
      end if;
      if lv_err_plpc_bm4 > 0 then
        begin
          pack_import.write_log('Warning ' || lv_err_plpc_bm4 ||
                                ' sales(only) products PLPC records inserted with billing method 4 instead!',
                                3);
        end;
      end if;
    end;
    cfbaddcustomeractivities;
    cfbimportmatorderinginfo;
    cfbfixedwearers;
    imp_plpcbudgetprotection;
  import_plpctemprentstop;
    pack_import.write_log('Stop import productlistpercustomer: ' ||
                          to_char(sysdate, 'dd-mm-yyyy hh24:mi:ss'));
  end cfbimportplcust;
  procedure cfbimportinventoryadjustment is
    --pvd added 28 januari 2004.
    nproductlistperdistrionpointid productlistperdistribpoint.productlistperdistribpoint_id%type;
  begin
    for x in (select o.* from i_onsiteinvadjustment o) loop
      begin
        -- get nproductlistperdistrionpointid
        select d.productlistperdistribpoint_id
        into   nproductlistperdistrionpointid
        from   productlistperdistribpoint d, product p, sizedefinition s, finishingmethod f,
               distributionpoint i, department z, customer c
        where  d.product_id = p.product_id
        and    p.code = x.productcode
        and    d.sizedefinition_id = s.sizedefinition_id
        and    s.code = x.sizecode
        and    d.finishingmethod_id = f.finishingmethod_id
        and    f.code = x.finishingmethodcode
        and    d.distributionpoint_id = i.distributionpoint_id
        and    i.department_id = z.department_id
        and    i.distributionpointnumber = x.consumptionpointnumber
        and    z.customer_id = c.customer_id
        and    c.customernumber = x.customernumber
        and    z.departmentnumber = x.departmentnumber;
        -- insert into onsiteinventoryadjustment
        insert into onsiteinventoryadjustment
          (onsiteinventoryadjustment_id, productlistperdistribpoint_id, origin, inventorydate,
           quantity, reference, systemuser_id, timestamp)
        values
          (seq_onsiteinventoryadjustment.nextval, nproductlistperdistrionpointid, 9,
           x.inventorydate, nvl(x.quantity, 0), x.reference, pack_import.lvnsystemuserid, sysdate);
      exception
        when no_data_found then
          pack_import.write_log('No data importinvadjustment error: ' || substr(sqlerrm, 1, 512), 3);
        when dup_val_on_index then
          update onsiteinventoryadjustment
          set    quantity = nvl(x.quantity, 0)
          where  productlistperdistribpoint_id = nproductlistperdistrionpointid
          and    inventorydate = x.inventorydate
          and    reference = x.reference
          and    origin = 9;
      end;
    end loop;
    commit;
  exception
    when others then
      pack_import.write_log('cfbimportinventoryadjustment error: ' || substr(sqlerrm, 1, 512), 3);
  end cfbimportinventoryadjustment;
  procedure cfbimportturnoverplpc is
    lcounter         number := 0;
    lerrormsg        varchar2(512);
    lproductid       product.product_id%type;
    lcustomerid      customer.customer_id%type;
    lturnovergroupid turnovergroup.turnovergroup_id%type;
    ltaxgroupid      taxgroup.taxgroup_id%type;
  begin
    --insert all missing records
    for x in (select * from i_turnover_plpc i) loop
      begin
        --find product and customer
        lerrormsg := ' product ' || x.productcode;
        select p.product_id into lproductid from product p where p.code = x.productcode;
        lerrormsg := ' customer ' || x.customernumber;
        select c.customer_id
        into   lcustomerid
        from   customer c
        where  c.customernumber = x.customernumber;
        --get taxgroup
        if x.taxgroup is null then
          begin
            ltaxgroupid := null;
          end;
        else
          begin
            lerrormsg := ' taxgroup code ' || x.taxgroup;
            select tx.taxgroup_id into ltaxgroupid from taxgroup tx where tx.code = x.taxgroup;
          end;
        end if; --taxgroup
        begin
          select g.turnovergroup_id
          into   lturnovergroupid
          from   turnovergroup g
          where  g.code = x.turnovergroupcode;
        exception
          when no_data_found then
            begin
              --add missing turnovergroup
              lerrormsg := ' during insert missing turnovergroup ' || x.turnovergroupcode;
              insert into turnovergroup
                (turnovergroup_id, salesjournalgroup_id, code, legacycode, active, systemuser_id,
                 timestamp, taxgroup_id)
              values
                (seq_turnovergroup.nextval, pack_import.lvnsalesjournalgroupminusid,
                 x.turnovergroupcode, null, 'Y', pack_import.lvnsystemuserid, sysdate, ltaxgroupid)
              returning turnovergroup_id into lturnovergroupid;
              insert into turnovergroup_desc
                (turnovergroup_id, language_id, description, systemuser_id, timestamp)
              values
                (lturnovergroupid, pack_import.lvnlanguageid, x.turnovergroupcode,
                 pack_import.lvnsystemuserid, sysdate);
            end;
        end;
        begin
          insert into customerproducttogdef
            (customer_id, product_id, turnovergroup_id, type, percentage, systemuser_id, timestamp)
          values
            (lcustomerid, lproductid, lturnovergroupid, x.turnovergrouptype, x.percentage,
             pack_import.lvnsystemuserid, sysdate);
          lcounter := lcounter + 1;
        exception
          when dup_val_on_index then
            null; --no problem
        end;
        if ltaxgroupid is not null then
          begin
            insert into customerproducttaxdef
              (customer_id, product_id, type, taxgroup_id, systemuser_id, timestamp)
            values
              (lcustomerid, lproductid, x.turnovergrouptype, ltaxgroupid,
               pack_import.lvnsystemuserid, sysdate);
          exception
            when dup_val_on_index then
              null; --no problem
          end;
        end if;
        commit;
      exception
        when no_data_found then
          begin
            rollback;
            lerrormsg := 'Error' || lerrormsg || ' not found!';
            pack_import.write_log(lerrormsg || substr(sqlerrm, 1, 512), 3);
          end;
      end;
    end loop;
    pack_import.write_log('    Succesfully imported ' || to_char(lcounter) ||
                          ' turnover plpc records.');
  exception
    when others then
      begin
        rollback;
        lerrormsg := 'Error during cfbimportturnoverplpc ' || lerrormsg;
        pack_import.write_log(lerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimportturnoverplpc;
end pack_import_plcustomer;
/
create or replace package pack_import_pricestructure is
  -- Author  : PVD
  -- Created : 18-jun-2003
  -- Version : 2.0
  -- Purpose : Conversion from pricelist structure into ABSSolute DB.
  -- Updated : 17-sep-2020 ABS-107917 DEFAULTPRICELIST to I_PRICELIST default value will be N
  --           19-sep-2020 ABS-107917 added customerexchangecharge, customercashdelay
  --           24-aug-2022 ABS-139603 conversion prevent double pricelist prios
  --           12-sep-2025 ABSN-10507 Data Conversion question on customerstockcharge
  procedure cfbimport_pricelist;
  procedure cfbimport_pricelistpercustomer;
  procedure cfbimport_specialchargepercust;
  procedure cfbimport_specialchargeperprod;
  procedure cfbimport_freqrelatedprices;
  procedure cfbimport_changespwrentprices;
  procedure import_customerexchangecharge;
  procedure import_customercashdelay;
  procedure cfbimport_customercharges;
  procedure cfbimport_customerstockcharge;
  procedure imp_customerbgprotectionprice;
  procedure cfbimport_costpricelist;
  procedure import_chargespecialsize_price;
  procedure imp_customerimagecareprice;
  procedure imp_priceindex;
end pack_import_pricestructure;
/
create or replace package body pack_import_pricestructure is
  lvnerrormsg varchar2(256);
  procedure cfbaddproductsizes is
    countrows            integer;
    errormsg             varchar2(256);
    fpnsizedefinition_id sizedefinition.sizedefinition_id%type;
  begin
    --sizedefinition
    countrows := 0;
    for x in (select trim(p.sizecode) sizecode
              from   i_pricelist p
              where  trim(p.sizecode) is not null
              and    not exists
               (select code from sizedefinition where code = trim(p.sizecode))
              group  by trim(p.sizecode)) loop
      begin
        pack_import.cfbcreate_sizedefinition(fpnsizedefinition_id, x.sizecode, 'N', null, null,
                                             null, 'N');
        pack_import.cfbcreate_sizedefinition_desc(fpnsizedefinition_id, x.sizecode);
        commit;
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          rollback;
          errormsg := 'cfbaddproductsizes: Fail to import sizedefinition ' || x.sizecode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    -- import productsize
    for x in (select p. product_id, s.sizedefinition_id
              from   product p, sizedefinition s, i_pricelist l
              where  trim(l.productcode) = p.code
              and    trim(l.sizecode) = s.code
              and    ((p.typeofmerchandise = 2 and s.code = '*') or s.code <> '*')
              and    not exists (select *
                      from   productsize z
                      where  z.product_id = p.product_id
                      and    z.sizedefinition_id = s.sizedefinition_id)) loop
      begin
        pack_import.cfbcreate_productsize(x.product_id,
                                          --fpnproduct_id,
                                          x.sizedefinition_id,
                                          --fpnsizedefinition_id,
                                          'N',
                                          --fpsspecialsize,
                                          --null,
                                          --fpsexternalordernumber,
                                          1,
                                          --fpnpackingamount,
                                          0
                                          --fpntheoreticalweight,
                                         , null);
        commit;
      exception
        when dup_val_on_index then
          null;
        when others then
          begin
            rollback;
            lvnerrormsg := 'cfbaddproductsizes, failed to add productsize';
            pack_import.write_log(lvnerrormsg || ' ' || substr(sqlerrm, 1, 512), 3);
          end;
      end;
    end loop;
  end cfbaddproductsizes;
  procedure cfbimport_pricelist is
    fpncurrency_id         currency.currency_id%type;
    fpnfinishingmethod_id  finishingmethod.finishingmethod_id%type;
    fpnweighingcategory_id weighingcategory.weighingcategory_id%type;
    fpnrepairtype_id       repairtype.repairtype_id%type;
    fpbimport_allowed      boolean := true;
    fpngeneralpricelist_id generalpricelist.generalpricelist_id%type;
    fpngeneralxxxprice_id  generalwashprice.generalwashprice_id%type;
    lcounter               number := 0;
    lv_chainid             chain.chain_id%type;
    lv_volumeprice_yn      varchar2(1);
    gv_message             abslog.message%type;
    lv_sizebillingroup_id  sizebillinggroup.sizebillinggroup_id%type;
  begin
    gv_message := 'cfbimport_pricelist | i_pricelist';
    pack_import_pricestructure.cfbaddproductsizes;
    --to make sure the special charge exists
    pack_import_pricestructure.cfbimport_specialchargepercust;
     -- Import price list. Note: product and size must already exist.
    /* Different price types are:
    1=Wash
    2=Rent
    3=Replacement
    4=Sales
    5=Weight
    6=Repair
    7/8=Emblem/template
    9=Insurance */
    for x in (select i.pricelistcode, i.pricelisttype,
                     rtrim(i.finishingmethodcode) finishingmethodcode, i.weighingcategorycode,
                     i.repairtypecode, i.rentpricetype, p.product_id, s.sizedefinition_id,
                     i.pricelistdescription, i.rentchangesperweek, i.currencycode, i.price,
                     i.priceperminute, i.startdateprice, i.sizecode, i.washpricetype, i.productcode,
                     i.chaincode, i.priceindexcode, i.priceupdatelockdate, i.volumeprice,
                     i.specialchargecode, i.percentage, i.pricecomponent,
                     nvl(i.defaultpricelist, 'N') defaultpricelist, i.maxinventory,
                     (select sc.specialcharge_id
                       from   specialcharge sc
                       where  sc.code = upper(trim(i.specialchargecode))) specialcharge_id,i.sizebillinggroupcode
              from   i_pricelist i
              left   outer join product p
              on     p.code = upper(trim(i.productcode))
              left   outer join sizedefinition s
              on     s.code = upper(trim(i.sizecode))
              where  (p.product_id is not null or i.pricelisttype in (5, 6, 10))) loop
      begin
        fpbimport_allowed := true;
        begin
          -- Determine currency.
          select currency_id into fpncurrency_id from currency where code = x.currencycode;
        exception
          when no_data_found then
            fpbimport_allowed := false;
            lvnerrormsg       := gv_message || 'NO_DATA_FOUND currency: ' || x.currencycode;
            pack_import.write_log(lvnerrormsg, -3);
        end;
        if x.pricelisttype in (1, 2, 9) then
          if (x.pricecomponent is null or x.finishingmethodcode is not null) then
            begin
              --determine finishing method id if needed.
              select f.finishingmethod_id
              into   fpnfinishingmethod_id
              from   finishingmethod f
              where  f.code = x.finishingmethodcode;
              -- product finishing method
              lvnerrormsg := gv_message || 'Adding product finishing method ';
              pack_import.cfbcreate_prodfinishingmethod(x.product_id, fpnfinishingmethod_id);
            exception
              when no_data_found then
                fpbimport_allowed := false;
                lvnerrormsg       := gv_message || 'NO_DATA_FOUND finishingmethodcode: ' || x.finishingmethodcode;
                pack_import.write_log(lvnerrormsg, -3);
            end;
          else
            -- when not needed make fpnfinishingmethod_id null.
            fpnfinishingmethod_id := null;
          end if;
        else
          -- when not needed make fpnfinishingmethod_id null.
          fpnfinishingmethod_id := null;
        end if;
        if x.pricelisttype in (1, 2, 3, 4, 7, 8, 9, 12) then
          if x.product_id is null then
            -- Check product
            fpbimport_allowed := false;
            lvnerrormsg       := gv_message || 'Product is not known : ' || nvl(x.productcode, 'NULL');
            pack_import.write_log(lvnerrormsg, -3);
          end if;
        end if;
        if x.pricelisttype in (1, 2, 3, 4, 7, 9, 12) then
          if x.sizedefinition_id is null then
            -- Check size
            fpbimport_allowed := false;
            lvnerrormsg       := gv_message || 'Sizedefinition is not known : ' || nvl(x.sizecode, 'NULL');
            pack_import.write_log(lvnerrormsg, -3);
          end if;
        end if;
        if x.pricelisttype = 5 then
          begin
            --determine weighing category id if needed.
            select w.weighingcategory_id
            into   fpnweighingcategory_id
            from   weighingcategory w
            where  w.code = x.weighingcategorycode;
          exception
            when no_data_found then
              fpbimport_allowed := false;
              lvnerrormsg       := gv_message || 'NO_DATA_FOUND weighingcategorycode: ' || x.weighingcategorycode;
              pack_import.write_log(lvnerrormsg, -3);
          end;
        else
          -- when not needed make fpnweighingcategory_id null.
          fpnweighingcategory_id := null;
        end if;
        if x.pricelisttype = 10 and x.specialcharge_id is null then
          begin
            --general special charge price, must have a valid special charge id linked
            fpbimport_allowed := false;
            lvnerrormsg       := gv_message || 'NO_DATA_FOUND Specialchargecode: ' ||
                                 nvl(x.specialchargecode, 'None specified') ||
                                 ', but it is needed for pricelisttype 10';
            pack_import.write_log(lvnerrormsg, -3);
          end;
        end if;
        if x.pricelisttype = 6 then
          begin
            --determine repair code if needed.
            select r.repairtype_id
            into   fpnrepairtype_id
            from   repairtype r
            where  r.code = x.repairtypecode;
          exception
            when no_data_found then
              fpbimport_allowed := false;
              lvnerrormsg       := gv_message || 'NO_DATA_FOUND repairtypecode: ' || x.repairtypecode;
              pack_import.write_log(lvnerrormsg, -3);
          end;
        else
          -- when not needed make repair code null.
          fpnrepairtype_id := null;
        end if;
        if x.chaincode is null then
          lv_chainid := null;
        else
          begin
            select ch.chain_id into lv_chainid from chain ch where ch.code = x.chaincode;
          exception
            when no_data_found then
              lv_chainid        := null;
              fpbimport_allowed := false;
              lvnerrormsg       := gv_message || 'NO_DATA_FOUND chain code: ' || x.chaincode;
              pack_import.write_log(lvnerrormsg, -3);
          end;
        end if;

        if fpbimport_allowed then
          begin
            -- start import for different price types.
            begin
              --get/create generalpricelist
              select g.generalpricelist_id
              into   fpngeneralpricelist_id
              from   generalpricelist g
              where  g.code = x.pricelistcode
              and    g.pricetype = x.pricelisttype;
            exception
              when no_data_found then
                begin
                  if nvl(x.volumeprice, 1) = 1 then
                    lv_volumeprice_yn := 'N';
                  else
                    lv_volumeprice_yn := 'Y';
                  end if;
                   --get_sizebillinggroup
                  lv_sizebillingroup_id := pack_import.get_sizebillinggroup(x.sizebillinggroupcode, null);
                  pack_import.cfbcreate_generalpricelist(fpngeneralpricelist_id,
                                                         --fpngeneralpricelist_id,
                                                         x.pricelisttype,
                                                         --fpnpricetype,
                                                         x.pricelistcode,
                                                         --fpscode,
                                                         x.pricelistdescription,
                                                         --fpsdescription,
                                                         'Y',
                                                         --fpsactive,
                                                         'Y',
                                                         --fpsautopriceupdate,
                                                         x.priceindexcode,
                                                         --fpspriceindexcode,
                                                         fpncurrency_id,
                                                         --fpncurrency_id,usage
                                                         0, lv_chainid, x.priceupdatelockdate,
                                                         lv_volumeprice_yn, x.defaultpricelist);
                end;
            end;
            --import the different pricetypes
            case x.pricelisttype
              when 1 then
                begin
                  -- Wash
                  pack_import.cfbcreate_generalwashprice(fpngeneralxxxprice_id,
                                                         --fpngeneralwashprice_id,
                                                         fpngeneralpricelist_id,
                                                         --fpngeneralpricelist_id,
                                                         x.product_id,
                                                         --fpnproduct_id,
                                                         x.sizedefinition_id,
                                                         --fpnsizedefinition_id,
                                                         fpnfinishingmethod_id,
                                                         --fpnfinishingmethod_id,
                                                         x.price,
                                                         --fpnprice,
                                                         x.startdateprice,
                                                         --fpdtstartdate,
                                                         x.washpricetype);
                end; -- End Wash
              when 2 then
                begin
                  -- Rent
                  if x.rentpricetype in (2, 4, 11) then
                    -- Check
                    if x.rentchangesperweek is null then
                      -- Check
                      fpbimport_allowed := false;
                      lvnerrormsg       := gv_message || 'rentchangesperweek is null for pricelisttype 2 and rentpricetype 2 or 4 or 11 and this is not allowed';
                      pack_import.write_log(lvnerrormsg, 3);
                    end if;
                  end if;
                  if x.rentpricetype is null then
                    -- Check
                    fpbimport_allowed := false;
                    lvnerrormsg       := gv_message || 'rentpricetype is null for pricelisttype 2 this is not allowed';
                    pack_import.write_log(lvnerrormsg, 3);
                  end if;
                  pack_import.cfbcreate_generalrentprice(fpngeneralxxxprice_id,
                                                         --fpngeneralrentprice_id,
                                                         fpngeneralpricelist_id,
                                                         --fpngeneralpricelist_id,
                                                         x.product_id,
                                                         --fpnproduct_id,
                                                         x.sizedefinition_id,
                                                         --fpnsizedefinition_id,
                                                         fpnfinishingmethod_id,
                                                         --fpnfinishingmethod_id,
                                                         x.price,
                                                         --fpnprice,
                                                         x.startdateprice,
                                                         --fpdtstartdate,
                                                         nvl(x.rentchangesperweek, 0),
                                                         --fpnchangesperweek,
                                                         x.rentpricetype,
                                                          --fpnsizebillinggroup_id
                                                         lv_sizebillingroup_id,
                                                         --fpntypeofrent,
                                                         x.maxinventory
                                                         );
                end; -- End Rent
              when 3 then
                begin
                  -- Replacement
                  pack_import.cfbcreate_genreplacementprice(fpngeneralxxxprice_id,
                                                            --fpngeneralreplacementprice_id,
                                                            fpngeneralpricelist_id,
                                                            --fpngeneralpricelist_id,
                                                            x.product_id,
                                                            --fpnproduct_id,
                                                            x.sizedefinition_id,
                                                            --fpnsizedefinition_id,
                                                            x.price,
                                                            --fpnprice,
                                                            x.startdateprice,
                                                            --fpdtstartdate,
                                                            lv_sizebillingroup_id
                                                            --fpnsizebillinggroup_id
                                                            );
                end; -- End Replacement
              when 4 then
                begin
                  -- Sales
                  pack_import.cfbcreate_generalsalesprice(fpngeneralxxxprice_id,
                                                          --fpngeneralsalesprice_id,
                                                          fpngeneralpricelist_id,
                                                          --fpngeneralpricelist_id,
                                                          x.product_id,
                                                          --fpnproduct_id,
                                                          x.sizedefinition_id,
                                                          --fpnsizedefinition_id,
                                                          x.price,
                                                          --fpnprice,
                                                          x.startdateprice,
                                                          --fpvolumeprice
                                                          x.volumeprice,
                                                          --fpnsizebillinggroup_id
                                                           lv_sizebillingroup_id);
                end; -- End Sales
              when 5 then
                begin
                  -- Weight
                  pack_import.cfbcreate_generalweightprice(fpngeneralxxxprice_id,
                                                           --fpngeneralweightprice_id,
                                                           fpngeneralpricelist_id,
                                                           --fpngeneralpricelist_id,
                                                           fpnweighingcategory_id,
                                                           --fpnweighingcategory_id,
                                                           'Y',
                                                           --fpssoil,
                                                           x.price,
                                                           --fpnprice,
                                                           x.startdateprice
                                                           --fpdtstartdate,
                                                           );
                end; -- End Weight
              when 6 then
                begin
                  -- Repair
                  pack_import.cfbcreate_generalrepairprice(fpngeneralxxxprice_id,
                                                           --fpngeneralrepairprice_id,
                                                           fpngeneralpricelist_id,
                                                           --fpngeneralpricelist_id,
                                                           fpnrepairtype_id,
                                                           --fpnrepairtype_id,
                                                           x.price,
                                                           --fpnprice,
                                                           x.startdateprice,
                                                           --fpdtstartdate,
                                                           nvl(x.priceperminute, 0)
                                                           --fpnpriceperminute,
                                                           );
                end; -- End Repair
              when 7 then
                begin
                  -- Emblem
                  pack_import.cfbcreate_generalemblemprice(fpngeneralxxxprice_id,
                                                           --fpngeneralemblemprice_id,
                                                           x.product_id,
                                                           --fpnproduct_id,
                                                           x.sizedefinition_id,
                                                           --fpnsizedefinition_id,
                                                           x.price,
                                                           --fpnprice,
                                                           x.startdateprice,
                                                           --fpdtstartdate,
                                                           fpngeneralpricelist_id
                                                           --fpngeneralpricelist_id,
                                                           );
                end; -- End Emblem
              when 8 then
                begin
                  -- Emblem template
                  pack_import.cfbcreate_generalemblemprice(fpngeneralxxxprice_id,
                                                           --fpngeneralemblemprice_id,
                                                           x.product_id,
                                                           --fpnproduct_id,
                                                           x.sizedefinition_id,
                                                           --fpnsizedefinition_id,
                                                           x.price,
                                                           --fpnprice,
                                                           x.startdateprice,
                                                           --fpdtstartdate,
                                                           fpngeneralpricelist_id
                                                           --fpngeneralpricelist_id,
                                                           );
                end; -- End Emblem template
              when 9 then
                if x.pricecomponent is not null then
                  begin
                    --9 = BudgetProtectionPrice
                    insert into generalbgprotectionprice
                      (generalbgprotectionprice_id, generalpricelist_id, product_id,
                       sizedefinition_id, pricecomponent, startdate, price, systemuser_id, timestamp)
                    values
                      (seq_generalbgprotectionprice.nextval, fpngeneralpricelist_id, x.product_id,
                       x.sizedefinition_id, x.pricecomponent, x.startdateprice, x.price,
                       pack_import.lvnsystemuserid, sysdate);
                  end;
                else
                  begin
                    --9 = Garment Insurance
                    insert into generalinsuranceprice
                      (generalinsuranceprice_id, generalpricelist_id, product_id, sizedefinition_id,
                       finishingmethod_id, price, startdate, systemuser_id, timestamp)
                    values
                      (seq_generalinsuranceprice.nextval, fpngeneralpricelist_id, x.product_id,
                       x.sizedefinition_id, fpnfinishingmethod_id, x.price, x.startdateprice,
                       pack_import.lvnsystemuserid, sysdate);
                  end;
                end if; --End 9 = Garment Insurance
              when 10 then
                --10=General Special Charge Price
                begin
                  insert into generalspecialchargeprice
                    (generalspecialchargeprice_id, generalpricelist_id, specialcharge_id, startdate,
                     price, percentage, minimumamount, maximumamount, systemuser_id, timestamp,
                     creationuser_id, creationtimestamp)
                  values
                    (seq_generalspecialchargeprice.nextval, fpngeneralpricelist_id,
                     x.specialcharge_id, x.startdateprice, x.price, x.percentage, null /*min.amount*/,
                     null /*max.amount*/, pack_import.lvnsystemuserid, sysdate,
                     pack_import.lvnsystemuserid, sysdate);
                end; --End 10 General Special Charge Price
              when 12 then
                begin
                  --Special Size Charge
                  insert into generalspecsizechargeprice
                    (generalspecsizechargeprice_id, generalpricelist_id, product_id,
                     sizedefinition_id, startdate, price, systemuser_id, timestamp)
                  values
                    (seq_generalspecsizechargeprice.nextval, fpngeneralpricelist_id, x.product_id,
                     x.sizedefinition_id, x.startdateprice, x.price, pack_import.lvnsystemuserid,
                     sysdate);
                end; --End 12  Special Size Charge
              else
                begin
                  lcounter := lcounter - 1;
                  pack_import.write_log('Unknown price type ' || to_char(x.pricelisttype) ||
                                        ' used, not imported!', 3);
                end;
            end case;
            lcounter := lcounter + 1;
          end;
        end if; -- import_allowed.
      exception
        when dup_val_on_index then
          null; --no problem already there..
      end;
    end loop;
    commit;
    if lcounter > 0 then
      begin
        pack_import.write_log(to_char(lcounter) || ' pricelist records added.');
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        lvnerrormsg := 'CFbImport_Pricelist: Fail to import.';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_pricelist;
  procedure cfbimport_pricelistpercustomer is
    fpnpricelistpercustomer_id pricelistpercustomer.pricelistpercustomer_id%type;
    lcounter                   number := 0;
  begin
    select count(1) into lcounter from i_pricelistpercustomer;
    if lcounter > 0 then
      begin
        pack_import.write_log(to_char(lcounter) ||
                              ' records in i_pricelistpercustomer to be converted.');
        lcounter := 0;
        --start conversion i_pricelistpercustomer
        for x in (select i.pricelistcode, i.pricelisttype, i.priority, i.startdate, c.customer_id,
                         g.generalpricelist_id, i.priceindexcode, i.priceupdatelockdate
                  from   i_pricelistpercustomer i
                  join   customer c
                  on     i.customernumber = c.customernumber
                  left   outer join generalpricelist g
                  on     (g.code = i.pricelistcode and g.pricetype = i.pricelisttype)
                  where  not exists (select plpc.pricelistpercustomer_id
                          from   pricelistpercustomer plpc
                          where  plpc.customer_id = c.customer_id
                          and    plpc.pricetype = i.pricelisttype
                          and    (plpc.generalpricelist_id = g.generalpricelist_id or
                                (plpc.generalpricelist_id is null and
                                g.generalpricelist_id is null)))
                  and    not exists (select plpc2.pricelistpercustomer_id
                          from   pricelistpercustomer plpc2
                          where  plpc2.customer_id = c.customer_id
                          and    plpc2.pricetype = i.pricelisttype
                          and    plpc2.priority = i.priority)) loop
          begin
            pack_import.cfbcreate_pricelistpercustomer(fpnpricelistpercustomer_id,
                                                       --fpnpricelistpercustomer_id,
                                                       x.customer_id,
                                                       --fpncustomer_id,
                                                       x.pricelisttype,
                                                       --fpnpricetype,
                                                       x.generalpricelist_id,
                                                       --fpngeneralpricelist_id,
                                                       x.priority,
                                                       --fpnpriority,
                                                       x.startdate,
                                                       --fpdtdateactive,
                                                       to_date('31-12-2099', 'DD-MM-YYYY'),
                                                       --fpdtdateinactive,
                                                       x.priceindexcode, x.priceupdatelockdate);
            lcounter := lcounter + 1;
          exception
            when dup_val_on_index then
              null;
          end;
        end loop;
        commit;
        pack_import.write_log(to_char(lcounter) || ' pricelistpercustomer records added.');
      end;
    end if;
    --imp_customerbgprotectionprice
    imp_customerbgprotectionprice;
    imp_customerimagecareprice;
  exception
    when others then
      begin
        rollback;
        lvnerrormsg := 'CFbImport_PricelistPerCustomer: Fail to import.';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_pricelistpercustomer;
  procedure cfbimport_specialchargepercust is
    fpnspecialcharge_id       specialcharge.specialcharge_id%type;
    lcounter                  number := 0;
    lcountprice               number := 0;
    lcountspecialchargesadded number := 0;
    procedure cfbcreatespecialcharge(fpnspecialcharge_id         in out specialcharge.specialcharge_id%type,
                                     fpnfrequency                in specialcharge.frequency%type,
                                     fpnspecialchargecode        in specialcharge.code%type,
                                     fpnspecialchargedescription in specialcharge_desc.description%type,
                                     fpdtstartdate               in specialcharge.startdate%type,
                                     fpnspecialchargeamount      in specialcharge.newamount%type,
                                     fpnspecialchargepercentage  in specialcharge.newpercentage%type,
                                     fpminamount                 in specialcharge.minimumamount%type,
                                     fpmaxamount                 in specialcharge.maximumamount%type) is
      fpsfixedamount varchar2(1);
    begin
      select s.specialcharge_id
      into   fpnspecialcharge_id
      from   specialcharge s
      where  s.code = fpnspecialchargecode;
    exception
      -- when does not already exist create it.
      when no_data_found then
        begin
          if fpnspecialchargeamount is null then
            fpsfixedamount := 'N';
          else
            fpsfixedamount := 'Y';
          end if;
          -- special charge does not exist so create it.
          pack_import.cfbcreate_specialcharge(fpnspecialcharge_id,
                                              --fpnspecialcharge_id,
                                              fpnfrequency,
                                              --fpnfrequency,
                                              'N',
                                              --fpsincludininvoiceminimum,
                                              fpdtstartdate,
                                              --fpdtstartdate,
                                              nvl(fpnspecialchargepercentage, 0),
                                              --fpnnewpercentage,
                                              0,
                                              --fpnoldpercentage,
                                              nvl(fpnspecialchargeamount, 0),
                                              --fpnnewamount,
                                              0,
                                              --fpnoldamount,
                                              fpsfixedamount,
                                              --fpsfixedamount,
                                              fpnspecialchargecode,
                                              --fpscode,
                                              null,
                                              --fpnturnovergroup_id,
                                              fpminamount, fpmaxamount);
          pack_import.cfbcreate_specialcharge_desc(fpnspecialcharge_id,
                                                   --fpnspecialcharge_id,
                                                   fpnspecialchargedescription
                                                   --fpsdescription,
                                                   );
          lcountspecialchargesadded := lcountspecialchargesadded + 1;
          commit;
        exception
          when others then
            begin
              rollback;
              fpnspecialcharge_id := null;
              lvnerrormsg         := 'CFbCreateSpecialCharge, failed to create:' ||
                                     fpnspecialchargecode || ' ';
              pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
            end;
        end;
      when others then
        begin
          rollback;
          fpnspecialcharge_id := null;
          lvnerrormsg         := 'CFbCreateSpecialCharge, failed to select:' ||
                                 fpnspecialchargecode || ' ';
          pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
        end;
    end cfbcreatespecialcharge;
  begin
    for x in (select c.customer_id, i.specialchargecode, i.specialchargedescription,
                     i.specialchargeamount, i.specialchargepercentage, i.startdate, i.frequency,
                     i.minimumamount, i.maximumamount, i.overruled, c.dateinactive
              from   i_specialchargespercustomer i, customer c
              where  i.customernumber = c.customernumber
              and    not exists (select 1
                      from   customerspecialchargeprice csc
                      join   specialcharge sc
                      on     sc.specialcharge_id = csc.specialcharge_id
                      where  csc.customer_id = c.customer_id
                      and    sc.code = i.specialchargecode
                      and    csc.startdate = i.startdate)) loop
      begin
        cfbcreatespecialcharge(fpnspecialcharge_id,
                               --fpnspecialcharge_id,
                               x.frequency,
                               --fpnfrequency,
                               x.specialchargecode,
                               --fpnspecialchargecode,
                               x.specialchargedescription,
                               --fpnspecialchargedescription,
                               x.startdate,
                               --fpdtstartdate,
                               x.specialchargeamount,
                               --fpnspecialchargeamount,
                               x.specialchargepercentage,
                               --fpnspecialchargepercentage,
                               x.minimumamount, x.maximumamount);
        if fpnspecialcharge_id is not null then
          --only when special charge is found.
          begin
            pack_import.cfbcreate_custspecialcharge(x.customer_id,
                                                    --fpncustomer_id,
                                                    fpnspecialcharge_id);
            --overrulled percentage..
            if x.overruled = 'Y' then
              begin
                insert into customerspecialchargeprice
                  (customerspecialchargeprice_id, customer_id, specialcharge_id, startdate, price,
                   percentage, minimumamount, maximumamount, systemuser_id, timestamp)
                values
                  (seq_customerspecialchargeprice.nextval, x.customer_id, fpnspecialcharge_id,
                   x.startdate, x.specialchargeamount, x.specialchargepercentage, x.minimumamount,
                   x.maximumamount, pack_import.lvnsystemuserid, sysdate);
                begin
                  insert into pricelistpercustomer
                    (pricelistpercustomer_id, customer_id, pricetype, priority, generalpricelist_id,
                     dateactive, dateinactive, systemuser_id, timestamp)
                  values
                    (seq_pricelistpercustomer.nextval, x.customer_id, 10, 1, null, x.startdate,
                     x.dateinactive, pack_import.lvnsystemuserid, sysdate);
                exception
                  when dup_val_on_index then
                    null; --already exists no problem
                end;
                commit;
                lcountprice := lcountprice + 1;
              end;
            end if;
            commit;
            lcounter := lcounter + 1;
          exception
            when dup_val_on_index then
              null; -- does not matter did already exist.
          end;
        end if;
      end;
    end loop;
    commit;
    if lcountspecialchargesadded > 0 then
      pack_import.write_log(to_char(lcountspecialchargesadded) || ' specialcharge records added');
    end if;
    if lcounter > 0 then
      pack_import.write_log(to_char(lcounter) || ' customer specialcharge added');
    end if;
    if lcountprice > 0 then
      pack_import.write_log(to_char(lcountprice) || ' customer specialcharge prices records added');
    end if;
  exception
    when others then
      begin
        rollback;
        lvnerrormsg := 'CFbImport_SpecialChargePerCust: Fail to import.';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_specialchargepercust;
  procedure cfbimport_specialchargeperprod is
    lcounter number := 0;
  begin
    for x in (select s.specialcharge_id, p.product_id, f.finishingmethod_id
              from   i_specialchargeperproduct i, product p, finishingmethod f, specialcharge s
              where  f.code = trim(i.finishingmethodcode)
              and    p.code = trim(i.productcode)
              and    s.code = trim(i.specialchargecode)
              and    not exists (select *
                      from   productfinishingmethodcharge o
                      where  o.specialcharge_id = s.specialcharge_id
                      and    o.finishingmethod_id = f.finishingmethod_id
                      and    o.product_id = p.product_id)) loop
      begin
        --make sure productfinishingmethod exists.
        pack_import.cfbcreate_prodfinishingmethod(x.product_id, x.finishingmethod_id);
        insert into productfinishingmethodcharge
          (specialcharge_id, timestamp, systemuser_id, product_id, finishingmethod_id)
        values
          (x.specialcharge_id, sysdate, pack_import.lvnsystemuserid, x.product_id,
           x.finishingmethod_id);
        lcounter := lcounter + 1;
      exception
        when dup_val_on_index then
          null; -- does not matter did already exist.
      end;
    end loop;
    commit;
    if lcounter > 0 then
      pack_import.write_log(to_char(lcounter) || ' specialcharge per product added.');
    end if;
  exception
    when others then
      begin
        rollback;
        lvnerrormsg := 'CFbImport_SpecialChargePerProd: Fail to import.';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_specialchargeperprod;
  procedure cfbimport_freqrelatedprices is
    fpncustomerrentprice_id      customerrentprice.customerrentprice_id%type;
    fpnproductlistpercustomer_id productlistpercustomer.productlistpercustomer_id%type;
    fpncustomerid                customer.customer_id%type;
    fpdcustomerdateactive        customer.dateactive%type;
    fpdcustomerdateinactive      customer.dateinactive%type;
    pricelistpercustomerid       pricelistpercustomer.pricelistpercustomer_id%type;
    lcounter                     number := 0;
  begin
    commit;
    for x in (select * from i_frequencyrelatedrentprices) loop
      begin
        -- determin plpc.
        select min(l.productlistpercustomer_id), min(l.customer_id), min(c.dateactive),
               max(c.dateinactive)
        into   fpnproductlistpercustomer_id, fpncustomerid, fpdcustomerdateactive,
               fpdcustomerdateinactive
        from   productlistpercustomer l, product p, sizedefinition s, finishingmethod f, customer c
        where  l.product_id = p.product_id
        and    p.code = trim(x.productcode)
        and    l.sizedefinition_id = s.sizedefinition_id
        and    s.code = trim(x.sizecode)
        and    l.finishingmethod_id = f.finishingmethod_id
        and    f.code = trim(x.finishingmethodcode)
        and    l.customer_id = c.customer_id
        and    c.customernumber = x.customernumber
        and    x.startdate between l.dateactive and l.dateinactive;
        if fpnproductlistpercustomer_id is not null then
          begin
            -- insert pricelistpercustomer if needed
            pack_import.cfbcreate_pricelistpercustomer(pricelistpercustomerid, fpncustomerid, 2,
                                                       null, null, fpdcustomerdateactive,
                                                       fpdcustomerdateinactive, null, null, 1);
            begin
              -- insert customer rent price
              pack_import.cfbcreate_customerrentprice(fpncustomerrentprice_id,
                                                      --fpncustomerrentprice_id,
                                                      fpnproductlistpercustomer_id,
                                                      --fpnproductlistpercustomer_id,
                                                      x.price,
                                                      --fpnprice,
                                                      x.startdate,
                                                      --fpdtstartdate,
                                                      x.frequency,
                                                      --fpnchangesperweek,
                                                      4,
                                                      --fpntypeofrent,
                                                      x.contractcoefficient);
              lcounter := lcounter + 1;
              update productlistpercustomer l
              set    l.rentpriceperfrequency = 'Y'
              where  l.productlistpercustomer_id = fpnproductlistpercustomer_id
              and    l.rentpriceperfrequency <> 'Y';
            exception
              when dup_val_on_index then
                null;
            end;
          end;
        else
          pack_import.write_log(' Missing PLPC,not imported freq.rel.price for cust: ' ||
                                to_char(x.customernumber) || ' product: ' || x.productcode || '!', 2);
        end if;
      end;
    end loop;
    commit;
    if lcounter > 0 then
      pack_import.write_log(to_char(lcounter) || ' frequency related prices added.');
    end if;
  exception
    when others then
      begin
        rollback;
        lvnerrormsg := 'cfbimport_frequencyrelatedprices: Fail to import.';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_freqrelatedprices;
  procedure cfbimport_changespwrentprices is
    fpncustomerrentprice_id      customerrentprice.customerrentprice_id%type;
    fpnproductlistpercustomer_id productlistpercustomer.productlistpercustomer_id%type;
    fpncustomerid                customer.customer_id%type;
    fpdcustomerdateactive        customer.dateactive%type;
    fpdcustomerdateinactive      customer.dateinactive%type;
    pricelistpercustomerid       pricelistpercustomer.pricelistpercustomer_id%type;
    lcounter                     number := 0;
    lv_sizebillingroup_id        sizebillinggroup.sizebillinggroup_id%type;
  begin
    for x in (select * from i_changesperweekrentprice) loop
      begin
        -- determin plpc.
        select min(l.productlistpercustomer_id), min(l.customer_id), min(c.dateactive),
               max(c.dateinactive)
        into   fpnproductlistpercustomer_id, fpncustomerid, fpdcustomerdateactive,
               fpdcustomerdateinactive
        from   productlistpercustomer l, product p, sizedefinition s, finishingmethod f, customer c
        where  l.product_id = p.product_id
        and    p.code = trim(x.productcode)
        and    l.sizedefinition_id = s.sizedefinition_id
        and    s.code = trim(x.sizecode)
        and    l.finishingmethod_id = f.finishingmethod_id
        and    f.code = trim(x.finishingmethodcode)
        and    l.customer_id = c.customer_id
        and    c.customernumber = x.customernumber
        and    x.startdate between l.dateactive and l.dateinactive;
        if fpnproductlistpercustomer_id is not null then
          begin
            -- insert pricelistpercustomer if needed
            pack_import.cfbcreate_pricelistpercustomer(pricelistpercustomerid, fpncustomerid, 2,
                                                       null, null, fpdcustomerdateactive,
                                                       fpdcustomerdateinactive, null, null, 1);
            begin
               --get_sizebillinggroup
             lv_sizebillingroup_id := pack_import.get_sizebillinggroup(x.sizebillinggroupcode, null);
              -- insert customer rent price
              pack_import.cfbcreate_customerrentprice(fpncustomerrentprice_id,
                                                      --fpncustomerrentprice_id,
                                                      fpnproductlistpercustomer_id,
                                                      --fpnproductlistpercustomer_id,
                                                      x.price,
                                                      --fpnprice,
                                                      x.startdate,
                                                      --fpdtstartdate,
                                                      x.changes,
                                                      --fpnchangesperweek,
                                                      2,
                                                      --fpntypeofrent,
                                                      x.contractcoefficient,
                                                      x.maxinventory,
                                                      lv_sizebillingroup_id);
              lcounter := lcounter + 1;
            exception
              when dup_val_on_index then
                null;
            end;
          end;
        else
          begin
            pack_import.write_log(' Missing PLPC,changespwrentprices for cust: ' ||
                                  to_char(x.customernumber) || ' product: ' || x.productcode || '!',
                                  2);
          end;
        end if;
      end;
    end loop;
    commit;
    if lcounter > 0 then
      pack_import.write_log(to_char(lcounter) || ' changes per week rent prices added.');
    end if;
  exception
    when others then
      begin
        rollback;
        lvnerrormsg := 'cfbimport_changespwrentprices: Fail to import.';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_changespwrentprices;
  procedure imp_customerimagecareprice is
    lvcounter        number := 0;
    customerid       customer.customer_id%type;
    productid        product.product_id%type;
    sizedefinitionid sizedefinition.sizedefinition_id%type;
  begin
    for x in (select * from i_customerimagecareprice) loop
      begin
        select c.customer_id
        into   customerid
        from   customer c
        where  c.customernumber = x.customernumber;
        select p.product_id into productid from product p where p.code = x.productcode;
        select s.sizedefinition_id
        into   sizedefinitionid
        from   sizedefinition s
        where  s.code = x.sizecode;
        --insert into customerbgprotectionprice
        insert into customerimagecareprice
          (customerimagecareprice_id, customer_id, product_id, sizedefinition_id, startdate, price,
           systemuser_id, timestamp)
        values
          (seq_customerimagecareprice.nextval, customerid, productid, sizedefinitionid, x.startdate,
           x.price, pack_import.lvnsystemuserid, sysdate);
        --count rows inserted
        lvcounter := lvcounter + 1;
      exception
        when dup_val_on_index then
          null; --no problem if it is already there
      end;
    end loop;
    commit;
    if lvcounter > 0 then
      pack_import.write_log(lvcounter || ' Customer ImageCare Prices imported.');
    end if;
  exception
    when others then
      begin
        rollback;
        lvnerrormsg := 'imp_customerimagecareprice: Fail to import.';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end imp_customerimagecareprice;
  procedure imp_priceindex is
    lv_counter  number := 0;
    lv_counter1 number := 0;
  begin
    --import priceindex
       lvnerrormsg := 'pack_import_pricestructure.imp_priceindex start';
       insert into priceindex
       (priceindex_id, code, description, systemuser_id, timestamp)
        select seq_priceindex.nextval, x.code, x.description, pack_import.lvnsystemuserid, sysdate
           from  (select i.priceindexcode code,
                     max(i.description) description
               from   i_priceindex i
               group  by i.priceindexcode) x
      where  not exists (select p.priceindex_id from priceindex p where p.code = x.code);
      lv_counter:= sql%rowcount;
      insert into priceindexhistory
                  (priceindex_id,startdate,percwashlog,percwashcog,percrent,percsales,percreplace,percweight,
                   percemblem,percrepair,percinsurance,percspecialcharge,percwearer,percwearerinv,percspecialsizecharge,systemuser_id,timestamp)
                   select x.priceindex_id,x.startdate,x.percwashlog,x.percwashcog,x.percrent,x.percsales,x.percreplace,x.percweight,
                   x.percemblem,x.percrepair,x.percinsurance,x.percspecialcharge,x.percwearer,x.percwearerinv,x.percspecialsizecharge,pack_import.lvnsystemuserid,sysdate
                   from (
                   select p.priceindex_id priceindex_id, i.startdate startdate,max(i.percwashlog) percwashlog,max(i.percwashcog) percwashcog,max(i.percrent) percrent,
                   max(i.percsales) percsales,max(i.percreplace) percreplace,
                   max(i.percweight) percweight,max(i.percemblem) percemblem,max(i.percrepair) percrepair,max(i.percinsurance) percinsurance,max(i.percspecialcharge) percspecialcharge,
                   max(i.percwearer) percwearer,max(i.percwearerinv) percwearerinv,max(i.percspecialsizecharge)percspecialsizecharge
                   from   i_priceindex i join priceindex p
                   on i.priceindexcode = p.code
                   group by p.priceindex_id,i.startdate
                   )x
                   where not exists(select pih.priceindex_id from priceindexhistory pih where pih.priceindex_id = x.priceindex_id and pih.startdate = x.startdate);
         lv_counter1:= sql%rowcount;
         if lv_counter > 0 then
      begin
        commit;
        pack_import.write_log(lv_counter || ' price index rows imported.');
        pack_import.write_log(lv_counter1 || ' price index history rows imported.');
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        lvnerrormsg := 'pack_import_pricestructure.imp_priceindex: Fail to import.';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end imp_priceindex;
  procedure import_customerexchangecharge is
    lv_countrows integer := 0;
  begin
    --import_customerexchangecharge
    insert into customerexchangecharge
      (customerexchangecharge_id, customer_id, startdate, price, systemuser_id, timestamp)
      select seq_customerexchangecharge.nextval, c.customer_id, ic.startdate, ic.price,
             pack_import.lvnsystemuserid, sysdate
      from   i_customercharges ic
      join   customer c
      on     c.customernumber = ic.customernumber
      where  ic.chargetype = 1 --1=Exchange Charge
      and    not exists (select 1
              from   customerexchangecharge cx
              where  cx.customer_id = c.customer_id
              and    cx.startdate = ic.startdate);
    lv_countrows := sql%rowcount;
    if lv_countrows > 0 then
      begin
        commit;
        pack_import.write_log(lv_countrows || ' Customer Exchange Charges imported');
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        lvnerrormsg := 'import_customerexchangecharge: Fail to import.';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end import_customerexchangecharge;
  procedure import_customercashdelay is
    lv_countrows integer := 0;
  begin
    --import_customercashdelay
    insert into customercashdelaycharge
      (customercashdelaycharge_id, customer_id, startdate, price, systemuser_id, timestamp)
      select seq_customercashdelaycharge.nextval, c.customer_id, ic.startdate, ic.price,
             pack_import.lvnsystemuserid, sysdate
      from   i_customercharges ic
      join   customer c
      on     c.customernumber = ic.customernumber
      where  ic.chargetype = 2 --2=Cash Delay Charge
      and    not exists (select 1
              from   customercashdelaycharge cx
              where  cx.customer_id = c.customer_id
              and    cx.startdate = ic.startdate);
    lv_countrows := sql%rowcount;
    if lv_countrows > 0 then
      begin
        commit;
        pack_import.write_log(lv_countrows || ' Customer Cash Delay Charges imported');
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        lvnerrormsg := 'import_customercashdelay: Fail to import.';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end import_customercashdelay;
  procedure cfbimport_customercharges is
  begin
    --cfbimport_customercharges
    /* i_customercharges.chargetype
    0=Stock Charge
    1=Exchange Charge
    2=Cash Delay Charge */
    import_customerexchangecharge;
    import_customercashdelay;
  end cfbimport_customercharges;
  procedure cfbimport_customerstockcharge is
    countrows  integer := 0;
    customerid customer.customer_id%type;
  begin
    for x in (select * from i_customerstockcharge) loop
      begin
        -- get customer_id
        select c.customer_id
        into   customerid
        from   customer c
        where  c.customernumber = x.customernumber;
        --insert data
        insert into customerstockcharge
          (customerstockcharge_id, customer_id, price, startdate, systemuser_id, timestamp)
        values
          (seq_customerstockcharge.nextval,customerid , x.price, x.startdate, pack_import.lvnsystemuserid,
           sysdate);
        commit;
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when no_data_found then
          pack_import.write_log(' cfbimport_customerstockcharge, error missing customer: ' ||
                                to_char(x.customernumber) || '!', -3);
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(to_char(countrows) || ' customerstockcharge records added.');
    end if;
  exception
    when others then
      begin
        rollback;
        lvnerrormsg := 'cfbimport_customerstockcharge: Fail to import.';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_customerstockcharge;
  procedure imp_customerbgprotectionprice is
    lvcounter               number := 0;
    lsizeid                 sizedefinition.sizedefinition_id%type;
    lpricelistpercustomerid pricelistpercustomer.pricelistpercustomer_id%type;
  begin
    --imp_customerbgprotectionprice
    lvnerrormsg := 'pack_import_pricestructure.imp_customerbgprotectionprice start';
    for pp in (select c.customer_id, p.product_id, bp.sizecode, bp.pricecomponent, bp.startdate,
                      bp.price
               from   i_customerbgprotectionprice bp
               join   customer c
               on     c.customernumber = bp.customernumber
               join   product p
               on     p.code = bp.productcode) loop
      begin
        begin
          --size
          lvnerrormsg := ' size ' || pp.sizecode;
          select s.sizedefinition_id into lsizeid from sizedefinition s where s.code = pp.sizecode;
        exception
          when no_data_found then
            begin
              pack_import.cfbcreate_sizedefinition(lsizeid, pp.sizecode, 'N', null, null, null, 'Y');
              pack_import.cfbcreate_sizedefinition_desc(lsizeid, pp.sizecode);
            end;
        end;
        -- insert pricelistpercustomer if needed
        pack_import.cfbcreate_pricelistpercustomer(lpricelistpercustomerid, pp.customer_id, 9, null,
                                                   null, pp.startdate, null, null, null, 1);
        --insert into customerbgprotectionprice
        insert into customerbgprotectionprice
          (customerbgprotectionprice_id, customer_id, product_id, sizedefinition_id, pricecomponent,
           startdate, price, systemuser_id, timestamp)
        values
          (seq_customerbgprotectionprice.nextval, pp.customer_id, pp.product_id, lsizeid,
           pp.pricecomponent, pp.startdate, pp.price, pack_import.lvnsystemuserid, sysdate);
        --count rows inserted
        lvcounter := lvcounter + 1;
      exception
        when dup_val_on_index then
          null; --no problem if it is already there
      end;
    end loop; --pp
    commit;
    if lvcounter > 0 then
      pack_import.write_log(lvcounter || ' Customer Budget Protection Prices imported.');
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('imp_customerbgprotectionprice: Failed to import ' ||
                              substr(sqlerrm, 1, 512), 3);
      end;
  end imp_customerbgprotectionprice;
  procedure cfbimport_costpricelist is
    lprocessedcount      integer := 0;
    lerrorcount          integer := 0;
    lv_currencyid        currency.currency_id%type;
    lv_procbu            businessunit.businessunit_id%type;
    lv_internalbu        businessunit.businessunit_id%type;
    lv_invoicebu         businessunit.businessunit_id%type;
    lv_productid         product.product_id%type;
    lv_sizeid            sizedefinition.sizedefinition_id%type;
    lv_finishingmethodid finishingmethod.finishingmethod_id%type;
    lv_costpricelistid   costpricelist.costpricelist_id%type;
  begin
    --cfbimport_costpricelist
    lvnerrormsg := 'pack_import_pricestructure.cfbimport_costpricelist start';
    for cpl in (select * from i_costpricelist i) loop
      begin
        --currency
        lvnerrormsg := 'currency code ' || cpl.currencycode;
        select cu.currency_id into lv_currencyid from currency cu where cu.code = cpl.currencycode;
        --processbu
        if cpl.processbusinessunit is null then
          lv_procbu := null;
        else
          begin
            lvnerrormsg := 'processing businessunit code ' || cpl.processbusinessunit;
            select bu.businessunit_id
            into   lv_procbu
            from   businessunit bu
            where  bu.code = cpl.processbusinessunit;
          end;
        end if;
        --internalbu
        if cpl.internalprocessingbu is null then
          lv_internalbu := null;
        else
          begin
            lvnerrormsg := 'internal proc. businessunit code ' || cpl.internalprocessingbu;
            select bu.businessunit_id
            into   lv_internalbu
            from   businessunit bu
            where  bu.code = cpl.internalprocessingbu;
          end;
        end if;
        --invoice bu
        if cpl.invoicebusinessunit is null then
          lv_invoicebu := null;
        else
          begin
            lvnerrormsg := 'invoice proc. businessunit code ' || cpl.invoicebusinessunit;
            select bu.businessunit_id
            into   lv_invoicebu
            from   businessunit bu
            where  bu.code = cpl.invoicebusinessunit;
          end;
        end if;
        --product
        lvnerrormsg := 'product code ' || cpl.productcode;
        select p.product_id into lv_productid from product p where p.code = cpl.productcode;
        --size
        lvnerrormsg := 'size code ' || cpl.sizecode;
        select s.sizedefinition_id
        into   lv_sizeid
        from   sizedefinition s
        where  s.code = cpl.sizecode;
        --finishingmethod
        lvnerrormsg := 'finishingmethod ' || cpl.finishingmethod;
        select f.finishingmethod_id
        into   lv_finishingmethodid
        from   finishingmethod f
        where  f.code = cpl.finishingmethod;
        --costpricelist
        begin
          select costp.costpricelist_id
          into   lv_costpricelistid
          from   costpricelist costp
          where  costp.code = cpl.costpricelistcode
          and    costp.pricetype = cpl.costpricelisttype
          and    costp.servicetype = cpl.servicetype;
        exception
          when no_data_found then
            begin
              insert into costpricelist
                (costpricelist_id, code, description, active, pricetype, currency_id, systemuser_id,
                 timestamp, servicetype, processbusinessunit_id, internalprocessingbu_id,
                 invoicebusinessunit_id)
              values
                (seq_costpricelist.nextval, cpl.costpricelistcode, cpl.description, cpl.active,
                 cpl.costpricelisttype, lv_currencyid, pack_import.lvnsystemuserid, sysdate,
                 cpl.servicetype, coalesce(lv_procbu, lv_internalbu, lv_invoicebu),
                 coalesce(lv_internalbu, lv_procbu, lv_invoicebu),
                 coalesce(lv_invoicebu, lv_procbu, lv_internalbu))
              returning costpricelist_id into lv_costpricelistid;
            end;
        end;
        --costpricelistdetail
        begin
          insert into costpricelistdetail
            (costpricelistdetail_id, costpricelist_id, sizedefinition_id, finishingmethod_id,
             product_id, price, startdate, systemuser_id, timestamp, depreciationpercentagestock,
             depreciationstartweek, depreciationpercentagepool, pricetype)
          values
            (seq_costpricelistdetail.nextval, lv_costpricelistid, lv_sizeid, lv_finishingmethodid,
             lv_productid, cpl.price, cpl.startdate, pack_import.lvnsystemuserid, sysdate,
             nvl(cpl.depreciationpercentagestock, 0), nvl(cpl.depreciationstartweek, 0),
             nvl(cpl.depreciationpercentagepool, 0), cpl.costpricelistdetailtype);
          lprocessedcount := lprocessedcount + 1;
        exception
          when dup_val_on_index then
            null; --already exists no problem
        end;
      exception
        when no_data_found then
          begin
            lerrorcount := lerrorcount + 1;
            pack_import.write_log('pack_import_pricestructure.cfbimport_costpricelist ' ||
                                  lvnerrormsg || ' not found', 3);
          end;
      end;
    end loop; --cpl
  exception
    when others then
      begin
        rollback;
        lvnerrormsg := 'pack_import_pricestructure.cfbimport_costpricelist: Fail to import.';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_costpricelist;
  procedure import_chargespecialsize_price is
    lv_sizespecialchargeoptions systemsetting.value%type;
    lv_counter                  number;
    lv_sizestarid               sizedefinition.sizedefinition_id%type;
    procedure intialize is
    begin
      --1 setting for all plants the same.. really not something on plant level only.
      /*
      0 - no special prices are used
      1 - special prices for Rent
      2 - special prices for Sales
      3 - special prices for Replacement
      4 - special prices for Rent and Sales
      5 - special prices for Rent and Replacement
      6 - special prices for Sales and Replacement
      7 - special prices for Rent, Sales and Replacement
      */
      lvnerrormsg := 'get system setting value for SIZESPECIALCHARGEOPTIONS';
      select nvl(max(trim(st.value)), '0')
      into   lv_sizespecialchargeoptions
      from   systemsetting st
      where  st.name = 'SIZESPECIALCHARGEOPTIONS';
      --get size star
      lvnerrormsg := 'Size *';
      select s.sizedefinition_id into lv_sizestarid from sizedefinition s where s.code = '*';
    end intialize;
    procedure copy_rent_chargeprices is
      procedure copy_generalrent_sbg is
      begin
        --copy_generalrent_sbg
        --GENERALPRICELIST_ID, PRODUCT_ID, SIZEDEFINITION_ID, FINISHINGMETHOD_ID, TYPEOFRENT,
        --STARTDATE, CHANGESPERWEEK, INVOICEFREQUENCYNUMBER, SIZEBILLINGGROUP_ID
        lvnerrormsg := 'copy_rent_chargeprices.copy_generalrent_sbg';
        insert into generalrentprice
          (generalrentprice_id, generalpricelist_id, product_id, sizedefinition_id,
           finishingmethod_id, timestamp, systemuser_id, price, startdate, changesperweek,
           typeofrent, invoicefrequencynumber, ratificationstartdate, creationuser_id,
           creationtimestamp, ratificationuser_id, ratificationtimestamp, sizebillinggroup_id)
          select seq_generalrentprice.nextval, grp.generalpricelist_id, grp.product_id,
                 grp.sizedefinition_id, grp.finishingmethod_id, sysdate, pack_import.lvnsystemuserid,
                 case
                   when (p.typeofmerchandise = 2 and grp.sizedefinition_id = lv_sizestarid and
                        sbg.surchargepercentage > 0) then
                    grp.price * (1 + (sbg.surchargepercentage / 100))
                   else
                    grp.price
                 end, grp.startdate, grp.changesperweek, grp.typeofrent, grp.invoicefrequencynumber,
                 grp.ratificationstartdate, pack_import.lvnsystemuserid, sysdate,
                 grp.ratificationuser_id, grp.ratificationtimestamp, sbg.sizebillinggroup_id
          from   generalrentprice grp
          join   product p
          on     p.product_id = grp.product_id
          join   sizebillgroupperprodgroup sbg
          on     sbg.productgroup_id = p.productgroup_id
          where  grp.sizebillinggroup_id is null
          and    not exists (select 1
                  from   generalrentprice grbg
                  where  grbg.generalpricelist_id = grp.generalpricelist_id
                  and    grbg.product_id = grp.product_id
                  and    grbg.sizedefinition_id = grp.sizedefinition_id
                  and    grbg.finishingmethod_id = grp.finishingmethod_id
                  and    grbg.typeofrent = grp.typeofrent
                  and    grbg.startdate = grp.startdate
                  and    grbg.changesperweek = grp.changesperweek
                  and    grbg.invoicefrequencynumber = grp.invoicefrequencynumber
                  and    grbg.sizebillinggroup_id = sbg.sizebillinggroup_id);
        --count inserted rows
        lv_counter := sql%rowcount;
        if lv_counter > 0 then
          begin
            --commit and write log
            commit;
            pack_import.write_log('Copied ' || lv_counter ||
                                  ' generalrentprice for size billing groups.' ||
                                  'System setting SIZESPECIALCHARGEOPTIONS ' ||
                                  lv_sizespecialchargeoptions, 1);
          end;
        end if;
      end copy_generalrent_sbg;
      procedure copy_customerrent_sbg is
      begin
        --copy_customerrent_sbg
        --PRODUCTLISTPERCUSTOMER_ID, STARTDATE, CHANGESPERWEEK,
        --TYPEOFRENT, INVOICEFREQUENCYNUMBER, SIZEBILLINGGROUP_ID
        lvnerrormsg := 'copy_rent_chargeprices.copy_customerrent_sbg';
        insert into customerrentprice
          (customerrentprice_id, productlistpercustomer_id, timestamp, systemuser_id, price,
           startdate, changesperweek, typeofrent, invoicefrequencynumber, ratificationstartdate,
           creationuser_id, creationtimestamp, ratificationuser_id, ratificationtimestamp,
           contractcoefficient, sizebillinggroup_id)
          select seq_customerrentprice.nextval, crp.productlistpercustomer_id, sysdate,
                 pack_import.lvnsystemuserid,
                 case
                   when (p.typeofmerchandise = 2 and l.sizedefinition_id = lv_sizestarid and
                        sbg.surchargepercentage > 0) then
                    crp.price * (1 + (sbg.surchargepercentage / 100))
                   else
                    crp.price
                 end, crp.startdate, crp.changesperweek, crp.typeofrent, crp.invoicefrequencynumber,
                 crp.ratificationstartdate, pack_import.lvnsystemuserid, sysdate,
                 crp.ratificationuser_id, crp.ratificationtimestamp, crp.contractcoefficient,
                 sbg.sizebillinggroup_id
          from   customerrentprice crp
          join   productlistpercustomer l
          on     l.productlistpercustomer_id = crp.productlistpercustomer_id
          join   product p
          on     p.product_id = l.product_id
          join   sizebillgroupperprodgroup sbg
          on     sbg.productgroup_id = p.productgroup_id
          join   customer c
          on     c.customer_id = l.customer_id
          where  c.useprodsizesurchargepricing = 'Y'
          and    crp.sizebillinggroup_id is null
          and    not exists
           (select 1
                  from   customerrentprice crbg
                  where  crbg.productlistpercustomer_id = crp.productlistpercustomer_id
                  and    crbg.startdate = crp.startdate
                  and    crbg.changesperweek = crp.changesperweek
                  and    crbg.typeofrent = crp.typeofrent
                  and    crbg.invoicefrequencynumber = crp.invoicefrequencynumber
                  and    crbg.sizebillinggroup_id = sbg.sizebillinggroup_id);
        --count inserted rows
        lv_counter := sql%rowcount;
        if lv_counter > 0 then
          begin
            --commit and write log
            commit;
            pack_import.write_log('Copied ' || lv_counter ||
                                  ' customerrentprice for size billing groups.' ||
                                  'System setting SIZESPECIALCHARGEOPTIONS ' ||
                                  lv_sizespecialchargeoptions, 1);
          end;
        end if;
      end copy_customerrent_sbg;
    begin
      --copy_rent_chargeprices
      lvnerrormsg := 'copy_rent_chargeprices';
      --copy_generalrent_sbg
      copy_generalrent_sbg;
      --copy_customerrent_sbg
      copy_customerrent_sbg;
    end copy_rent_chargeprices;
    procedure copy_sales_chargeprices is
      procedure copy_generalsales_sbg is
      begin
        --copy_sales_chargeprices
        --GENERALPRICELIST_ID, PRODUCT_ID, SIZEDEFINITION_ID, STARTDATE,
        --VOLUMEPRICE, SIZEBILLINGGROUP_ID
        lvnerrormsg := 'copy_sales_chargeprices';
        insert into generalsalesprice
          (generalsalesprice_id, generalpricelist_id, product_id, sizedefinition_id, timestamp,
           systemuser_id, price, startdate, volumeprice, ratificationstartdate, creationuser_id,
           creationtimestamp, ratificationuser_id, ratificationtimestamp, sizebillinggroup_id)
          select seq_generalsalesprice.nextval, gsp.generalpricelist_id, gsp.product_id,
                 gsp.sizedefinition_id, sysdate, pack_import.lvnsystemuserid,
                 case
                   when (p.typeofmerchandise = 2 and gsp.sizedefinition_id = lv_sizestarid and
                        sbg.surchargepercentage > 0) then
                    gsp.price * (1 + (sbg.surchargepercentage / 100))
                   else
                    gsp.price
                 end, gsp.startdate, gsp.volumeprice, gsp.ratificationstartdate,
                 pack_import.lvnsystemuserid, sysdate, gsp.ratificationuser_id,
                 gsp.ratificationtimestamp, sbg.sizebillinggroup_id
          from   generalsalesprice gsp
          join   product p
          on     p.product_id = gsp.product_id
          join   sizebillgroupperprodgroup sbg
          on     sbg.productgroup_id = p.productgroup_id
          where  gsp.sizebillinggroup_id is null
          and    not exists (select 1
                  from   generalsalesprice gsbg
                  where  gsbg.generalpricelist_id = gsp.generalpricelist_id
                  and    gsbg.product_id = gsp.product_id
                  and    gsbg.sizedefinition_id = gsp.sizedefinition_id
                  and    gsbg.startdate = gsp.startdate
                  and    gsbg.volumeprice = gsp.volumeprice
                  and    gsbg.sizebillinggroup_id = sbg.sizebillinggroup_id);
        --count inserted rows
        lv_counter := sql%rowcount;
        if lv_counter > 0 then
          begin
            --commit and write log
            commit;
            pack_import.write_log('Copied ' || lv_counter ||
                                  ' generalsalesprice for size billing groups.' ||
                                  'System setting SIZESPECIALCHARGEOPTIONS ' ||
                                  lv_sizespecialchargeoptions, 1);
          end;
        end if;
      end copy_generalsales_sbg;
      procedure copy_customersales_sbg is
      begin
        --copy_customersales_sbg
        --CUSTOMER_ID, PRODUCT_ID, SIZEDEFINITION_ID, STARTDATE, VOLUMEPRICE, SIZEBILLINGGROUP_ID
        lvnerrormsg := 'copy_customersales_sbg';
        insert into customersalesprice
          (customersalesprice_id, product_id, sizedefinition_id, timestamp, systemuser_id, price,
           startdate, customer_id, volumeprice, ratificationstartdate, creationuser_id,
           creationtimestamp, ratificationuser_id, ratificationtimestamp, sizebillinggroup_id)
          select seq_customersalesprice.nextval, csp.product_id, csp.sizedefinition_id, sysdate,
                 pack_import.lvnsystemuserid,
                 case
                   when (p.typeofmerchandise = 2 and csp.sizedefinition_id = lv_sizestarid and
                        sbg.surchargepercentage > 0) then
                    csp.price * (1 + (sbg.surchargepercentage / 100))
                   else
                    csp.price
                 end, csp.startdate, csp.customer_id, csp.volumeprice, csp.ratificationstartdate,
                 pack_import.lvnsystemuserid, sysdate, csp.ratificationuser_id,
                 csp.ratificationtimestamp, csp.sizebillinggroup_id
          from   customersalesprice csp
          join   customer c
          on     c.customer_id = csp.customer_id
          join   product p
          on     p.product_id = csp.product_id
          join   sizebillgroupperprodgroup sbg
          on     sbg.productgroup_id = p.productgroup_id
          where  c.useprodsizesurchargepricing = 'Y'
          and    csp.sizebillinggroup_id is null
          and    not exists (select 1
                  from   customersalesprice csbg
                  where  csbg.customer_id = csp.customer_id
                  and    csbg.product_id = csp.product_id
                  and    csbg.sizedefinition_id = csp.sizedefinition_id
                  and    csbg.startdate = csp.startdate
                  and    csbg.volumeprice = csp.volumeprice
                  and    csbg.sizebillinggroup_id = sbg.sizebillinggroup_id);
        --count inserted rows
        lv_counter := sql%rowcount;
        if lv_counter > 0 then
          begin
            --commit and write log
            commit;
            pack_import.write_log('Copied ' || lv_counter ||
                                  ' customersalesprice for size billing groups.' ||
                                  'System setting SIZESPECIALCHARGEOPTIONS ' ||
                                  lv_sizespecialchargeoptions, 1);
          end;
        end if;
      end copy_customersales_sbg;
    begin
      --copy_generalsales_sbg
      copy_generalsales_sbg;
      --copy_customersales_sbg
      copy_customersales_sbg;
    end copy_sales_chargeprices;
    procedure copy_replacement_chargeprices is
      procedure copy_generalreplacement_sbg is
      begin
        --copy_generalreplacement_sbg
        --GENERALPRICELIST_ID, PRODUCT_ID, SIZEDEFINITION_ID, STARTDATE, SIZEBILLINGGROUP_ID
        lvnerrormsg := 'copy_generalreplacement_sbg';
        insert into generalreplacementprice
          (generalreplacementprice_id, generalpricelist_id, product_id, sizedefinition_id,
           timestamp, systemuser_id, price, startdate, ratificationstartdate, creationuser_id,
           creationtimestamp, ratificationuser_id, ratificationtimestamp, sizebillinggroup_id)
          select seq_generalreplacementprice.nextval, grl.generalpricelist_id, grl.product_id,
                 grl.sizedefinition_id, sysdate, pack_import.lvnsystemuserid,
                 case
                   when (p.typeofmerchandise = 2 and grl.sizedefinition_id = lv_sizestarid and
                        sbg.surchargepercentage > 0) then
                    grl.price * (1 + (sbg.surchargepercentage / 100))
                   else
                    grl.price
                 end, grl.startdate, grl.ratificationstartdate, pack_import.lvnsystemuserid, sysdate,
                 grl.ratificationuser_id, grl.ratificationtimestamp, sbg.sizebillinggroup_id
          from   generalreplacementprice grl
          join   product p
          on     p.product_id = grl.product_id
          join   sizebillgroupperprodgroup sbg
          on     sbg.productgroup_id = p.productgroup_id
          where  grl.sizebillinggroup_id is null
          and    not exists (select 1
                  from   generalreplacementprice glbg
                  where  glbg.generalpricelist_id = grl.generalpricelist_id
                  and    glbg.product_id = grl.product_id
                  and    glbg.sizedefinition_id = grl.sizedefinition_id
                  and    glbg.startdate = grl.startdate
                  and    glbg.sizebillinggroup_id = sbg.sizebillinggroup_id);
        --count inserted rows
        lv_counter := sql%rowcount;
        if lv_counter > 0 then
          begin
            --commit and write log
            commit;
            pack_import.write_log('Copied ' || lv_counter ||
                                  ' generalreplacementprice for size billing groups.' ||
                                  'System setting SIZESPECIALCHARGEOPTIONS ' ||
                                  lv_sizespecialchargeoptions, 1);
          end;
        end if;
      end copy_generalreplacement_sbg;
      procedure copy_customerreplacement_sbg is
      begin
        --CUSTOMER_ID, PRODUCT_ID, SIZEDEFINITION_ID, STARTDATE, SIZEBILLINGGROUP_ID
        --copy_customerreplacment_sbg
        lvnerrormsg := 'copy_customerreplacement_sbg';
        insert into customerreplacementprice
          (customerreplacementprice_id, product_id, sizedefinition_id, customer_id, startdate,
           price, systemuser_id, timestamp, ratificationstartdate, creationuser_id,
           creationtimestamp, ratificationuser_id, ratificationtimestamp, sizebillinggroup_id)
          select seq_customerreplacementprice.nextval, crp.product_id, crp.sizedefinition_id,
                 crp.customer_id, crp.startdate, crp.price, pack_import.lvnsystemuserid, sysdate,
                 crp.ratificationstartdate, pack_import.lvnsystemuserid, sysdate,
                 crp.ratificationuser_id, crp.ratificationtimestamp, sbg.sizebillinggroup_id
          from   customerreplacementprice crp
          join   customer c
          on     c.customer_id = crp.customer_id
          join   product p
          on     p.product_id = crp.product_id
          join   sizebillgroupperprodgroup sbg
          on     sbg.productgroup_id = p.productgroup_id
          where  c.useprodsizesurchargepricing = 'Y'
          and    crp.sizebillinggroup_id is null
          and    not exists (select 1
                  from   customerreplacementprice crbg
                  where  crbg.customer_id = crp.customer_id
                  and    crbg.product_id = crp.product_id
                  and    crbg.sizedefinition_id = crp.sizedefinition_id
                  and    crbg.startdate = crp.startdate
                  and    crbg.sizebillinggroup_id = sbg.sizebillinggroup_id);
        --count inserted rows
        lv_counter := sql%rowcount;
        if lv_counter > 0 then
          begin
            --commit and write log
            commit;
            pack_import.write_log('Copied ' || lv_counter ||
                                  ' customerreplacementprice for size billing groups.' ||
                                  'System setting SIZESPECIALCHARGEOPTIONS ' ||
                                  lv_sizespecialchargeoptions, 1);
          end;
        end if;
      end copy_customerreplacement_sbg;
    begin
      --copy_replacement_chargeprices
      lvnerrormsg := 'copy_replacement_chargeprices';
      --copy_generalreplacement_sbg
      copy_generalreplacement_sbg;
      --copy_customerreplacment_sbg
      copy_customerreplacement_sbg;
    end copy_replacement_chargeprices;
  begin
    --import_chargespecialsize_price
    lvnerrormsg := '';
    --intialize
    intialize;
    --depending on system setting copy prices
    case lv_sizespecialchargeoptions
      when '0' then
        begin
          --0 - no special prices are used
          null;
        end;
      when '1' then
        begin
          --1 - special prices for Rent
          copy_rent_chargeprices;
        end;
      when '2' then
        begin
          --2 - special prices for Sales
          copy_sales_chargeprices;
        end;
      when '3' then
        begin
          --3 - special prices for Replacement
          copy_replacement_chargeprices;
        end;
      when '4' then
        begin
          --4 - special prices for Rent and Sales
          copy_rent_chargeprices;
          copy_sales_chargeprices;
        end;
      when '5' then
        begin
          --5 - special prices for Rent and Replacement
          copy_rent_chargeprices;
          copy_replacement_chargeprices;
        end;
      when '6' then
        begin
          --6 - special prices for Sales and Replacement
          copy_sales_chargeprices;
          copy_replacement_chargeprices;
        end;
      when '7' then
        begin
          --7 - special prices for Rent, Sales and Replacement
          copy_rent_chargeprices;
          copy_sales_chargeprices;
          copy_replacement_chargeprices;
        end;
      else
        begin
          pack_import.write_log('import_chargespecialsize_price, unknown value ' ||
                                lv_sizespecialchargeoptions ||
                                ' for system setting SIZESPECIALCHARGEOPTIONS?!', 3);
        end;
    end case;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('Error pack_import_pricestructure.import_chargespecialsize_price: ' ||
                              lvnerrormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
  end import_chargespecialsize_price;
end pack_import_pricestructure;
/
create or replace package pack_import_product is
  -- Author  : CRISTINA
  -- Created : 27/05/2002 11:54:51 AM
  -- Version : 2.0
  -- Changes : TNE 09/04/2003 order 500468
  --           PVD 18-aug-2003 added usedforemblem to insert sizedefinition.
  --           23-July-2018 added  procedure create_turnovergroups
  --           24-July-2018 added product emblem color descriptions
  --           25-July-2018 added product salesonly
  --           09-Nov-2018  ABS-74387 Add MRP and Invoice Column to conversion
  --           29-Jul-2020  ABS-99217 First Aid Kit (Cabinet Service)
  --           26-Nov-2020  ABS-127652 Extend conversion tool - I_PRODUCT
  --           25-Jul-202   ABS-134042 Cleanroom - Extend conversion for I_IMAGE
  --           29-AUG-2025  ABSN-9922 Pack product not being set through conversion
  procedure p_update_productgroup_turn;
  procedure import_images;
  procedure create_turnovergroups;
  procedure cfbimportproduct;
  procedure cfbimportproductsize;
  procedure cfbimportemblemproduct;
  procedure addmissingproductsize;
  procedure add_missing_default_prodsize;
  procedure add_alternativesizes;
end pack_import_product;
/
create or replace package body pack_import_product is
  errormsg                varchar2(256);
  sizetypeminusid         sizetype.sizetype_id%type;
  fabricid                fabric.fabric_id%type;
  sizedefinitionstarid    sizedefinition.sizedefinition_id%type;
  sizedefinitionminusid   sizedefinition.sizedefinition_id%type;
  generalpricelistrentid  generalpricelist.generalpricelist_id%type;
  generalpricelistreplid  generalpricelist.generalpricelist_id%type;
  generalpricelistsalesid generalpricelist.generalpricelist_id%type;
  specialchargeid         specialcharge.specialcharge_id%type;
  changesperweek_nr       generalrentprice.changesperweek%type;
  typeofrent_nr           generalrentprice.typeofrent%type;
  procedure create_specialcharge is
  begin
    -- special charge
    select specialcharge_id into specialchargeid from specialcharge where code = '1';
  exception
    when no_data_found then
      begin
        pack_import.cfbcreate_specialcharge(specialchargeid, 3, 'Y',
                                            to_date('1-1-2001', 'DD-MM-YYYY'), 0, 0, 0, 0, 'N', '1',
                                            null);
        pack_import.cfbcreate_specialcharge_desc(specialchargeid, 'Standard Special Charge');
        -- special charge tax
        begin
          insert into specialchargetax
            (specialcharge_id, country_id, taxgroup_id, systemuser_id, timestamp)
            select specialchargeid, pack_import.lvncountrydefaultid, min(tx.taxgroup_id),
                   pack_import.lvnsystemuserid, sysdate
            from   taxgroup tx
            where  tx.active = 'Y'
            and    tx.country_id = pack_import.lvncountrydefaultid;
        exception
          when others then
            null;
        end;
      end;
  end create_specialcharge;
  procedure import_images is
    lv_imageid   image.image_id%type;
    lv_countrows integer := 0;
    errorcount   integer := 0;
  begin
    --import_images
    for x in (select i.imagetype, i.imagecode, i.imagename, i.image, i.description, i.freetext
              from   i_image i
              where  not exists (select 1
                      from   image y
                      where  y.code = upper(trim(i.imagecode))
                      and    y.imagetype = i.imagetype)
              order  by i.imagetype, i.imagecode) loop
      begin
        --insert into image
        insert into image
          (image_id, imagetype, code, imagename, image, systemuser_id, timestamp, capturetimestamp,
           freetext)
        values
          (seq_image.nextval, nvl(x.imagetype, 1), upper(trim(x.imagecode)),
           coalesce(x.imagename, x.description, x.imagecode), x.image, pack_import.lvnsystemuserid,
           sysdate, null, x.freetext)
        returning image_id into lv_imageid;
        --insert into image_desc
        insert into image_desc
          (image_id, language_id, description, systemuser_id, timestamp)
        values
          (lv_imageid, pack_import.lvnlanguageid,
           substr(coalesce(x.description, x.imagename, x.imagecode), 1, 40),
           pack_import.lvnsystemuserid, sysdate);
        lv_countrows := lv_countrows + 1;
      exception
        when others then
          begin
            errorcount := errorcount + 1;
            pack_import.write_log('Error import image code ' || x.imagecode || ' Type ' ||
                                  to_char(x.imagetype) || ' ' || sqlerrm, 3);
          end;
      end;
    end loop; --x
    if errorcount > 0 then
      begin
        pack_import.write_log('Error(s) ' || errorcount ||
                              ' during import images (pack_import_product.import_images)', 3);
      end;
    end if;
    if lv_countrows > 0 then
      begin
        commit;
        pack_import.write_log(lv_countrows || ' image(s) imported.');
      end;
    end if;
  end import_images;
  procedure create_turnovergroups is
    lv_countrows           number;
    lv_errorcount          number;
    lv_salesjournalgroupid salesjournalgroup.salesjournalgroup_id%type;
    lv_turnovegroupid      turnovergroup.turnovergroup_id%type;
  begin
    --create_turnovergroups
    lv_countrows  := 0;
    lv_errorcount := 0;
    for y in (select z.salesjournalgroup_code, z.salesjournalgroup_desc
              from   (select it.salesjournalgroup_code,
                              max(it.salesjournalgroup_desc) salesjournalgroup_desc
                       from   i_turnovergroup it
                       where  it.salesjournalgroup_code is not null
                       group  by it.salesjournalgroup_code) z
              where  not exists
               (select 1 from salesjournalgroup sjg where sjg.code = z.salesjournalgroup_code)) loop
      begin
        insert into salesjournalgroup
          (salesjournalgroup_id, code, active, systemuser_id, timestamp)
        values
          (seq_salesjournalgroup.nextval, y.salesjournalgroup_code, 'Y',
           pack_import.lvnsystemuserid, sysdate)
        returning salesjournalgroup_id into lv_salesjournalgroupid;
        insert into salesjournalgroup_desc
          (salesjournalgroup_id, language_id, timestamp, systemuser_id, description)
        values
          (lv_salesjournalgroupid, pack_import.lvnlanguageid, sysdate, pack_import.lvnsystemuserid,
           nvl(y.salesjournalgroup_desc, y.salesjournalgroup_code));
        --count rows
        lv_countrows := lv_countrows + 1;
      exception
        when dup_val_on_index then
          null; --does not matter if its was already there
        when others then
          begin
            lv_errorcount := lv_errorcount + 1;
            pack_import.write_log('Failed to import salesjournalgroup ' ||
                                  y.salesjournalgroup_code || ' ' || substr(sqlerrm, 1, 512), -3);
          end;
      end;
    end loop; -- y
    if lv_errorcount > 0 then
      begin
        commit;
        pack_import.write_log(lv_errorcount || ' NOT imported salesjournalgroup, due to errors!', 3);
      end;
    end if;
    if lv_countrows > 0 then
      begin
        commit;
        pack_import.write_log(lv_countrows ||
                              ' salesjournalgroup rows imported from i_turnovergroup.');
      end;
    end if;
    --reset count
    lv_countrows  := 0;
    lv_errorcount := 0;
    --start convert missing turnovergroups
    for x in (select it.*,
                     nvl(sjg.salesjournalgroup_id, pack_import.lvnsalesjournalgroupminusid) salesjournalgroup_id,
                     (select tx.taxgroup_id
                       from   taxgroup tx
                       where  tx.code = it.taxgroupcode
                       and    tx.country_id = pack_import.lvncountrydefaultid) taxgroup_id
              from   i_turnovergroup it
              left   outer join salesjournalgroup sjg
              on     sjg.code = it.salesjournalgroup_code
              where  not exists
               (select tg.code from turnovergroup tg where tg.code = it.turnovergroup_code)) loop
      begin
        insert into turnovergroup
          (turnovergroup_id, salesjournalgroup_id, code, legacycode, active, systemuser_id,
           timestamp, taxgroup_id)
        values
          (seq_turnovergroup.nextval, x.salesjournalgroup_id, x.turnovergroup_code,
           x.turnovergroup_legacycode, nvl(x.active, 'Y'), pack_import.lvnsystemuserid, sysdate,
           x.taxgroup_id) return turnovergroup_id into lv_turnovegroupid;
        insert into turnovergroup_desc
          (turnovergroup_id, language_id, description, systemuser_id, timestamp)
        values
          (lv_turnovegroupid, pack_import.lvnlanguageid,
           nvl(x.turnovergroup_description, x.turnovergroup_code), pack_import.lvnsystemuserid,
           sysdate);
        lv_countrows := lv_countrows + 1;
      exception
        when dup_val_on_index then
          null; --does not matter if its was already there
        when others then
          begin
            lv_errorcount := lv_errorcount + 1;
            errormsg      := 'create_turnovergroups: Failed to import turnovergroup code ' ||
                             x.turnovergroup_code;
            pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
          end;
      end;
    end loop;
    if lv_errorcount > 0 then
      begin
        commit;
        pack_import.write_log(lv_errorcount ||
                              ' rows NOT imported from i_turnovergroup, due to errors!', 3);
      end;
    end if;
    if lv_countrows > 0 then
      begin
        commit;
        pack_import.write_log(lv_countrows || ' turnovergroup rows imported from i_turnovergroup.');
      end;
    end if;
  end create_turnovergroups;
  procedure cfbimportproductfixedinfo is
    countrows   integer;
    errorcount  integer := 0;
    colorid     color.color_id%type;
    lactivityid activity.activity_id%type;
    taxgroupid  taxgroup.taxgroup_id%type := -1;
  begin
    --import_images
    import_images;
    begin
      insert into mrpcode
        (mrpcode_id, code, description, active, systemuser_id, timestamp)
        select seq_mrpcode.nextval, mrpi.mrpcode, mrpi.mrpcode, 'Y', pack_import.lvnsystemuserid,
               sysdate
        from   (select upper(trim(i.mrpcode)) mrpcode
                 from   i_product i
                 where  i.mrpcode is not null
                 group  by upper(trim(i.mrpcode))) mrpi
        where  not exists (select 1 from mrpcode mrpc where mrpc.code = mrpi.mrpcode);
      countrows := sql%rowcount;
      if countrows > 0 then
        begin
          commit;
          pack_import.write_log(countrows || ' mrpcode rows imported.');
          countrows := 0;
        end;
      end if;
    exception
      when others then
        begin
          pack_import.write_log('cfbimportproductfixedinfo: During adding of new mrpcode(s) ' ||
                                substr(sqlerrm, 1, 512), 3);
        end;
    end;
    begin
      --assembly label layout
      for x in (select ip.assemblylayout, replace(replace(max(ip.sterile), 0, 'N'), 1, 'Y') sterile
                from   i_product ip
                where  ip.assemblylayout is not null
                group  by ip.assemblylayout) loop
        begin
          insert into labellayout
            (labellayout_id, code, description, labeltype, defaultlayout, systemuser_id, timestamp,
             layoutreceiveonstock, sterile)
          values
            (seq_labellayout.nextval, x.assemblylayout, x.assemblylayout, 4, 'N',
             pack_import.lvnsystemuserid, sysdate, 'N', x.sterile);
        end;
      end loop;
    exception
      when others then
        begin
          errormsg := 'cfbimportproductfixedinfo: During adding of all assembly label layouts';
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
        end;
    end;
    begin
      -- generalpricelist rent '1'
      select generalpricelist_id
      into   generalpricelistrentid
      from   generalpricelist
      where  code = '1'
      and    pricetype = 2;
    exception
      when no_data_found then
        begin
          pack_import.cfbcreate_generalpricelist(generalpricelistrentid, 2, '1', 'Standard', 'Y',
                                                 'Y', null, pack_import.lvncurrencydefaultid, 0);
        end;
    end;
    begin
      -- generalpricelist replacement '1'
      select generalpricelist_id
      into   generalpricelistreplid
      from   generalpricelist
      where  code = '1'
      and    pricetype = 3;
    exception
      when no_data_found then
        begin
          pack_import.cfbcreate_generalpricelist(generalpricelistreplid, 3, '1', 'Standard', 'Y',
                                                 'Y', null, pack_import.lvncurrencydefaultid, 0);
        end;
    end;
    begin
      -- generalpricelist sales '1'
      select generalpricelist_id
      into   generalpricelistsalesid
      from   generalpricelist
      where  code = '1'
      and    pricetype = 4;
    exception
      when no_data_found then
        begin
          pack_import.cfbcreate_generalpricelist(generalpricelistsalesid, 4, '1', 'Standard', 'Y',
                                                 'Y', null, pack_import.lvncurrencydefaultid, 0);
        end;
    end;
    begin
      -- sizetype '-'
      select sizetype_id
      into   sizetypeminusid
      from   sizetype
      where  code = '-'
      and    usagetype = 1;
    exception
      when no_data_found then
        begin
          insert into sizetype
            (sizetype_id, code, systemuser_id, timestamp)
          values
            (seq_sizetype.nextval, '-', pack_import.lvnsystemuserid, sysdate)
          returning sizetype_id into sizetypeminusid;
          insert into sizetype_desc
            (sizetype_id, language_id, description, systemuser_id, timestamp)
          values
            (seq_sizetype.currval, pack_import.lvnlanguageid, '-', pack_import.lvnsystemuserid,
             sysdate);
        end;
    end;
    -- sizedefinition '*'
    begin
      select sizedefinition_id into sizedefinitionstarid from sizedefinition where code = '*';
    exception
      when no_data_found then
        begin
          pack_import.cfbcreate_sizedefinition(sizedefinitionstarid, '*', 'N', null, null, null,
                                               'N');
          pack_import.cfbcreate_sizedefinition_desc(sizedefinitionstarid, 'All sizes');
        end;
    end;
    -- sizedefinition '-'
    begin
      select sizedefinition_id into sizedefinitionminusid from sizedefinition where code = '-';
    exception
      when no_data_found then
        begin
          pack_import.cfbcreate_sizedefinition(sizedefinitionminusid, '-', 'N', null, null, null,
                                               'N');
          pack_import.cfbcreate_sizedefinition_desc(sizedefinitionminusid, '-');
        end;
    end;
    -- sizespersizetype (sizetype, sizedefinition_id) ('STD', '*')
    begin
      insert into sizespersizetype
        (sizetype_id, sizedefinition_id, sequencenumber, systemuser_id, timestamp)
        select a.sizetype_id, b.sizedefinition_id, nvl(max(c.sequencenumber), 0) + 1,
               pack_import.lvnsystemuserid, sysdate
        from   sizetype a, sizedefinition b, sizespersizetype c
        where  a.code = 'STD'
        and    b.code = '*'
        and    a.sizetype_id = c.sizetype_id(+)
        group  by a.sizetype_id, b.sizedefinition_id;
    exception
      when dup_val_on_index then
        null;
    end;
    -- sizespersizetype (sizetype, sizedefinition_id) ('STD', '-')
    begin
      insert into sizespersizetype
        (sizetype_id, sizedefinition_id, sequencenumber, systemuser_id, timestamp)
        select a.sizetype_id, b.sizedefinition_id, nvl(max(c.sequencenumber), 0) + 1,
               pack_import.lvnsystemuserid, sysdate
        from   sizetype a, sizedefinition b, sizespersizetype c
        where  a.code = 'STD'
        and    b.code = '-'
        and    a.sizetype_id = c.sizetype_id(+)
        group  by a.sizetype_id, b.sizedefinition_id;
    exception
      when dup_val_on_index then
        null;
    end;
    -- sizespersizetype (sizetype, sizedefinition_id) ('-', '*')
    begin
      insert into sizespersizetype
        (sizetype_id, sizedefinition_id, sequencenumber, systemuser_id, timestamp)
        select a.sizetype_id, b.sizedefinition_id, nvl(max(c.sequencenumber), 0) + 1,
               pack_import.lvnsystemuserid, sysdate
        from   sizetype a, sizedefinition b, sizespersizetype c
        where  a.code = '-'
        and    b.code = '*'
        and    a.sizetype_id = c.sizetype_id(+)
        group  by a.sizetype_id, b.sizedefinition_id;
    exception
      when dup_val_on_index then
        null;
    end;
    -- sizespersizetype (sizetype, sizedefinition_id) ('-', '-')
    begin
      insert into sizespersizetype
        (sizetype_id, sizedefinition_id, sequencenumber, systemuser_id, timestamp)
        select a.sizetype_id, b.sizedefinition_id, nvl(max(c.sequencenumber), 0) + 1,
               pack_import.lvnsystemuserid, sysdate
        from   sizetype a, sizedefinition b, sizespersizetype c
        where  a.code = '-'
        and    b.code = '-'
        and    a.sizetype_id = c.sizetype_id(+)
        group  by a.sizetype_id, b.sizedefinition_id;
    exception
      when dup_val_on_index then
        null;
    end;
    -- color
    countrows := 0;
    for x in (select colorcode, nvl(max(colordesc), colorcode) colordesc
              from   i_product
              where  colorcode is not null
              and    not exists (select code from color where code = colorcode)
              group  by colorcode) loop
      begin
        pack_import.cfbcreate_color(colorid, x.colorcode, null, 'N');
        pack_import.cfbcreate_color_desc(colorid, x.colordesc);
        countrows := countrows + 1;
      exception
        when others then
          errormsg := 'CFbImportProduct: Fail to import color code/description ' || x.colorcode || '/' ||
                      x.colordesc;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' color rows imported.');
      end;
    end if;
    -- fabric
    countrows := 0;
    for vcursor in (select fabriccode, nvl(max(fabricdesc), fabriccode) fabricdesc
                    from   i_product
                    where  fabriccode is not null
                    and    not exists (select code from fabric where code = fabriccode)
                    group  by fabriccode) loop
      begin
        pack_import.cfbcreate_fabric(fabricid, vcursor.fabriccode, 'N');
        pack_import.cfbcreate_fabric_desc(fabricid, vcursor.fabricdesc);
        countrows := countrows + 1;
      exception
        when others then
          errormsg := 'CFbImportProduct: Fail to import fabric code/description ' ||
                      vcursor.fabriccode || '/' || vcursor.fabricdesc;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' fabric rows imported.');
      end;
    end if;
    -- washing process
    countrows := 0;
    for vcursor in (select washprocesscode,
                           nvl(max(washprocessdesc), washprocesscode) washprocessdesc
                    from   i_product
                    where  washprocesscode is not null
                    and    not exists
                     (select code from washingprocess where code = washprocesscode)
                    group  by washprocesscode) loop
      begin
        insert into washingprocess
          (washingprocess_id, code, systemuser_id, timestamp, color)
        values
          (seq_washingprocess.nextval, vcursor.washprocesscode, pack_import.lvnsystemuserid,
           sysdate, 0);
        insert into washingprocess_desc
          (washingprocess_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_washingprocess.currval, pack_import.lvnlanguageid, vcursor.washprocessdesc,
           pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      exception
        when others then
          errormsg := 'CFbImportProduct: Fail to import washing process code/description ' ||
                      vcursor.washprocesscode || '/' || vcursor.washprocessdesc;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' washing process rows imported.');
      end;
    end if;
    -- registration unit
    countrows := 0;
    for vcursor in (select registrationunitcode,
                           nvl(max(registrationunitdesc), registrationunitcode) registrationunitdesc
                    from   i_product
                    where  registrationunitcode is not null
                    and    not exists (select code
                            from   registrationunit
                            where  code = substr(registrationunitcode, 1, 3))
                    group  by registrationunitcode) loop
      begin
        insert into registrationunit
          (registrationunit_id, code, decimals, systemuser_id, timestamp)
        values
          (seq_registrationunit.nextval, substr(vcursor.registrationunitcode, 1, 3), 0,
           pack_import.lvnsystemuserid, sysdate);
        insert into registrationunit_desc
          (registrationunit_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_registrationunit.currval, pack_import.lvnlanguageid, vcursor.registrationunitdesc,
           pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      exception
        when others then
          errormsg := 'CFbImportProduct: Fail to import registration unit code/description ' ||
                      vcursor.registrationunitcode || '/' || vcursor.registrationunitdesc;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' registration unit rows imported.');
      end;
    end if;
    -- finishing method
    countrows := 0;
    for vcursor in (select finishingmethodcode,
                           nvl(max(finishingmethoddesc), finishingmethodcode) finishingmethoddesc
                    from   i_product
                    where  finishingmethodcode is not null
                    and    not exists
                     (select code from finishingmethod where code = finishingmethodcode)
                    group  by finishingmethodcode) loop
      begin
        insert into finishingmethod
          (finishingmethod_id, code, active, systemuser_id, timestamp)
        values
          (seq_finishingmethod.nextval, vcursor.finishingmethodcode, 'Y',
           pack_import.lvnsystemuserid, sysdate);
        insert into finishingmethod_desc
          (finishingmethod_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_finishingmethod.currval, pack_import.lvnlanguageid, vcursor.finishingmethoddesc,
           pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      exception
        when others then
          errormsg := 'CFbImportProduct: Fail to import finishing method code/description ' ||
                      vcursor.finishingmethodcode || '/' || vcursor.finishingmethoddesc;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' finishing method rows imported.');
      end;
    end if;
    -- finishcode
    for x in (select i.finishingcode,
                     nvl(max(i.finishingdescription), i.finishingcode) finishingdescription
              from   i_product i
              where  i.finishingcode is not null
              and    not exists (select f.finishingcode_id
                      from   finishingcode f
                      where  f.finishingcode = i.finishingcode)
              group  by i.finishingcode) loop
      begin
        insert into finishingcode
          (finishingcode_id, finishingcode, active, systemuser_id, timestamp)
        values
          (seq_finishingcode.nextval, x.finishingcode, 'Y', pack_import.lvnsystemuserid, sysdate);
        insert into finishingcode_desc
          (finishingcode_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_finishingcode.currval, pack_import.lvnlanguageid,
           nvl(x.finishingdescription, x.finishingcode), pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      exception
        when others then
          errormsg := 'CFbImportProduct: Fail to import finishing code/description ' ||
                      x.finishingcode || '/' || x.finishingdescription;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' finishing rows imported.');
      end;
    end if;
    -- turnovergroup
    countrows := 0;
    for vcursor in (select distinct turnovergrouprent tcode
                    from   i_product
                    where  turnovergrouprent is not null
                    and    not exists
                     (select code from turnovergroup where code = turnovergrouprent)
                    union
                    select distinct turnovergroupwash tcode
                    from   i_product
                    where  turnovergroupwash is not null
                    and    not exists
                     (select code from turnovergroup where code = turnovergroupwash)
                    union
                    select distinct turnovergrouprepl tcode
                    from   i_product
                    where  turnovergrouprepl is not null
                    and    not exists
                     (select code from turnovergroup where code = turnovergrouprepl)
                    union
                    select distinct turnovergroupsales tcode
                    from   i_product
                    where  turnovergroupsales is not null
                    and    not exists
                     (select code from turnovergroup where code = turnovergroupsales)
                    union
                    select distinct turnovergrouploss tcode
                    from   i_product
                    where  turnovergrouploss is not null
                    and    not exists
                     (select code from turnovergroup where code = turnovergrouploss)
                    union
                    select distinct turnovergroupadvance tcode
                    from   i_product
                    where  turnovergroupadvance is not null
                    and    not exists
                     (select code from turnovergroup where code = turnovergroupadvance)
                    union
                    select distinct turnovergroupcorrections tcode
                    from   i_product
                    where  turnovergroupcorrections is not null
                    and    not exists
                     (select code from turnovergroup where code = turnovergroupcorrections)
                    union
                    select distinct turnovergroupwashcog tcode
                    from   i_product
                    where  turnovergroupwashcog is not null
                    and    not exists
                     (select code from turnovergroup where code = turnovergroupwashcog)
                    union
                    select distinct turnovergrouploan tcode
                    from   i_product
                    where  turnovergrouploan is not null
                    and    not exists
                     (select code from turnovergroup where code = turnovergrouploan)
                    union
                    select distinct turnovergrouprentnotret tcode
                    from   i_product
                    where  turnovergrouprentnotret is not null
                    and    not exists
                     (select code from turnovergroup where code = turnovergrouprentnotret)) loop
      begin
        insert into turnovergroup
          (turnovergroup_id, salesjournalgroup_id, code, legacycode, active, systemuser_id,
           timestamp)
        values
          (seq_turnovergroup.nextval, pack_import.lvnsalesjournalgroupminusid, vcursor.tcode, null,
           'Y', pack_import.lvnsystemuserid, sysdate);
        insert into turnovergroup_desc
          (turnovergroup_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_turnovergroup.currval, pack_import.lvnlanguageid, vcursor.tcode,
           pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null; --does not matter if its was already there
        when others then
          errormsg := 'CFbImportProduct: Fail to import turnovergroup code ' || vcursor.tcode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' turnovergroup rows imported.');
      end;
    end if;
    -- convert supplier
    pack_import_supplier.cfbimport_supplier;
    -- supplier
    countrows := 0;
    for vcursor in (select suppliernumber,
                           nvl(max(suppliername), to_char(suppliernumber)) suppliername
                    from   i_product
                    where  suppliernumber is not null
                    and    not exists
                     (select suppliernumber
                            from   supplier
                            where  supplier.suppliernumber = i_product.suppliernumber)
                    group  by suppliernumber) loop
      begin
        -- insert address then supplier.
        insert into address
          (address_id, street, zipcode, city, state, systemuser_id, county, timestamp, street2)
        values
          (seq_address.nextval, null, '-', '-', null, pack_import.lvnsystemuserid, null, sysdate,
           null);
        insert into supplier
          (supplier_id, suppliernumber, name, address_id, currency_id, systemuser_id, timestamp,
           averageshipmentcosts, sendpurchaseorder, country_id, dateactive)
        values
          (seq_supplier.nextval, vcursor.suppliernumber, vcursor.suppliername, seq_address.currval,
           pack_import.lvncurrencydefaultid, pack_import.lvnsystemuserid, sysdate, 0, 0,
           pack_import.lvncountrydefaultid, trunc(sysdate) - 1);
        countrows := countrows + 1;
      exception
        when others then
          errormsg := 'CFbImportProduct: Fail to import supplier number/name ' ||
                      vcursor.suppliernumber || '/' || vcursor.suppliername;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' supplier rows imported.');
      end;
    end if;
    -- productgroup
    countrows := 0;
    for vcursor in (select a.productgroupcode,
                           nvl(max(a.productgroupdesc), a.productgroupcode) productgroupdesc,
                           max(a.pgactivitytypecode) pgactivitytypecode
                    from   i_product a
                    where  not exists
                     (select code from productgroup pg where pg.code = a.productgroupcode)
                    group  by a.productgroupcode) loop
      begin
        --get activity
        pack_import.cfbcreate_activity(lactivityid, vcursor.pgactivitytypecode);
        --insert productgroup
        insert into productgroup
          (productgroup_id, activity_id, code, legacyproductgroupcode, active, systemuser_id,
           timestamp)
        values
          (seq_productgroup.nextval, lactivityid, vcursor.productgroupcode,
           vcursor.productgroupcode, 'Y', pack_import.lvnsystemuserid, sysdate);
        insert into productgroup_desc
          (productgroup_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_productgroup.currval, pack_import.lvnlanguageid, vcursor.productgroupdesc,
           pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportProduct: Fail to import product group code/description ' ||
                      vcursor.productgroupcode || '/' || vcursor.productgroupdesc;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' product group rows imported.');
      end;
    end if;
    -- taxgroup
    countrows := 0;
    for vcursor in (select taxgroupcode, nvl(max(taxgroupdesc), taxgroupcode) taxgroupdesc
                    from   i_product
                    where  taxgroupcode is not null
                    and    not exists (select code from taxgroup where code = taxgroupcode)
                    group  by taxgroupcode) loop
      begin
        insert into taxgroup
          (taxgroup_id, code, description, country_id, active, taxrate, oldtaxrate,
           startdatetaxrate, systemuser_id, timestamp)
        values
          (seq_taxgroup.nextval, vcursor.taxgroupcode, vcursor.taxgroupdesc,
           pack_import.lvncountrydefaultid, 'Y', 0, 0, to_date('1-1-2001', 'DD-MM-YYYY'),
           pack_import.lvnsystemuserid, sysdate)
        returning taxgroup_id into taxgroupid;
        countrows := countrows + 1;
      exception
        when others then
          errormsg := 'CFbImportProduct: Fail to import tax group code/description ' ||
                      vcursor.taxgroupcode || '/' || vcursor.taxgroupdesc;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' tax group rows imported.');
      end;
    end if;
    -- product group tax
    begin
      insert into productgrouptax
        (productgroup_id, country_id, taxgroup_id, timestamp, systemuser_id)
        select g.productgroup_id, t.country_id, max(t.taxgroup_id) taxgroup_id, sysdate,
               pack_import.lvnsystemuserid
        from   i_product ip, taxgroup t, productgroup g
        where  ip.taxgroupcode = t.code
        and    ip.productgroupcode = g.code
        and    not exists (select x.productgroup_id, x.taxgroup_id
                from   productgrouptax x
                where  x.productgroup_id = g.productgroup_id
                and    x.country_id = t.country_id)
        group  by g.productgroup_id, t.country_id;
    exception
      when others then
        begin
          errormsg := 'CFbImportProduct: Fail to import productgrouptax';
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
        end;
    end;
    -- provisiongroupcode
    countrows := 0;
    for x in (select i.provisiongroupcode
              from   i_product i
              where  i.provisiongroupcode is not null
              and    not exists (select g.provisiongroup_id
                      from   provisiongroup g
                      where  g.code = i.provisiongroupcode)
              group  by i.provisiongroupcode
              order  by i.provisiongroupcode) loop
      begin
        insert into provisiongroup
          (provisiongroup_id, code, description, active, systemuser_id, timestamp)
        values
          (seq_provisiongroup.nextval, x.provisiongroupcode, x.provisiongroupcode, 'Y',
           pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' provisiongroup rows imported.');
      end;
    end if;
    --product ranking
    countrows  := 0;
    errorcount := 0;
    for x in (select i.productrankingprio
              from   i_product i
              where  i.productrankingprio is not null
              and    not exists (select r.productranking_id
                      from   productranking r
                      where  r.priority = i.productrankingprio)
              group  by i.productrankingprio
              order  by i.productrankingprio) loop
      begin
        insert into productranking
          (productranking_id, priority, ranking, systemuser_id, timestamp)
        values
          (seq_productranking.nextval, x.productrankingprio, to_char(x.productrankingprio),
           pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          begin
            errorcount := errorcount + 1;
          end;
      end;
    end loop;
    if errorcount > 0 then
      begin
        pack_import.write_log(errorcount ||
                              ' duplicate errors on product ranking priority, please check product ranking.',
                              3);
      end;
    end if;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' productranking rows imported.');
      end;
    end if;
    --product sort group
    countrows  := 0;
    errorcount := 0;
    for zz in (select ip.productsortgroupcode
               from   i_product ip
               where  ip.productsortgroupcode is not null
               and    not exists
                (select 1 from productsortgroup psg where psg.code = ip.productsortgroupcode)
               group  by ip.productsortgroupcode
               order  by ip.productsortgroupcode) loop
      begin
        insert into productsortgroup
          (productsortgroup_id, code, description, systemuser_id, timestamp)
        values
          (seq_productsortgroup.nextval, zz.productsortgroupcode, zz.productsortgroupcode,
           pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          begin
            errorcount := errorcount + 1;
          end;
      end;
    end loop; --zz
    if errorcount > 0 then
      begin
        pack_import.write_log(errorcount ||
                              ' duplicate errors on productsortgroup, please check productsortgroup.',
                              3);
      end;
    end if;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' productsortgroup rows imported.');
      end;
    end if;
    --product modification group
    countrows  := 0;
    errorcount := 0;
    for zm in (select mgz.code
               from   (select ip.modificationgroup1 code
                        from   i_product ip
                        where  ip.modificationgroup1 is not null
                        and    not exists (select 1
                                from   modificationgroup mg
                                where  mg.code = ip.modificationgroup1)
                        union all
                        select ip.modificationgroup2
                        from   i_product ip
                        where  ip.modificationgroup2 is not null
                        and    not exists (select 1
                                from   modificationgroup mg
                                where  mg.code = ip.modificationgroup2)
                        union all
                        select ip.modificationgroup3
                        from   i_product ip
                        where  ip.modificationgroup3 is not null
                        and    not exists (select 1
                                from   modificationgroup mg
                                where  mg.code = ip.modificationgroup3)) mgz
               group  by mgz.code
               order  by mgz.code) loop
      begin
        insert into modificationgroup
          (modificationgroup_id, code, systemuser_id, timestamp)
        values
          (seq_modificationgroup.nextval, zm.code, pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          begin
            errorcount := errorcount + 1;
          end;
      end;
    end loop; --zm
    if errorcount > 0 then
      begin
        pack_import.write_log(errorcount ||
                              ' duplicate errors on modificationgroup, please check productsortgroup.',
                              3);
      end;
    end if;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(countrows || ' modificationgroup rows imported.');
      end;
    end if;
  exception
    when others then
      pack_import.write_log('error during cfbimportproductfixedinfo: ' || ' ' ||
                            substr(sqlerrm, 1, 512), 3);
  end cfbimportproductfixedinfo;
  procedure p_update_productgroup_turn is
  begin
    update productgroup pg
    set    pg.rentturnovergroup_id =
            (select max(p.rentturnovergroup_id)
             from   product p
             where  p.productgroup_id = pg.productgroup_id)
    where  pg.rentturnovergroup_id is null;
    update productgroup pg
    set    pg.washturnovergroup_id =
            (select max(p.washturnovergroup_id)
             from   product p
             where  p.productgroup_id = pg.productgroup_id)
    where  pg.washturnovergroup_id is null;
    update productgroup pg
    set    pg.salesturnovergroup_id =
            (select max(p.salesturnovergroup_id)
             from   product p
             where  p.productgroup_id = pg.productgroup_id)
    where  pg.salesturnovergroup_id is null;
    update productgroup pg
    set    pg.replacementturnovergroup_id =
            (select max(p.replacementturnovergroup_id)
             from   product p
             where  p.productgroup_id = pg.productgroup_id)
    where  pg.replacementturnovergroup_id is null;
    update productgroup pg
    set    pg.lossturnovergroup_id =
            (select max(p.lossturnovergroup_id)
             from   product p
             where  p.productgroup_id = pg.productgroup_id)
    where  pg.lossturnovergroup_id is null;
    update productgroup pg
    set    pg.advanceturnovergroup_id =
            (select max(p.advanceturnovergroup_id)
             from   product p
             where  p.productgroup_id = pg.productgroup_id)
    where  pg.advanceturnovergroup_id is null;
    update productgroup pg
    set    pg.correctionsturnovergroup_id =
            (select max(p.correctionsturnovergroup_id)
             from   product p
             where  p.productgroup_id = pg.productgroup_id)
    where  pg.correctionsturnovergroup_id is null;
    update productgroup pg
    set    pg.washcogturnovergroup_id =
            (select max(p.washcogturnovergroup_id)
             from   product p
             where  p.productgroup_id = pg.productgroup_id)
    where  pg.washcogturnovergroup_id is null;
    update productgroup pg
    set    pg.loanturnovergroup_id =
            (select max(p.loanturnovergroup_id)
             from   product p
             where  p.productgroup_id = pg.productgroup_id)
    where  pg.loanturnovergroup_id is null;
    update productgroup pg
    set    pg.rentnotretturnovergroup_id =
            (select max(p.rentnotretturnovergroup_id)
             from   product p
             where  p.productgroup_id = pg.productgroup_id)
    where  pg.rentnotretturnovergroup_id is null;
    commit;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log(' cfbimportproduct fail to update product group turnovergroups ' ||
                              substr(sqlerrm, 1, 512), 2);
      end;
  end p_update_productgroup_turn;
  procedure cfbimportpackcontent is
    lvncountrows number;
  begin
    --convert packcontents
    select count(1)
    into   lvncountrows
    from   i_packcontent ip
    where  not exists
     (select 1
            from   packcontents pc, product pack, product p, sizedefinition s, finishingmethod f
            where  ip.packcode = pack.code
            and    ip.productcode = p.code
            and    ip.sizecode = s.code
            and    ip.finishingmethodcode = f.code
            and    pc.pack_id = pack.product_id
            and    pc.packsequence = ip.packsequence
            and    pc.product_id = p.product_id
            and    pc.sizedefinition_id = s.sizedefinition_id
            and    pc.finishingmethod_id = f.finishingmethod_id
            and    pc.dateactive = ip.dateactive);
    if lvncountrows > 0 then
      begin
        pack_import.write_log(lvncountrows || ' pack contents rows to be imported.');
        --insert into packcontents
        insert into packcontents
          (pack_id, packcontents_id, packsequence, product_id, sizedefinition_id, amount, remark,
           location, systemuser_id, timestamp, finishingmethod_id, uniquelycoded, dateactive,
           dateinactive, allowpackcontents, rownumber, positionnumber)
          select pack.product_id, seq_packcontents.nextval, ip.packsequence, p.product_id,
                 s.sizedefinition_id, ip.amount, ip.remark, ip.location, pack_import.lvnsystemuserid,
                 sysdate, f.finishingmethod_id, ip.uniquelycoded, ip.dateactive, ip.dateinactive,
                 ip.allowpackcontents, ip.rownumber, ip.positionnumber
          from   i_packcontent ip
          join   product pack
          on     pack.code = ip.packcode
          join   product p
          on     p.code = ip.productcode
          join   sizedefinition s
          on     s.code = ip.sizecode
          join   finishingmethod f
          on     f.code = ip.finishingmethodcode
          where  not exists (select 1
                  from   packcontents pc
                  where  pc.pack_id = pack.product_id
                  and    pc.packsequence = ip.packsequence
                  and    pc.product_id = p.product_id
                  and    pc.sizedefinition_id = s.sizedefinition_id
                  and    pc.finishingmethod_id = f.finishingmethod_id
                  and    pc.dateactive = ip.dateactive
                  and    ip.rownumber is null
                  and    pc.rownumber is null
                  and    ip.positionnumber is null
                  and    pc.positionnumber is null)
          and    not exists (select 1
                  from   packcontents pc
                  where  pc.pack_id = pack.product_id
                  and    ip.packsequence is null
                  and    pc.packsequence is null
                  and    pc.product_id = p.product_id
                  and    pc.sizedefinition_id = s.sizedefinition_id
                  and    pc.finishingmethod_id = f.finishingmethod_id
                  and    pc.dateactive = ip.dateactive
                  and    ip.rownumber = pc.rownumber
                  and    ip.positionnumber = pc.positionnumber);
        lvncountrows := sql%rowcount;
        if lvncountrows > 0 then
          begin
            commit;
            pack_import.write_log(lvncountrows || ' pack contents rows imported.');
          end;
        end if;
      end;
    end if;
    --convert packcontentsalternative
    select count(1) into lvncountrows from i_packcontentsalternative;
    if lvncountrows > 0 then
      begin
        pack_import.write_log(lvncountrows || ' pack content alternative rows in i-table.');
        --insert into packcontentsalternative
        insert into packcontentsalternative
          (packcontentsalternative_id, packcontents_id, sequencenumber, product_id,
           sizedefinition_id, systemuser_id, timestamp)
          select seq_packcontentsalternative.nextval, pc.packcontents_id, ipa.sequencenumber,
                 pa.product_id, sa.sizedefinition_id, pack_import.lvnsystemuserid, sysdate
          from   i_packcontentsalternative ipa
          join   product pack
          on     pack.code = ipa.packcode
          join   sizedefinition s
          on     s.code = ipa.sizecode
          join   finishingmethod f
          on     f.code = ipa.finishingmethodcode
          join   product pa
          on     pa.code = ipa.alternativeproductcode
          join   sizedefinition sa
          on     sa.code = ipa.alternativesizecode
          join   packcontents pc
          on     (pc.pack_id = pack.product_id and pc.packsequence = ipa.packsequence and
                 pc.sizedefinition_id = s.sizedefinition_id and
                 pc.finishingmethod_id = f.finishingmethod_id)
          and    not exists (select 1
                  from   packcontentsalternative pcx
                  where  pcx.packcontents_id = pc.packcontents_id
                  and    pcx.sequencenumber = ipa.sequencenumber);
        lvncountrows := sql%rowcount;
        if lvncountrows > 0 then
          begin
            commit;
            pack_import.write_log(lvncountrows || ' pack content alternative rows imported.');
          end;
        end if;
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('Error during pack_import_product.cfbimportpackcontent: ' ||
                              substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimportpackcontent;
  function get_sizegroupingcode(fp_sizegroupingocde sizegroupingcode.code%type)
    return sizegroupingcode.sizegroupingcode_id%type is
    lv_sizegroupingcodeid sizegroupingcode.sizegroupingcode_id%type;
    procedure insert_sizegroupingcode is
    begin
      --insert_sizegroupingcode
      insert into sizegroupingcode
        (sizegroupingcode_id, code, description, systemuser_id, timestamp)
      values
        (seq_sizegroupingcode.nextval, fp_sizegroupingocde, fp_sizegroupingocde,
         pack_import.lvnsystemuserid, sysdate)
      returning sizegroupingcode_id into lv_sizegroupingcodeid;
    end insert_sizegroupingcode;
  begin
    --get_sizegroupingcode
    if fp_sizegroupingocde is null then
      begin
        return null;
      end;
    else
      begin
        select sgc.sizegroupingcode_id
        into   lv_sizegroupingcodeid
        from   sizegroupingcode sgc
        where  sgc.code = fp_sizegroupingocde;
      exception
        when no_data_found then
          begin
            insert_sizegroupingcode;
          end;
      end;
    end if;
    return lv_sizegroupingcodeid;
  end get_sizegroupingcode;
  procedure cfbimportproduct is
    productid                     product.product_id%type;
    parentproductid               product.parentproduct_id%type;
    modelyn                       product.model%type;
    errormsgdetail                varchar2(100) := null;
    countrows                     integer;
    countproducts                 integer;
    sizetypeid                    sizetype.sizetype_id%type;
    finishingcodeid               finishingcode.finishingcode_id%type;
    emblemfontid                  emblemfont.emblemfont_id%type;
    lprovisiongroupid             provisiongroup.provisiongroup_id%type;
    ldefaultreturngrade_id        qualitygrade.qualitygrade_id%type;
    ldummypriceid                 number;
    lvndefaultsalesgradeid        product.defaultsalesgrade_id%type;
    lvndefaultmountgradeid        product.defaultmountinggrade_id%type;
    lvntreatmentcheckscheme_id    treatmentcheckscheme.treatmentcheckscheme_id%type;
    lvntreatmenttype_id           treatmenttype.treatmenttype_id%type;
    lvnexpirationcode_id          expirationcode.expirationcode_id%type;
    lvnassemblylabellayout_id     labellayout.labellayout_id%type;
    lv_defaultresidualvalschemeid residualvaluescheme.residualvaluescheme_id%type;
    lv_misproductid               misproduct.misproduct_id%type;
    lv_modificationgroupid        modificationgroup.modificationgroup_id%type;
    lv_invoicecolumn              product.invoicecolumn%type;
    procedure add_sizebillgroupperprodgroups is
      lv_countrows number := 0;
      procedure add_sizebillgroupperprodgroup(fp_sizebillinggroupcode in sizebillinggroup.code%type,
                                              fp_productgroupid       sizebillgroupperprodgroup.productgroup_id%type,
                                              fp_surchargepercentage  in sizebillgroupperprodgroup.surchargepercentage%type) is
        lv_sizebillinggroupid          sizebillgroupperprodgroup.sizebillinggroup_id%type;
        lv_sizebillgroupperprodgroupid sizebillgroupperprodgroup.sizebillgroupperprodgroup_id%type;
        lv_chk_count                   number;
        lv_productgroupcode            productgroup.code%type;
      begin
        --add_sizebillgroupperprodgroup
        lv_sizebillinggroupid := pack_import.get_sizebillinggroup(fp_sizebillinggroupcode, null);
        begin
          select max(sbg.sizebillgroupperprodgroup_id)
          into   lv_sizebillgroupperprodgroupid
          from   sizebillgroupperprodgroup sbg
          where  sbg.sizebillinggroup_id = lv_sizebillinggroupid
          and    sbg.productgroup_id = fp_productgroupid;
        exception
          when no_data_found then
            begin
              lv_sizebillgroupperprodgroupid := null;
            end;
        end;
        if lv_sizebillgroupperprodgroupid is null then
          begin
            --check already existing lines, can max be 4
            begin
              select count(1)
              into   lv_chk_count
              from   sizebillgroupperprodgroup sbg
              where  sbg.productgroup_id = fp_productgroupid;
            exception
              when no_data_found then
                begin
                  lv_chk_count := 0;
                end;
            end;
            if nvl(lv_chk_count, 0) >= 4 then
              begin
                --get productgroup code
                select pg.code
                into   lv_productgroupcode
                from   productgroup pg
                where  pg.productgroup_id = fp_productgroupid;
                --display error max 4 lines can be added
                pack_import.write_log('Error add_sizebillgroupperprodgroups; Cannot add sizebillinggroupcode ' ||
                                      fp_sizebillinggroupcode || ' to productgroup code ' ||
                                      lv_productgroupcode || ' with percentage ' ||
                                      to_char(fp_surchargepercentage) || ', because there are ' ||
                                      to_char(lv_chk_count) || ' lines already!', 3);
              end;
            else
              begin
                --insert into sizebillgroupperprodgroup
                insert into sizebillgroupperprodgroup
                  (sizebillgroupperprodgroup_id, sizebillinggroup_id, productgroup_id,
                   surchargepercentage, systemuser_id, timestamp)
                values
                  (seq_sizebillgroupperprodgroup.nextval, lv_sizebillinggroupid, fp_productgroupid,
                   fp_surchargepercentage, pack_import.lvnsystemuserid, sysdate);
                --count records added
                lv_countrows := lv_countrows + 1;
              end;
            end if;
          end;
        end if;
      end add_sizebillgroupperprodgroup;
    begin
      --add_sizebillgroupperprodgroups
      for tt in (select t.productgroup_id, t.sizebillinggroupcode1,
                        (select max(ips.surchargepercentage1)
                          from   i_product ips
                          where  ips.sizebillinggroupcode1 = t.sizebillinggroupcode1) surchargepercentage1,
                        t.sizebillinggroupcode2,
                        (select max(ips.surchargepercentage2)
                          from   i_product ips
                          where  ips.sizebillinggroupcode2 = t.sizebillinggroupcode2) surchargepercentage2,
                        t.sizebillinggroupcode3,
                        (select max(ips.surchargepercentage3)
                          from   i_product ips
                          where  ips.sizebillinggroupcode3 = t.sizebillinggroupcode3) surchargepercentage3,
                        t.sizebillinggroupcode4,
                        (select max(ips.surchargepercentage4)
                          from   i_product ips
                          where  ips.sizebillinggroupcode4 = t.sizebillinggroupcode4) surchargepercentage4
                 from   (select p.productgroup_id, a.sizebillinggroupcode1, a.sizebillinggroupcode2,
                                 a.sizebillinggroupcode3, a.sizebillinggroupcode4
                          from   i_product a
                          join   product p
                          on     p.code = a.code
                          where  (a.sizebillinggroupcode1 is not null or
                                 a.sizebillinggroupcode2 is not null or
                                 a.sizebillinggroupcode3 is not null or
                                 a.sizebillinggroupcode4 is not null)
                          group  by p.productgroup_id, a.sizebillinggroupcode1, a.sizebillinggroupcode2,
                                    a.sizebillinggroupcode3, a.sizebillinggroupcode4) t) loop
        begin
          --get_sizebillinggroup
          if tt.sizebillinggroupcode1 is not null and tt.surchargepercentage1 is not null then
            begin
              add_sizebillgroupperprodgroup(tt.sizebillinggroupcode1, tt.productgroup_id,
                                            tt.surchargepercentage1);
            end;
          end if;
          if tt.sizebillinggroupcode2 is not null and tt.surchargepercentage2 is not null then
            begin
              add_sizebillgroupperprodgroup(tt.sizebillinggroupcode2, tt.productgroup_id,
                                            tt.surchargepercentage2);
            end;
          end if;
          if tt.sizebillinggroupcode3 is not null and tt.surchargepercentage3 is not null then
            begin
              add_sizebillgroupperprodgroup(tt.sizebillinggroupcode3, tt.productgroup_id,
                                            tt.surchargepercentage3);
            end;
          end if;
          if tt.sizebillinggroupcode4 is not null and tt.surchargepercentage4 is not null then
            begin
              add_sizebillgroupperprodgroup(tt.sizebillinggroupcode4, tt.productgroup_id,
                                            tt.surchargepercentage4);
            end;
          end if;
        end;
      end loop; --tt
      if lv_countrows > 0 then
        begin
          --commit
          commit;
          pack_import.write_log(countrows || ' sizebillgroupperprodgroup(s) added');
        end;
      end if;
    end add_sizebillgroupperprodgroups;
  begin
    select count(p.product_id) into countproducts from product p;
    begin
      select max(st.value)
      into   lv_invoicecolumn
      from   systemsetting st
      where  st.name = 'GARMENTRENTCOLUMN1';
      if lv_invoicecolumn is null then
        lv_invoicecolumn := 0;
      end if;
    exception
      when others then
        lv_invoicecolumn := 0;
    end;
    -- product - insert
    countrows := 0;
    for vcursor in (select a.*, b.productgroup_id, c.color_id, d.fabric_id, e.washingprocess_id,
                           f.supplier_id, g.registrationunit_id, h.finishingmethod_id,
                           (select min(txg.taxgroup_id)
                             from   taxgroup txg
                             where  txg.code = a.taxgroupcode
                             and    txg.country_id = pack_import.lvncountrydefaultid) taxgroup_id,
                           r.productranking_id,
                           nvl((select t.turnovergroup_id
                                from   turnovergroup t
                                where  t.code = a.turnovergrouprent), b.rentturnovergroup_id) rentturnovergroup_id,
                           nvl((select t.turnovergroup_id
                                from   turnovergroup t
                                where  t.code = a.turnovergroupwash), b.washturnovergroup_id) washturnovergroup_id,
                           nvl((select t.turnovergroup_id
                                from   turnovergroup t
                                where  t.code = a.turnovergrouprepl), b.replacementturnovergroup_id) replacementturnovergroup_id,
                           nvl((select t.turnovergroup_id
                                from   turnovergroup t
                                where  t.code = a.turnovergroupsales), b.salesturnovergroup_id) salesturnovergroup_id,
                           nvl((select t.turnovergroup_id
                                from   turnovergroup t
                                where  t.code = a.turnovergrouploss), b.lossturnovergroup_id) lossturnovergroup_id,
                           nvl((select t.turnovergroup_id
                                from   turnovergroup t
                                where  t.code = a.turnovergroupadvance), b.advanceturnovergroup_id) advanceturnovergroup_id,
                           nvl((select t.turnovergroup_id
                                from   turnovergroup t
                                where  t.code = a.turnovergroupcorrections),
                                b.correctionsturnovergroup_id) correctionsturnovergroup_id,
                           nvl((select t.turnovergroup_id
                                from   turnovergroup t
                                where  t.code = a.turnovergroupwashcog), b.washcogturnovergroup_id) washcogturnovergroup_id,
                           nvl((select t.turnovergroup_id
                                from   turnovergroup t
                                where  t.code = a.turnovergrouploan), b.loanturnovergroup_id) loanturnovergroup_id,
                           nvl((select t.turnovergroup_id
                                from   turnovergroup t
                                where  t.code = a.turnovergrouprentnotret),
                                b.rentnotretturnovergroup_id) rentnotretturnovergroup_id,
                           (select psg.productsortgroup_id
                             from   productsortgroup psg
                             where  psg.code = a.productsortgroupcode) productsortgroup_id,
                           (select max(i.image_id)
                             from   image i
                             where  i.code = upper(trim(a.imagecode))
                             and    i.imagetype = 1) image_id,
                           (select mrp.mrpcode_id
                             from   mrpcode mrp
                             where  mrp.code = upper(trim(a.mrpcode))) mrpcode_id
                    from   i_product a, productgroup b, color c, fabric d, washingprocess e,
                           supplier f, registrationunit g, finishingmethod h, productranking r
                    where  a.productgroupcode = b.code
                    and    a.colorcode = c.code
                    and    a.fabriccode = d.code
                    and    a.washprocesscode = e.code
                    and    a.suppliernumber = f.suppliernumber
                    and    substr(a.registrationunitcode, 1, 3) = g.code
                    and    a.finishingmethodcode = h.code
                    and    a.productrankingprio = r.priority(+)
                    and    not exists
                     (select x.product_id from product x where a.code = x.code)
                    order  by a.parentproductcode desc) loop
      sizetypeid := sizetypeminusid;
      if vcursor.default_residualvaluescheme is null then
        lv_defaultresidualvalschemeid := null;
      else
        begin
          select residualvaluescheme_id
          into   lv_defaultresidualvalschemeid
          from   residualvaluescheme
          where  code = vcursor.default_residualvaluescheme;
        exception
          when no_data_found then
            begin
              insert into residualvaluescheme
                (residualvaluescheme_id, code, calculationweeks, systemuser_id, timestamp,
                 calculationbasis)
              values
                (seq_residualvaluescheme.nextval, vcursor.default_residualvaluescheme, 0,
                 pack_import.lvnsystemuserid, sysdate, 1)
              returning residualvaluescheme_id into lv_defaultresidualvalschemeid;
              insert into residualvaluescheme_desc
                (residualvaluescheme_id, language_id, description, systemuser_id, timestamp)
              values
                (lv_defaultresidualvalschemeid, pack_import.lvnlanguageid,
                 coalesce(vcursor.default_residualvaluesch_desc, vcursor.default_residualvaluescheme),
                 pack_import.lvnsystemuserid, sysdate);
            end;
        end;
      end if; --default_residualvaluescheme
      if vcursor.misproductcode is null then
        lv_misproductid := null;
      else
        begin
          select mp.misproduct_id
          into   lv_misproductid
          from   misproduct mp
          where  mp.code = vcursor.misproductcode;
        exception
          when no_data_found then
            begin
              insert into misproduct
                (misproduct_id, code, systemuser_id, timestamp)
              values
                (seq_misproduct.nextval, vcursor.misproductcode, pack_import.lvnsystemuserid,
                 sysdate)
              returning misproduct_id into lv_misproductid;
              insert into misproduct_desc
                (misproduct_id, language_id, description, systemuser_id, timestamp)
              values
                (lv_misproductid, pack_import.lvnlanguageid,
                 coalesce(vcursor.misproductdescription, vcursor.misproductcode),
                 pack_import.lvnsystemuserid, sysdate);
            end;
        end;
      end if; --misproduct
      if vcursor.treatmentcheckschemecode is null then
        lvntreatmentcheckscheme_id := null;
      else
        begin
          select ts.treatmentcheckscheme_id
          into   lvntreatmentcheckscheme_id
          from   treatmentcheckscheme ts
          where  ts.code = vcursor.treatmentcheckschemecode;
        exception
          when no_data_found then
            begin
              pack_import.write_log('CFbImportProduct: treatmentcheckscheme ' ||
                                    vcursor.treatmentcheckschemecode ||
                                    ' does not exist. Used for product code/description ' ||
                                    vcursor.code || '/' || vcursor.description, 2);
            end;
        end;
      end if;
      --Tatiana 23.09.2002 change defaultvalues for changesperweek and typeofrent depending on typeofmerchandise
      if vcursor.typeofmerchandise = 2 then
        changesperweek_nr := 5;
        typeofrent_nr     := 2;
      else
        changesperweek_nr := 0;
        typeofrent_nr     := 1;
      end if;
      -- select finishingcode were it exists othewise null via min(..)
      select min(finishingcode_id)
      into   finishingcodeid
      from   finishingcode f
      where  f.finishingcode = vcursor.finishingcode;
      --PVD 7 June 2006 adding parent product/model
      select min(p.product_id)
      into   parentproductid
      from   product p
      where  p.code = vcursor.parentproductcode;
      if parentproductid is null then
        modelyn := 'N';
      else
        modelyn := 'Y';
      end if;
      if vcursor.provisiongroupcode is null then
        lprovisiongroupid := null;
      else
        begin
          select min(g.provisiongroup_id)
          into   lprovisiongroupid
          from   provisiongroup g
          where  g.code = vcursor.provisiongroupcode;
        end;
      end if;
      --get default grades
      if vcursor.defaultreturngradecode is not null then
        ldefaultreturngrade_id := pack_import.getqualitygradeid(vcursor.defaultreturngradecode);
      else
        ldefaultreturngrade_id := null;
      end if;
      if vcursor.defaultsalesgradecode is null then
        lvndefaultsalesgradeid := null;
      else
        lvndefaultsalesgradeid := pack_import.getqualitygradeid(vcursor.defaultsalesgradecode);
      end if;
      if vcursor.defaultmountingordergradecode is null then
        lvndefaultmountgradeid := null;
      else
        lvndefaultmountgradeid := pack_import.getqualitygradeid(vcursor.defaultmountingordergradecode);
      end if;
      begin
        -- product
        --TNE order 500468
        errormsgdetail := '';
        -- insert
        pack_import.cfbcreate_product(productid,
                                      --fpnproduct_id,
                                      vcursor.code,
                                      --fpscode,
                                      vcursor.packingsequence,
                                      --fpnpackingsequence,
                                      vcursor.bundlequantity,
                                      --fpnpackingamount,
                                      vcursor.active,
                                      --fpsactive,
                                      'N',
                                      --fpsgarmentset,
									   case when vcursor.packtype <> 0 then 'Y' else 'N' end, --fpspack
                                      --fpspack,
                                      modelyn,
                                      --fpsmodel,
                                      vcursor.occupancyrelated,
                                      --fpsoccupancyrelated,
                                      'N',
                                      --fpsspecialsize,
                                      1,
                                      --fpnvolumeunits,
                                      vcursor.theoreticalweight,
                                      --fpntheoreticalweight,
                                      vcursor.legacycode,
                                      --fpslegacyproductcode,
                                      vcursor.fabric_id,
                                      --fpnfabric_id,
                                      vcursor.color_id,
                                      --fpncolor_id,
                                      vcursor.supplier_id,
                                      --fpnsupplier_id,
                                      sizetypeid,
                                      --fpnsizetype_id,
                                      vcursor.washingprocess_id,
                                      --fpnwashingprocess_id,
                                      vcursor.productgroup_id,
                                      --fpnproductgroup_id,
                                      null,
                                      --fpnweighingcategory_id,
                                      parentproductid,
                                      --fpnparentproduct_id,
                                      vcursor.registrationunit_id,
                                      --fpnregistrationunit_id,
                                      nvl(vcursor.soilcountmethod, 0),
                                      --fpssoilcount,
                                      vcursor.recordpassivestock,
                                      --fpsrecordpassivestock,
                                      vcursor.permitinvoiceadjust,
                                      --fpspermitinvoiceadjust,
                                      vcursor.typeofmerchandise,
                                      --fpntypeofmerchandise,
                                      vcursor.minimumturnaround,
                                      --fpnminimumturnaround,
                                      vcursor.autoreplacement,
                                      --fpnautoreplacement,
                                      vcursor.shortdescription,
                                      --fpsshortdescription,
                                      case vcursor.typeofmerchandise when 5 then 0 else
                                       lv_invoicecolumn end,
                                      --fpninvoicecolumn,
                                      vcursor.rentturnovergroup_id,
                                      --fpnrentturnovergroup_id,
                                      vcursor.washturnovergroup_id,
                                      --fpnwashturnovergroup_id,
                                      vcursor.replacementturnovergroup_id,
                                      --fpnreplacementturnovergroup_id,
                                      vcursor.salesturnovergroup_id,
                                      --fpnsalesturnovergroup_id,
                                      vcursor.image_id,
                                      --fpnimage_id,
                                      nvl(vcursor.maxwashes, 0),
                                      --fpnmaxwashes,
                                      nvl(vcursor.uniquepoolitem, 'N'),
                                      --fpsuniquepoolitem,
                                      vcursor.putuptype,
                                      --fpnputuptype,
                                      vcursor.exchangemethod,
                                      --fpnexchangemethod,
                                      vcursor.producteannumber,
                                      --fpneannumber);
                                      finishingcodeid,
                                      --fpnfinishingcode_id,
                                      vcursor.fulfillmentgroup,
                                      --fpnfulfillmentgroup
                                      nvl(vcursor.storeactivestocklocation, 'N'), lprovisiongroupid,
                                      vcursor.usegradecategorydefect, ldefaultreturngrade_id,
                                      vcursor.mountingproduct, vcursor.showonmountingorder,
                                      vcursor.showondismountingorder, vcursor.showonpicklistrsc,
                                      lvndefaultsalesgradeid, lvndefaultmountgradeid,
                                      nvl(vcursor.percentagefirstdelivery, 100),
                                      vcursor.lossturnovergroup_id, vcursor.advanceturnovergroup_id,
                                      vcursor.correctionsturnovergroup_id,
                                      vcursor.washcogturnovergroup_id, vcursor.packtype,
                                      lvntreatmentcheckscheme_id, vcursor.lotnumberrequiredyn,
                                      --fpnorpackcontentsallowed
                                      case when vcursor.packtype = 2 then 3 else 0 end,
                                      pack_import_stock.get_stockroomid(vcursor.defaultstockroom),
                                      vcursor.fixedstockroom, vcursor.productranking_id,
                                      vcursor.loanturnovergroup_id, vcursor.sizebreakdown,
                                      lv_defaultresidualvalschemeid, lv_misproductid,
                                      vcursor.confirmproductonpda, vcursor.totalpackweight,
                                      vcursor.packvolumeunits, vcursor.productsortgroup_id,
                                      vcursor.rentnotretturnovergroup_id,
                                      vcursor.customgarmentcharge,
                                      vcursor.materialmaintenanceprotection,
                                      vcursor.deliverytobillrelationship,
                                      substr(vcursor.remark, 1, 5000), vcursor.salesonly,
                                      vcursor.mrpcode_id, vcursor.mmpdefaultpercentage,
                                      vcursor.allowoneofforderingonra);
        -- create productorpack if needed
        if vcursor.packtype = 2 then
          begin
            if vcursor.treatmenttype is null then
              lvntreatmenttype_id := null;
            else
              pack_import.cfbcreate_treatmenttype(lvntreatmenttype_id, vcursor.treatmenttype);
            end if;
            if vcursor.expirationcode is null then
              lvnexpirationcode_id := null;
            else
              begin
                --select expirationcode_id
                errormsgdetail := 'expirationcode ' || vcursor.expirationcode;
                select ex.expirationcode_id
                into   lvnexpirationcode_id
                from   expirationcode ex
                where  ex.code = vcursor.expirationcode;
              end;
            end if;
            select ll.labellayout_id
            into   lvnassemblylabellayout_id
            from   labellayout ll
            where  ll.labeltype = 4
            and    ll.code = vcursor.assemblylayout;
            insert into productorpack
              (product_id, sterile, treatmenttype_id, expirationcode_id, minactivestocklevel,
               assemblylabellayout_id, systemuser_id, timestamp)
            values
              (productid, vcursor.sterile, lvntreatmenttype_id, lvnexpirationcode_id,
               vcursor.minactivestocklevel, lvnassemblylabellayout_id, pack_import.lvnsystemuserid,
               sysdate);
          end;
        end if;
        ---import emblem data when its an emblem
        if vcursor.typeofmerchandise = 4 then
          begin
            if vcursor.emblemfontdescription is not null then
              begin
                select f.emblemfont_id
                into   emblemfontid
                from   emblemfont f
                where  f.description = vcursor.emblemfontdescription;
              exception
                when no_data_found then
                  begin
                    insert into emblemfont
                      (emblemfont_id, description, active, systemuser_id, timestamp)
                    values
                      (seq_emblemfont.nextval, vcursor.emblemfontdescription, 'Y',
                       pack_import.lvnsystemuserid, sysdate)
                    returning emblemfont_id into emblemfontid;
                  end;
              end;
            else
              emblemfontid := null;
            end if;
            pack_import.cfbcreate_emblemproduct(productid, vcursor.emblemtype,
                                                pack_import_emblem.cfbdeterminecolor(vcursor.emblemtextcolor,
                                                                                      vcursor.emblemtextcolor_description),
                                                pack_import_emblem.cfbdeterminecolor(vcursor.emblembordercolor,
                                                                                      vcursor.emblembordercolor_description),
                                                emblemfontid);
          exception
            when others then
              begin
                errormsg := 'CFbImportProduct: error import emblem info for (emblem)product code/description ' ||
                            vcursor.code || '/' || vcursor.description;
                pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
              end;
          end;
        end if;
        -- product description
        insert into product_desc
          (product_id, language_id, description, longdescription, systemuser_id, timestamp)
        values
          (productid, pack_import.lvnlanguageid, vcursor.description,
           nvl(vcursor.longdescription, vcursor.description), pack_import.lvnsystemuserid, sysdate);
        -- product_link
        insert into product_link_desc
          (product_link_id, language_id, description, longdescription, systemuser_id, timestamp,
           registrationunitdescription)
        values
          (productid, pack_import.lvnlanguageid, vcursor.description,
           nvl(vcursor.longdescription, vcursor.description), pack_import.lvnsystemuserid, sysdate,
           vcursor.registrationunitdesc);
        commit;
        countrows := countrows + 1;
        -- product finishing method
        errormsgdetail := 'product finishing method for ';
        pack_import.cfbcreate_prodfinishingmethod(productid, vcursor.finishingmethod_id);
        -- product tax
        errormsgdetail := 'product tax for ';
        begin
          insert into producttax
            (product_id, country_id, taxgroup_id, systemuser_id, timestamp)
          values
            (productid, pack_import.lvncountrydefaultid, vcursor.taxgroup_id,
             pack_import.lvnsystemuserid, sysdate);
        exception
          when dup_val_on_index then
            null;
        end;
        -- general rent price
        errormsgdetail := 'rent price for ';
        --Tatiana  23.09.2002 change defaultvalues for changesperweek and typeofrent depending on typeofmerchandise
        if vcursor.defaultrentprice is not null or vcursor.defaultrentprice != 0 then
          begin
            pack_import.cfbcreate_generalrentprice(ldummypriceid, generalpricelistrentid, productid,
                                                   sizedefinitionstarid, vcursor.finishingmethod_id,
                                                   vcursor.defaultrentprice,
                                                   to_date('1-1-2001', 'DD-MM-YYYY'),
                                                   changesperweek_nr, typeofrent_nr, null);
          exception
            when dup_val_on_index then
              null;
            when others then
              errormsg := 'CFbImportProduct: Fail to import cfbcreate_generalrentprice ' ||
                          errormsgdetail || 'product code/description ' || vcursor.code || '/' ||
                          vcursor.description;
              pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
          end;
        end if;
        -- general replacement price
        errormsgdetail := 'replacement price for ';
        if vcursor.defaultreplaceprice is not null or vcursor.defaultreplaceprice != 0 then
          begin
            pack_import.cfbcreate_genreplacementprice(ldummypriceid, generalpricelistreplid,
                                                      productid, sizedefinitionstarid,
                                                      vcursor.defaultreplaceprice,
                                                      to_date('1-1-2001', 'DD-MM-YYYY'),null);
          exception
            when dup_val_on_index then
              null;
            when others then
              errormsg := 'CFbImportProduct: Fail to import cfbcreate_genreplacementprice ' ||
                          errormsgdetail || 'product code/description ' || vcursor.code || '/' ||
                          vcursor.description;
              pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
          end;
        end if;
        -- general sales price
        errormsgdetail := 'sales price for ';
        if vcursor.defaultsalesprice is not null or vcursor.defaultsalesprice != 0 then
          begin
            pack_import.cfbcreate_generalsalesprice(ldummypriceid, generalpricelistsalesid,
                                                    productid, sizedefinitionstarid,
                                                    vcursor.defaultsalesprice,
                                                    to_date('1-1-2001', 'DD-MM-YYYY'),1,null);
          exception
            when dup_val_on_index then
              null;
            when others then
              errormsg := 'CFbImportProduct: Fail to import cfbcreate_generalsalesprice ' ||
                          errormsgdetail || 'product code/description ' || vcursor.code || '/' ||
                          vcursor.description;
              pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
          end;
        end if;
        -- product finishing method charge
        errormsgdetail := 'special charge for ';
        if vcursor.specchargeapplicable = 'Y' then
          begin
            create_specialcharge;
            begin
              insert into productfinishingmethodcharge
                (product_id, finishingmethod_id, specialcharge_id, systemuser_id, timestamp)
              values
                (productid, vcursor.finishingmethod_id, specialchargeid,
                 pack_import.lvnsystemuserid, sysdate);
            exception
              when dup_val_on_index then
                null;
              when others then
                errormsg := 'CFbImportProduct: Fail to import productfinishingmethodcharge ' ||
                            errormsgdetail || 'product code/description ' || vcursor.code || '/' ||
                            vcursor.description;
                pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
            end;
          end;
        end if;
        --convert product modification groups
        if vcursor.modificationgroup1 is not null then
          begin
            errormsg := 'modificationgroup1 ' || vcursor.modificationgroup1;
            select mdg.modificationgroup_id
            into   lv_modificationgroupid
            from   modificationgroup mdg
            where  mdg.code = vcursor.modificationgroup1;
            insert into productmodificationgroup
              (product_id, modificationgroup_id, sequencenumber, systemuser_id, timestamp)
            values
              (productid, lv_modificationgroupid, 1, pack_import.lvnsystemuserid, sysdate);
          exception
            when dup_val_on_index then
              null; --already exists
          end;
        end if;
        if vcursor.modificationgroup2 is not null then
          begin
            errormsg := 'modificationgroup2 ' || vcursor.modificationgroup2;
            select mdg.modificationgroup_id
            into   lv_modificationgroupid
            from   modificationgroup mdg
            where  mdg.code = vcursor.modificationgroup2;
            insert into productmodificationgroup
              (product_id, modificationgroup_id, sequencenumber, systemuser_id, timestamp)
            values
              (productid, lv_modificationgroupid, 2, pack_import.lvnsystemuserid, sysdate);
          exception
            when dup_val_on_index then
              null; --already exists
          end;
        end if;
        if vcursor.modificationgroup3 is not null then
          begin
            errormsg := 'modificationgroup3 ' || vcursor.modificationgroup3;
            select mdg.modificationgroup_id
            into   lv_modificationgroupid
            from   modificationgroup mdg
            where  mdg.code = vcursor.modificationgroup3;
            insert into productmodificationgroup
              (product_id, modificationgroup_id, sequencenumber, systemuser_id, timestamp)
            values
              (productid, lv_modificationgroupid, 3, pack_import.lvnsystemuserid, sysdate);
          exception
            when dup_val_on_index then
              null; --already exists
          end;
        end if;
        if (vcursor.cabinet_type is not null or vcursor.productbarcode is not null or
           vcursor.secondaryproductbarcode is not null) then
          begin
            insert into productuniqueitemservice
              (product_id, type, productbarcode, systemuser_id, timestamp, secondaryproductbarcode)
            values
              (productid, nvl(vcursor.cabinet_type, 1), vcursor.productbarcode,
               pack_import.lvnsystemuserid, sysdate, vcursor.secondaryproductbarcode);
          exception
            when dup_val_on_index then
              null; --already exists
          end;
        end if;
        commit;
      exception
        when dup_val_on_index then
          null;
        when others then
          begin
            rollback;
            errormsg := 'CFbImportProduct: Fail to import ' || errormsgdetail ||
                        ' product code/description ' || vcursor.code || '/' || vcursor.description;
            pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
          end;
      end;
    end loop;
    begin
      -- Fix to add packingdepartments by default.
      insert into packingdepartmentdefinition
        (productgroup_id, plant_id, plantdepartment_id, systemuser_id, timestamp,
         soilreceiveplantdepartment_id)
        select g.productgroup_id, p.plant_id,
               (select min(d.plantdepartment_id)
                 from   plantdepartment d
                 where  d.plant_id = p.plant_id
                 and    d.defaultplantdepartment = 'Y'), g.systemuser_id, sysdate, null
        from   plant p, productgroup g
        where  exists (select d.plantdepartment_id
                from   plantdepartment d
                where  d.plant_id = p.plant_id
                and    d.defaultplantdepartment = 'Y')
        and    not exists (select x.plantdepartment_id, x.productgroup_id
                from   packingdepartmentdefinition x
                where  x.productgroup_id = g.productgroup_id
                and    x.plant_id = p.plant_id);
    exception
      when others then
        errormsg := 'CFbImportProduct: add packingdepartments by default. ';
        pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
    end;
    commit;
    begin
      ---color usefor emblems update
      update color c
      set    c.usedforemblem = 'Y'
      where  c.usedforemblem = 'N'
      and    exists (select p.product_id
              from   i_product i, product p
              where  i.code = p.code
              and    p.typeofmerchandise = 4
              and    i.colorcode = c.code);
    exception
      when others then
        pack_import.write_log(' cfbimportproduct fail to update usedforemblem for colors ' ||
                              substr(sqlerrm, 1, 512), 3);
    end;
    begin
      ---color usefor emblems fabric update
      update fabric f
      set    f.usedforemblem = 'Y'
      where  f.usedforemblem = 'N'
      and    exists (select p.product_id
              from   i_product i, product p
              where  i.code = p.code
              and    p.typeofmerchandise = 4
              and    i.fabriccode = f.code);
    exception
      when others then
        pack_import.write_log(' cfbimportproduct fail to update usedforemblem for fabrics ' ||
                              substr(sqlerrm, 1, 512), 3);
    end;
    commit;
    --p_update_productgroup_turn
    p_update_productgroup_turn;
    --cfbimportpackcontent
    cfbimportpackcontent;
    --add_sizebillgroupperprodgroups
    add_sizebillgroupperprodgroups;
    --Write logs
    if countrows > 0 then
      begin
        pack_import.write_log(countproducts || ' products already existed.');
        select count(p.code) into countproducts from i_product p;
        pack_import.write_log(countproducts || ' in i_product.');
        pack_import.write_log(countrows || ' product rows imported.');
        select count(p.product_id) into countproducts from product p;
        pack_import.write_log(countproducts || ' now in product.');
      end;
    end if;
  end;
  procedure cfbimportproductsize is
    countrows           integer;
    sizetypeid          sizetype.sizetype_id%type;
    sizeid              sizedefinition.sizedefinition_id%type;
    lsizebillinggroupid sizedefinition.sizebillinggroup_id%type;
    lsizegroupingcodeid sizegroupingcode.sizegroupingcode_id%type;
    lprovisiongroupid   provisiongroup.provisiongroup_id%type;
    lgeneralrentpriceid generalrentprice.generalrentprice_id%type;
    lgeneralreplpriceid generalreplacementprice.generalreplacementprice_id%type;
    lgeneralsalepriceid generalsalesprice.generalsalesprice_id%type;
    procedure update_prodzise is
    begin
      --update_prodzise
      if pack_import.lvdbcustomercode <> 'SMG' then
        begin
          --update product specialsize
          update product p
          set    p.specialsize = 'Y'
          where  p.specialsize <> 'Y'
          and    p.timestamp > (sysdate - 2 / 24)
          and    exists (select 1
                  from   i_productsize ips
                  where  ips.productcode = p.code
                  and    ips.specialsize = 'Y');
          countrows := sql%rowcount;
          if countrows > 0 then
            begin
              --commit
              commit;
              pack_import.write_log(countrows || ' products updated to specialsize = Y');
              countrows := 0;
            end;
          end if;
        end;
      end if;
      ---size usefor emblems update
      update sizedefinition s
      set    s.usedforemblem = 'Y'
      where  s.usedforemblem = 'N'
      and    exists (select p.product_id
              from   i_productsize i, product p
              where  i.productcode = p.code
              and    p.typeofmerchandise = 4
              and    i.sizecode = s.code);
      countrows := sql%rowcount;
      if countrows > 0 then
        begin
          --commit
          commit;
          pack_import.write_log(countrows || ' sizedefinition updated usedforemblem = Y');
        end;
      end if;
    exception
      when others then
        pack_import.write_log(' cfbimportproductsize failed update_prodzise usedforemblem/specialsize for sizes ' ||
                              substr(sqlerrm, 1, 512), 3);
    end update_prodzise;
    procedure add_sizes is
    begin
      --add_sizes
      countrows := 0;
      for x in (select s.sizecode, max(s.description) description,
                       max(substr(s.legacycode, 1, 6)) legacycode, max(s.useforemblems) useforemblems,
                       max(s.width) width, max(s.length) length,
                       max(s.default_sizebillgroup_for_size) default_sizebillgroup_for_size,
                       max(s.sizegroupingcode) sizegroupingcode
                from   i_productsize s
                where  not exists
                 (select sizedefinition_id from sizedefinition where code = sizecode)
                group  by s.sizecode) loop
        begin
          --get_sizebillinggroup
          lsizebillinggroupid := pack_import.get_sizebillinggroup(x.default_sizebillgroup_for_size, 'Y');
          --get_sizegroupingcode
          lsizegroupingcodeid := get_sizegroupingcode(x.sizegroupingcode);
          --cfbcreate_sizedefinition/desc
          pack_import.cfbcreate_sizedefinition(sizeid, x.sizecode, 'N', x.legacycode, x.width,
                                               x.length, x.useforemblems, lsizebillinggroupid,
                                               lsizegroupingcodeid);
          pack_import.cfbcreate_sizedefinition_desc(sizeid, nvl(x.description, x.sizecode));
          countrows := countrows + 1;
        exception
          when dup_val_on_index then
            null;
          when others then
            pack_import.write_log('CFbImportProductSize.add_sizes: Fail to import size definition code/description ' ||
                                  x.sizecode || '/' || x.description || ' ' ||
                                  substr(sqlerrm, 1, 512), 3);
        end;
      end loop;
      if countrows > 0 then
        begin
          commit;
          pack_import.write_log(countrows || ' size definition rows imported.');
          lsizebillinggroupid := null;
          countrows           := 0;
        end;
      end if;
    end add_sizes;
  begin
    --update_prodsize
    update_prodzise;
    --add_sizes;
    add_sizes;
    -- sizes per size type, product size
    for vcursor in (select p.product_id, p.typeofmerchandise, p.packingamount,
                           nvl(a.theoreticalweight, p.theoreticalweight) theoreticalweight,
                           p.productgroup_id, s.sizedefinition_id, a.sizegroupcode, a.sizecode,
                           a.productcode, a.defaultrentprice, a.defaultreplaceprice,
                           a.defaultsalesprice, a.legacycode, a.description, a.sizegroupdescription,
                           a.provisiongroupcode, a.maxcartqty, a.specialsize, a.standardlength,
                           a.sizebillinggroupcode
                    from   i_productsize a
                    join   product p
                    on     p.code = a.productcode
                    join   sizedefinition s
                    on     s.code = a.sizecode
                    where  ((pack_import.lvdbcustomercode = 'WMU') or not exists
                            (select 1
                             from   productsize ps
                             where  ps.product_id = p.product_id
                             and    ps.sizedefinition_id = s.sizedefinition_id))
                    order  by a.productcode, a.sequencenumber, a.sizecode) loop
      begin
        select p.sizetype_id
        into   sizetypeid
        from   sizetype p
        where  p.code = vcursor.sizegroupcode
        and    p.usagetype = 1;
      exception
        when no_data_found then
          insert into sizetype
            (sizetype_id, code, systemuser_id, timestamp)
          values
            (seq_sizetype.nextval, vcursor.sizegroupcode, pack_import.lvnsystemuserid, sysdate)
          returning sizetype_id into sizetypeid;
          insert into sizetype_desc
            (sizetype_id, language_id, description, systemuser_id, timestamp)
          values
            (sizetypeid, pack_import.lvnlanguageid, vcursor.sizegroupdescription,
             pack_import.lvnsystemuserid, sysdate);
      end;
      -- update productsize
      update product p
      set    p.sizetype_id = sizetypeid
      where  p.product_id = vcursor.product_id
      and    p.timestamp > (sysdate - 2 / 24)
      and    p.sizetype_id <> sizetypeid;
      --Tatiana 23.09.2002 change defaultvalues for changesperweek and typeofrent depending on typeofmerchandise
      if vcursor.typeofmerchandise = 2 then
        changesperweek_nr := 5;
        typeofrent_nr     := 2;
      else
        changesperweek_nr := 0;
        typeofrent_nr     := 1;
      end if;
      -- sizespersizetype
      pack_import.cfbcreate_sizespersizetype(vcursor.sizedefinition_id, sizetypeid);
      -- product size
      begin
        if vcursor.provisiongroupcode is null then
          lprovisiongroupid := null;
        else
          begin
            select min(g.provisiongroup_id)
            into   lprovisiongroupid
            from   provisiongroup g
            where  g.code = vcursor.provisiongroupcode;
          end;
        end if;
        --get_sizebillinggroup
        lsizebillinggroupid := pack_import.get_sizebillinggroup(vcursor.sizebillinggroupcode, null);
        pack_import.cfbcreate_productsize(vcursor.product_id, vcursor.sizedefinition_id,
                                          vcursor.specialsize, vcursor.packingamount,
                                          vcursor.theoreticalweight, lprovisiongroupid,
                                          vcursor.maxcartqty, vcursor.standardlength,
                                          lsizebillinggroupid);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'CFbImportProductSize: Fail to import product size for product/sizedefinition ' ||
                      vcursor.productcode || '/' || vcursor.sizecode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
      -- general rent price
      if vcursor.defaultrentprice is not null then
        begin
          for zz in (select pf.finishingmethod_id
                     from   productfinishingmethod pf
                     where  pf.product_id = vcursor.product_id) loop
            begin
              pack_import.cfbcreate_generalrentprice(lgeneralrentpriceid, generalpricelistrentid,
                                                     vcursor.product_id, vcursor.sizedefinition_id,
                                                     zz.finishingmethod_id, vcursor.defaultrentprice,
                                                     to_date('1-1-2001', 'DD-MM-YYYY'),
                                                     changesperweek_nr, typeofrent_nr,lsizebillinggroupid);
            exception
              when dup_val_on_index then
                update generalrentprice
                set    price = vcursor.defaultrentprice
                where  generalpricelist_id = generalpricelistrentid
                and    product_id = vcursor.product_id
                and    sizedefinition_id = vcursor.sizedefinition_id
                and    finishingmethod_id = zz.finishingmethod_id
                and    startdate = to_date('1-1-2001', 'DD-MM-YYYY')
                and    changesperweek = changesperweek_nr
                and    typeofrent = typeofrent_nr;
            end;
          end loop; --zz
        end;
      end if;
      -- general replacement price
      if vcursor.defaultreplaceprice is not null then
        begin
          pack_import.cfbcreate_genreplacementprice(lgeneralreplpriceid, generalpricelistreplid,
                                                    vcursor.product_id, vcursor.sizedefinition_id,
                                                    vcursor.defaultreplaceprice,
                                                    to_date('1-1-2001', 'DD-MM-YYYY'),lsizebillinggroupid);
        exception
          when dup_val_on_index then
            update generalreplacementprice
            set    price = vcursor.defaultreplaceprice
            where  generalpricelist_id = generalpricelistreplid
            and    product_id = vcursor.product_id
            and    sizedefinition_id = vcursor.sizedefinition_id
            and    startdate = to_date('1-1-2001', 'DD-MM-YYYY');
        end;
      end if;
      -- general sales price
      if vcursor.defaultsalesprice is not null then
        begin
          pack_import.cfbcreate_generalsalesprice(lgeneralsalepriceid, generalpricelistsalesid,
                                                  vcursor.product_id, vcursor.sizedefinition_id,
                                                  vcursor.defaultsalesprice,
                                                  to_date('1-1-2001', 'DD-MM-YYYY'),1,lsizebillinggroupid);
        exception
          when dup_val_on_index then
            update generalsalesprice
            set    price = vcursor.defaultsalesprice
            where  generalpricelist_id = generalpricelistsalesid
            and    product_id = vcursor.product_id
            and    sizedefinition_id = vcursor.sizedefinition_id
            and    startdate = to_date('1-1-2001', 'DD-MM-YYYY');
        end;
      end if;
    end loop;
    --commit
    commit;
    if countrows > 0 then
      begin
        pack_import.write_log(countrows || ' product size rows processed.');
      end;
    end if;
  end cfbimportproductsize;
  procedure cfbimportemblemproduct is
    colorminusid              color.color_id%type;
    fabricminusid             fabric.fabric_id%type;
    placementminusid          placement.placement_id%type;
    templatepantsid           emblemtemplate.emblemtemplate_id%type;
    templateshirtsid          emblemtemplate.emblemtemplate_id%type;
    emblemtemplatelineid      emblemtemplateline.emblemtemplateline_id%type;
    emblemtemplatelinepriceid emblemtemplatelineprice.emblemtemplatelineprice_id%type;
  begin
    begin
      select color_id into colorminusid from color where code = '-';
    exception
      when no_data_found then
        begin
          pack_import.cfbcreate_color(colorminusid, '-', null, 'N');
          pack_import.cfbcreate_color_desc(colorminusid, '-');
        end;
    end;
    begin
      select fabric_id into fabricminusid from fabric where code = '-';
    exception
      when no_data_found then
        begin
          pack_import.cfbcreate_fabric(fabricminusid, '-', 'N');
          pack_import.cfbcreate_fabric_desc(fabricminusid, '-');
        end;
    end;
    begin
      select placement_id into placementminusid from placement where code = '-';
    exception
      when no_data_found then
        insert into placement
          (placement_id, code, systemuser_id, timestamp)
        values
          (seq_placement.nextval, '-', pack_import.lvnsystemuserid, sysdate)
        returning placement_id into placementminusid;
        insert into placement_desc
          (placement_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_placement.currval, pack_import.lvnlanguageid, '-', pack_import.lvnsystemuserid,
           sysdate);
    end;
    -- emblem product
    for x in (select a.product_id
              from   product a, i_emblem b
              where  a.code = b.code
              and    a.timestamp > (sysdate - 2 / 24)
              and    not exists
               (select e.product_id from emblemproduct e where e.product_id = a.product_id)
              group  by a.product_id
              union all
              select t.product_id
              from   product t
              where  t.typeofmerchandise = 4
              and    not exists
               (select e.product_id from emblemproduct e where e.product_id = t.product_id)
              group  by t.product_id) loop
      begin
        update product
        set    typeofmerchandise = 4
        where  product_id = x.product_id
        and    typeofmerchandise <> 4
        and    timestamp > (sysdate - 2 / 24);
        pack_import.cfbcreate_emblemproduct(x.product_id, 3, colorminusid, colorminusid, null);
      exception
        when dup_val_on_index then
          null;
        when others then
          pack_import.write_log('Failed to insert into emblem product when type of merchandise is an emblem ' ||
                                substr(sqlerrm, 1, 512), 3);
      end;
    end loop;
    -- emblem template
    for vcursor in (select a.customer_id, c.product_id, b.price, a.dateactive
                    from   customer a, i_emblem b, product c
                    where  a.customernumber = b.customernumber
                    and    c.code = b.code) loop
      -- PANTS
      begin
        select emblemtemplate_id
        into   templatepantsid
        from   emblemtemplate
        where  code = 'PANTS'
        and    customer_id = vcursor.customer_id;
      exception
        when no_data_found then
          begin
            pack_import.cfbcreate_emblemtemplate(templatepantsid, vcursor.customer_id, 'PANTS',
                                                 'Pants', 'N', 'Y', 'Y');
          end;
      end;
      begin
        pack_import.cfbcreate_emblemtemplateline(emblemtemplatelineid, templatepantsid,
                                                 vcursor.product_id, sizedefinitionminusid, 8, '-',
                                                 colorminusid, colorminusid, colorminusid,
                                                 fabricminusid, placementminusid, 3, 1, 1, null,
                                                 null, null);
        pack_import.cfbcreate_emblemtemplineprice(emblemtemplatelinepriceid, emblemtemplatelineid,
                                                  vcursor.price, vcursor.dateactive);
      exception
        when dup_val_on_index then
          update emblemtemplatelineprice
          set    price = vcursor.price
          where  emblemtemplateline_id = emblemtemplatelineid
          and    startdate = vcursor.dateactive;
      end;
      -- SHIRTS
      begin
        select emblemtemplate_id
        into   templateshirtsid
        from   emblemtemplate
        where  code = 'SHIRTS'
        and    customer_id = vcursor.customer_id;
      exception
        when no_data_found then
          pack_import.cfbcreate_emblemtemplate(templateshirtsid, vcursor.customer_id, 'SHIRTS',
                                               'Shirts', 'N', 'Y', 'Y');
      end;
      begin
        pack_import.cfbcreate_emblemtemplateline(emblemtemplatelineid, templateshirtsid,
                                                 vcursor.product_id, sizedefinitionminusid, 8, '-',
                                                 colorminusid, colorminusid, colorminusid,
                                                 fabricminusid, placementminusid, 3, 1, 1, null,
                                                 null, null);
        pack_import.cfbcreate_emblemtemplineprice(emblemtemplatelinepriceid, emblemtemplatelineid,
                                                  vcursor.price, vcursor.dateactive);
      exception
        when dup_val_on_index then
          update emblemtemplatelineprice
          set    price = vcursor.price
          where  emblemtemplateline_id = emblemtemplatelineid
          and    startdate = vcursor.dateactive;
      end;
    end loop;
  end cfbimportemblemproduct;
  procedure add_missing_default_prodsize is
    lv_countrows number;
  begin
    --add_missing_default_prodsize
    if pack_import.lvdbcustomercode <> 'SMG' then
      begin
        -- for products that are not in i_productsize.csv
        -- insert into productsize: '-' for non-garments and '*' for garments
        -- non-garments
        insert into productsize
          (product_id, sizedefinition_id, sequencenumber, specialsize, packingamount,
           theoreticalweight, systemuser_id, timestamp)
          select a.product_id, sizedefinitionminusid, 1, 'N', a.packingamount, a.theoreticalweight,
                 pack_import.lvnsystemuserid, sysdate
          from   product a
          where  a.typeofmerchandise <> 2
          and    not exists
           (select x.product_id from productsize x where x.product_id = a.product_id);
        lv_countrows := sql%rowcount;
        if lv_countrows > 0 then
          begin
            --commit
            commit;
            pack_import.write_log(lv_countrows || ' default productsize minus(es) added');
          end;
        end if;
        -- garments
        insert into productsize
          (product_id, sizedefinition_id, sequencenumber, specialsize, packingamount,
           theoreticalweight, systemuser_id, timestamp)
          select a.product_id, sizedefinitionstarid, 1, 'N', a.packingamount, a.theoreticalweight,
                 pack_import.lvnsystemuserid, sysdate
          from   product a
          where  a.typeofmerchandise = 2
          and    not exists
           (select x.product_id from productsize x where x.product_id = a.product_id);
        lv_countrows := sql%rowcount;
        if lv_countrows > 0 then
          begin
            --commit
            commit;
            pack_import.write_log(lv_countrows || ' default productsize star(s) added');
          end;
        end if;
      end;
    end if;
  exception
    when dup_val_on_index then
      null;
  end add_missing_default_prodsize;
  procedure addmissingproductsize is
    lv_counter number := 0;
  begin
    -- add missing productsizes
    for x in (select u.product_id, u.sizedefinition_id
              from   wearerinventory u
              where  not exists (select *
                      from   productsize s
                      where  s.product_id = u.product_id
                      and    s.sizedefinition_id = u.sizedefinition_id)
              group  by u.product_id, u.sizedefinition_id) loop
      begin
        pack_import.cfbcreate_productsize(x.product_id, x.sizedefinition_id, 'N', 1, 0, null);
        lv_counter := lv_counter + 1;
      end;
    end loop;
    for x in (select u.product_id, u.sizedefinition_id
              from   uniqueitem u
              where  not exists (select *
                      from   productsize s
                      where  s.product_id = u.product_id
                      and    s.sizedefinition_id = u.sizedefinition_id)
              group  by u.product_id, u.sizedefinition_id) loop
      begin
        pack_import.cfbcreate_productsize(x.product_id, x.sizedefinition_id, 'N', 1, 0, null);
        lv_counter := lv_counter + 1;
      end;
    end loop;
    for x in (select u.product_id, u.sizedefinition_id
              from   productlistpercustomer u
              where  not exists (select *
                      from   productsize s
                      where  s.product_id = u.product_id
                      and    s.sizedefinition_id = u.sizedefinition_id)
              group  by u.product_id, u.sizedefinition_id) loop
      begin
        pack_import.cfbcreate_productsize(x.product_id, x.sizedefinition_id, 'N', 1, 0, null);
        lv_counter := lv_counter + 1;
      end;
    end loop;
    for x in (select u.product_id, u.sizedefinition_id
              from   productlistperdistribpoint u
              where  not exists (select *
                      from   productsize s
                      where  s.product_id = u.product_id
                      and    s.sizedefinition_id = u.sizedefinition_id)
              group  by u.product_id, u.sizedefinition_id) loop
      begin
        pack_import.cfbcreate_productsize(x.product_id, x.sizedefinition_id, 'N', 1, 0, null);
        lv_counter := lv_counter + 1;
      end;
    end loop;
    if lv_counter > 0 then
      begin
        commit;
        pack_import.write_log('Added ' || lv_counter || ' productsize(s)!');
      end;
    end if;
    --add_missing_default_prodsize
    add_missing_default_prodsize;
  exception
    when others then
      rollback;
      pack_import.write_log('addmissingproductsize Error: ' || substr(sqlerrm, 1, 512), 3);
  end addmissingproductsize;
  procedure add_alternativesizes is
    lv_sizeid      sizedefinition.sizedefinition_id%type;
    lv_alt_sizeid  sizedefinition.sizedefinition_id%type;
    lv_unf_sizeid  sizedefinition.sizedefinition_id%type;
    lv_description sizedefinition_desc.description%type;
    lv_message     abslog.message%type;
    lv_count       number := 0;
    lv_sizecount   number := 0;
    errorcount     number := 0;
    lv_sizetypeid  sizetype.sizetype_id%type;
  begin
    --add sizetypes
    for y in (select z.sizetype
              from   (select s.size_type sizetype
                       from   i_alternativesizes s
                       where  s.size_type is not null
                       group  by s.size_type) z
              where  not exists (select 1 from sizetype f where f.code = z.sizetype)) loop
      begin
        insert into sizetype
          (sizetype_id, code, systemuser_id, timestamp)
        values
          (seq_sizetype.nextval, y.sizetype, pack_import.lvnsystemuserid, sysdate)
        returning sizetype_id into lv_sizetypeid;
        insert into sizetype_desc
          (sizetype_id, language_id, description, systemuser_id, timestamp)
        values
          (lv_sizetypeid, pack_import.lvnlanguageid, y.sizetype, pack_import.lvnsystemuserid,
           sysdate);
      end;
    end loop; --y
    --add_alternativesizes
    for x in (select iz.sizecode, iz.alternativesizecode, nvl(iz.sequence, 1) sequence,
                     ta.sizetype_id, iz.unfinishedsizecode,
                     nvl(iz.description, iz.sizecode) description
              from   i_alternativesizes iz
              left   outer join sizetype ta
              on     ta.code = iz.size_type
              where  not exists
               (select 1
                      from   alternativesizedefinition al, sizedefinition h, sizedefinition l
                      where  al.sizedefinition_id = h.sizedefinition_id
                      and    al.alternativesizedefinition_id = l.sizedefinition_id
                      and    h.code = iz.sizecode
                      and    l.code = iz.alternativesizecode)) loop
      begin
        --get size id's
        begin
          lv_message := ' size code ' || x.sizecode;
          select s.sizedefinition_id
          into   lv_sizeid
          from   sizedefinition s
          where  s.code = x.sizecode;
        exception
          when no_data_found then
            begin
              pack_import.cfbcreate_sizedefinition(lv_sizeid, x.sizecode, 'N', null, null, null,
                                                   'N');
              pack_import.cfbcreate_sizedefinition_desc(lv_sizeid, x.description);
              lv_sizecount := lv_sizecount + 1;
            end;
        end;
        --add sizetypes
        if x.sizetype_id is not null then
          begin
            pack_import.cfbcreate_sizespersizetype(lv_sizeid, x.sizetype_id);
          end;
        end if;
        if x.alternativesizecode is null then
          lv_alt_sizeid := null;
        else
          begin
            lv_message := ' alternative size code ' || x.alternativesizecode;
            select s.sizedefinition_id
            into   lv_alt_sizeid
            from   sizedefinition s
            where  s.code = x.alternativesizecode;
          exception
            when no_data_found then
              begin
                begin
                  select max(it.description)
                  into   lv_description
                  from   i_alternativesizes it
                  where  it.sizecode = x.alternativesizecode;
                exception
                  when no_data_found then
                    lv_description := x.alternativesizecode;
                end;
                pack_import.cfbcreate_sizedefinition(lv_alt_sizeid, x.alternativesizecode, 'N',
                                                     null, null, null, 'N');
                pack_import.cfbcreate_sizedefinition_desc(lv_alt_sizeid,
                                                          nvl(lv_description, x.alternativesizecode));
                lv_sizecount := lv_sizecount + 1;
              end;
          end;
          --add sizetypes
          if x.sizetype_id is not null and lv_alt_sizeid is not null then
            begin
              pack_import.cfbcreate_sizespersizetype(lv_alt_sizeid, x.sizetype_id);
            end;
          end if;
        end if; --x.alternativesizecode
        if x.unfinishedsizecode is null then
          lv_unf_sizeid := null;
        else
          begin
            lv_message := ' unfinished size code ' || x.unfinishedsizecode;
            select s.sizedefinition_id
            into   lv_unf_sizeid
            from   sizedefinition s
            where  s.code = x.unfinishedsizecode;
          exception
            when no_data_found then
              begin
                begin
                  select max(it.description)
                  into   lv_description
                  from   i_alternativesizes it
                  where  it.sizecode = x.unfinishedsizecode;
                exception
                  when no_data_found then
                    lv_description := x.unfinishedsizecode;
                end;
                pack_import.cfbcreate_sizedefinition(lv_unf_sizeid, x.unfinishedsizecode, 'Y', null,
                                                     null, null, 'N');
                pack_import.cfbcreate_sizedefinition_desc(lv_unf_sizeid,
                                                          nvl(lv_description, x.unfinishedsizecode));
                lv_sizecount := lv_sizecount + 1;
              end;
          end;
          --link unfinished size
          update sizedefinition s
          set    s.unfinishedlength = 'N', s.unfinishedsizedefinition_id = lv_unf_sizeid
          where  s.sizedefinition_id = lv_sizeid;
          --add sizetypes
          if x.sizetype_id is not null and lv_unf_sizeid is not null then
            begin
              pack_import.cfbcreate_sizespersizetype(lv_unf_sizeid, x.sizetype_id);
            end;
          end if;
        end if;
        if lv_alt_sizeid is not null then
          begin
            --insert into alternativesizedefinition
            lv_message := ' insert into alternativesizedefinition size ' || x.sizecode ||
                          ' alt.size ' || x.alternativesizecode;
            insert into alternativesizedefinition
              (sizedefinition_id, alternativesizedefinition_id, sequencenumber, systemuser_id,
               timestamp)
            values
              (lv_sizeid, lv_alt_sizeid, x.sequence, pack_import.lvnsystemuserid, sysdate);
            update sizedefinition s
            set    s.reservealternativesize = 'Y'
            where  s.reservealternativesize <> 'Y'
            and    s.sizedefinition_id = lv_sizeid;
            lv_count := lv_count + 1;
          exception
            when dup_val_on_index then
              begin
                null; --no problem already ok
              end;
          end;
        end if;
      exception
        when no_data_found then
          begin
            errorcount := errorcount + 1;
            pack_import.write_log('Error during add_alternativesizes ' || lv_message ||
                                  ' not found', 3);
          end;
        when others then
          begin
            errorcount := errorcount + 1;
            pack_import.write_log('Error during add_alternativesizes ' || lv_message ||
                                  ' exception others see debug info ', 3);
            pack_import.write_log('Error during add_alternativesizes exception others ' || sqlerrm,
                                  5);
          end;
      end;
    end loop; --x
    commit;
    if errorcount > 0 then
      begin
        pack_import.write_log('Add_alternativesizes ' || to_char(errorcount) ||
                              ' errors during import from i_alternativesizes', 3);
      end;
    end if; --errorcount
    if lv_sizecount > 0 then
      begin
        pack_import.write_log('Add_alternativesizes succesfully imported ' ||
                              to_char(lv_sizecount) || ' sizes from i_alternativesizes');
      end;
    end if; --lv_sizecount
    if lv_count > 0 then
      begin
        pack_import.write_log('Add_alternativesizes succesfully imported ' || to_char(lv_count) ||
                              ' records from i_alternativesizes');
      end;
    end if; --lv_count
  end add_alternativesizes;
begin
  if pack_import.lvnsalesjournalgroupminusid is null then
    begin
      pack_import.cfbimportplantfixedinfo;
    end;
  end if;
  create_turnovergroups;
  cfbimportproductfixedinfo;
exception
  when others then
    pack_import.write_log('cfbimportproductfixedinfo Error: ' || substr(sqlerrm, 1, 512), 3);
end pack_import_product;
/
create or replace package pack_import_productsizeconv is
  /****************************************\
  * Conversion of the i-tables             *
  * I_PRODUCTCONVERSIONSIZE                *
  * I_WEARERINVENTORY PHASE-IN PART        *
  *   --version 3.01                       *
  \****************************************/
  procedure import_productconversionsize;
  procedure import_phaseoutwearerinventory;
  procedure phaseout;
end pack_import_productsizeconv;
/
create or replace package body pack_import_productsizeconv is
  gv_message varchar2(512);
  procedure import_productconversionsize is
    lv_counter                 number := 0;
    lv_customerid              customer.customer_id%type;
    lv_customerselection       productconversion.customerselection%type;
    lv_sourceproductid         product.product_id%type;
    lv_destinationproductid    product.product_id%type;
    lv_destinationsizeid       sizedefinition.sizedefinition_id%type;
    lv_destinationplpcid       productlistpercustomer.productlistpercustomer_id%type;
    lv_productconversionid     productconversion.productconversion_id%type;
    lv_productconversionlineid productconversionline.productconversionline_id%type;
    lv_totalcount              number;
  begin
    --total count i_productconversionsize
    gv_message := 'total count i_productconversionsize';
    select count(1)
    into   lv_totalcount
    from   (select 1
             from   i_productconversionsize i
             group  by i.customernumber, i.sourceproductcode, i.destinationproductcode) xx;
    --import_productconversionsize
    for x in (select i.customernumber, i.sourceproductcode, i.destinationproductcode,
                     trunc(min(i.startdate)) startdate
              from   i_productconversionsize i
              group  by i.customernumber, i.sourceproductcode, i.destinationproductcode) loop
      begin
        --get customer number
        gv_message := to_char(x.customernumber) || ' customer number ';
        --customer selection 0 = Customer, 1 = Debtor, 2 = Master Account
        select c.customer_id,
               case
                 when masteraccount = 2 and c.customer_id = c.masteraccount_id then
                  2
                 else
                  0
               end
        into   lv_customerid, lv_customerselection
        from   customer c
        where  c.customernumber = x.customernumber;
        --get source product
        gv_message := x.sourceproductcode || ' source product code ';
        select p.product_id
        into   lv_sourceproductid
        from   product p
        where  p.code = x.sourceproductcode;
        --get destination product
        gv_message := x.destinationproductcode || ' destination product code ';
        select p.product_id
        into   lv_destinationproductid
        from   product p
        where  p.code = x.destinationproductcode;
        --
        begin
          --insert into productconversion
          gv_message := 'select productconversion';
          select pc.productconversion_id
          into   lv_productconversionid
          from   productconversion pc
          where  pc.customer_link_id = lv_customerid
          and    pc.sourceproduct_id = lv_sourceproductid
          and    pc.destinationproduct_id = lv_destinationproductid
          and    pc.destinationemblemtemplate_id is null;
        exception
          when no_data_found then
            begin
              --insert into productconversion
              gv_message := 'insert into productconversion';
              insert into productconversion
                (productconversion_id, sourceproduct_id, startdate, status, systemuser_id,
                 timestamp, customer_link_id, customerselection, destinationproduct_id,
                 destinationemblemtemplate_id)
              values
                (seq_productconversion.nextval, lv_sourceproductid, x.startdate, 1,
                 pack_import.lvnsystemuserid, sysdate, lv_customerid, lv_customerselection,
                 lv_destinationproductid, null)
              returning productconversion_id into lv_productconversionid;
            end;
        end;
        --go through all PLPC lines for customer / product that are active at start date or after that
        for jvd in (select l.*
                    from   productlistpercustomer l
                    where  l.customer_id = lv_customerid
                    and    l.product_id = lv_destinationproductid
                    and    (x.startdate between l.dateactive and l.dateinactive or
                          x.startdate < l.dateactive)) loop
          begin
            begin
              --get destination PLPC
              gv_message := 'source PLPC for customer ' || to_char(x.customernumber) || ' product ' ||
                            x.destinationproductcode || ' on date ' ||
                            to_char(jvd.dateactive, 'dd-mm-yyyy');
              select l.productlistpercustomer_id
              into   lv_destinationplpcid
              from   productlistpercustomer l
              where  l.customer_id = lv_customerid
              and    l.product_id = lv_destinationproductid
              and    l.sizedefinition_id = lv_destinationsizeid
              and    l.finishingmethod_id = jvd.finishingmethod_id
              and    (jvd.dateactive between l.dateactive and l.dateinactive);
            exception
              when no_data_found then
                begin
                  --check with size *
                  gv_message := 'source PLPC for customer ' || to_char(x.customernumber) ||
                                ' product ' || x.destinationproductcode ||
                                ' for size star on date ' || to_char(jvd.dateactive, 'dd-mm-yyyy');
                  select l.productlistpercustomer_id
                  into   lv_destinationplpcid
                  from   productlistpercustomer l
                  where  l.customer_id = lv_customerid
                  and    l.product_id = lv_destinationproductid
                  and    l.sizedefinition_id =
                         (select s.sizedefinition_id from sizedefinition s where s.code = '*')
                  and    l.finishingmethod_id = jvd.finishingmethod_id
                  and    (jvd.dateactive between l.dateactive and l.dateinactive);
                end;
            end;
            begin
              --select pcl.productconversionline_id
              gv_message := 'select pcl.productconversionline_id';
              select pcl.productconversionline_id
              into   lv_productconversionlineid
              from   productconversionline pcl
              where  pcl.productconversion_id = lv_productconversionid
              and    pcl.sourceplpc_id = jvd.productlistpercustomer_id
              and    pcl.destinationplpc_id = lv_destinationplpcid;
            exception
              when no_data_found then
                begin
                  --insert into productconversionline
                  gv_message := 'insert into productconversionline';
                  insert into productconversionline
                    (productconversionline_id, productconversion_id, sourceplpc_id,
                     destinationplpc_id, systemuser_id, timestamp)
                  values
                    (seq_productconversionline.nextval, lv_productconversionid,
                     jvd.productlistpercustomer_id, lv_destinationplpcid,
                     pack_import.lvnsystemuserid, sysdate)
                  returning productconversionline_id into lv_productconversionlineid;
                end;
            end;
          end;
        end loop; --jvd
        --add conversion size records!
        --add missing productconversionsize records
        for jajvd in (select i.destinationsizecode, sd.sizedefinition_id destsize_id,
                             i.sourcesizecode, ss.sizedefinition_id sourcesize_id
                      from   i_productconversionsize i
                      join   sizedefinition ss
                      on     ss.code = i.sourcesizecode
                      join   sizedefinition sd
                      on     sd.code = i.destinationsizecode
                      where  i.customernumber = x.customernumber
                      and    i.sourceproductcode = x.sourceproductcode
                      and    i.destinationproductcode = x.destinationproductcode
                      and    ss.code <> '*'
                      and    sd.code <> '*') loop
          begin
            --check if source product/size exists!
            gv_message := 'source product ' || x.sourceproductcode || ' size ' ||
                          jajvd.sourcesizecode;
            select psy.sizedefinition_id
            into   lv_destinationsizeid
            from   productsize psy
            where  psy.product_id = lv_sourceproductid
            and    psy.sizedefinition_id = jajvd.sourcesize_id;
            --check if dest product/size exists!
            gv_message := 'destination product ' || x.destinationproductcode || ' size ' ||
                          jajvd.destinationsizecode;
            select psy.sizedefinition_id
            into   lv_destinationsizeid
            from   productsize psy
            where  psy.product_id = lv_destinationproductid
            and    psy.sizedefinition_id = jajvd.destsize_id;
            --insert into productconversionsize
            gv_message := 'insert into productconversionsize source prod. ' || x.sourceproductcode ||
                          ' source size ' || jajvd.sourcesizecode || ' dest.prod. ' ||
                          x.destinationproductcode || ' dest.size ' || jajvd.destinationsizecode;
            insert into productconversionsize
              (productconversionsize_id, productconversion_id, sourcesizedefinition_id,
               destinationsizedefinition_id, systemuser_id, timestamp)
            values
              (seq_productconversionsize.nextval, lv_productconversionid, jajvd.sourcesize_id,
               jajvd.destsize_id, pack_import.lvnsystemuserid, sysdate);
          end;
        end loop;
        --commit
        commit;
        lv_counter := lv_counter + 1;
      exception
        when no_data_found then
          begin
            rollback;
            pack_import.write_log(gv_message || ' does not exists.', 3);
          end;
        when others then
          begin
            rollback;
            pack_import.write_log(gv_message || ' ' || substr(sqlerrm, 1, 512), 5);
          end;
      end;
    end loop; --x
    --logging
    if lv_totalcount > 0 then
      begin
        pack_import.write_log(lv_totalcount || ' rows in the table i_productconversionsize');
        if lv_counter > 0 then
          begin
            pack_import.write_log(lv_counter ||
                                  ' i_productconversionsize rows succesfully (re)processed');
          end;
        end if;
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        gv_message := 'pack_import_productsizeconv.import_productconversionsize: Failed to import.';
        pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 5);
      end;
  end import_productconversionsize;
  procedure import_phaseoutwearerinventory is
    lv_counter                  number := 0;
    lv_customerid               customer.customer_id%type;
    lv_customerselection        productconversion.customerselection%type;
    lv_sourceproductid          product.product_id%type;
    lv_destinationproductid     product.product_id%type;
    lv_sourcesizeid             sizedefinition.sizedefinition_id%type;
    lv_destinationsizeid        sizedefinition.sizedefinition_id%type;
    lv_productconversionid      productconversion.productconversion_id%type;
    lv_productconversionsizeid  productconversionsize.productconversionsize_id%type;
    lv_weareremploymentid       weareremployment.weareremployment_id%type;
    lv_wearerinventoryid        wearerinventory.wearerinventory_id%type;
    lv_phaseinwearerinventoryid wearerinventory.wearerinventory_id%type;
  begin
    --insert into phaseoutwearerinventory records
    for y in (select *
              from   i_wearerinventory i
              where  i.phasein_productcode is not null
              and    i.phasein_sizecode is not null
              and    i.phasein_dateactive_wil is not null) loop
      begin
        --fill variable so it can be updated if needed
        lv_wearerinventoryid := y.wearerinventory_id;
        --get customer number
        gv_message := to_char(y.customernumber) || ' customer number ';
        --customer selection 0 = Customer, 1 = Debtor, 2 = Master Account
        select c.customer_id,
               case
                 when masteraccount = 2 and c.customer_id = c.masteraccount_id then
                  2
                 else
                  0
               end
        into   lv_customerid, lv_customerselection
        from   customer c
        where  c.customernumber = y.customernumber;
        --get source product
        gv_message := y.productcode || ' source product code ';
        select p.product_id into lv_sourceproductid from product p where p.code = y.productcode;
        --get destination product
        gv_message := y.phasein_productcode || ' destination (phase in) product code ';
        select p.product_id
        into   lv_destinationproductid
        from   product p
        where  p.code = y.phasein_productcode;
        --get source size
        gv_message := y.sizecode || ' source size code ';
        select s.sizedefinition_id
        into   lv_sourcesizeid
        from   sizedefinition s
        where  s.code = y.sizecode;
        --get destination size
        gv_message := y.phasein_sizecode || ' destination (phase in) size code ';
        select s.sizedefinition_id
        into   lv_destinationsizeid
        from   sizedefinition s
        where  s.code = y.phasein_sizecode;
        --insert into productconversion
        gv_message := 'select productconversion for customer ' || to_char(y.customernumber) ||
                      ' wearer ' || y.wearernumber || ' phase in product ' || y.phasein_productcode ||
                      ' source product ' || y.productcode || ' from or earlier then ' ||
                      nvl(y.phasein_dateactive_wil, sysdate);
        select pc.productconversion_id, pos.productconversionsize_id
        into   lv_productconversionid, lv_productconversionsizeid
        from   productconversion pc
        left   outer join productconversionsize pos
        on     (pos.productconversion_id = pc.productconversion_id and
               pos.sourcesizedefinition_id = lv_sourcesizeid and
               pos.destinationsizedefinition_id = lv_destinationsizeid)
        where  pc.customer_link_id = lv_customerid
        and    pc.sourceproduct_id = lv_sourceproductid
        and    pc.destinationproduct_id = lv_destinationproductid
        and    pc.startdate <= trunc(nvl(y.phasein_dateactive_wil, sysdate))
        and    pc.destinationemblemtemplate_id is null;
        if lv_wearerinventoryid is not null then
          begin
            --select weareremployment
            gv_message := 'select weareremployment for wearerinventory_id ' ||
                          nvl(to_char(lv_wearerinventoryid), 'NULL');
            select wi.weareremployment_id
            into   lv_weareremploymentid
            from   wearerinventory wi
            where  wi.wearerinventory_id = lv_wearerinventoryid;
          end;
        else
          begin
            --get wearerer employment and inventory
            gv_message := 'customer/wearer (employment): ' || to_char(y.customernumber) || '/' ||
                          to_char(y.wearernumber) || ' employment number ' ||
                          nvl(y.weareremploymentnumber, 1);
            select we.weareremployment_id
            into   lv_weareremploymentid
            from   weareremployment we
            where  we.sequencenumber = nvl(y.weareremploymentnumber, 1)
            and    we.wearer_id =
                   (select w.wearer_id
                     from   wearer w
                     where  w.wearernumber = y.wearernumber
                     and    w.customer_id =
                            (select c.customer_id
                              from   customer c
                              where  c.customernumber = y.customernumber));
            --get wearer inventory
            gv_message := 'customer/wearer (inventory): ' || to_char(y.customernumber) || '/' ||
                          to_char(y.wearernumber) || ' product ' || y.productcode || ' size ' ||
                          y.sizecode || ' employment number ' || nvl(y.weareremploymentnumber, 1);
            select wi.wearerinventory_id
            into   lv_wearerinventoryid
            from   wearerinventory wi
            where  wi.weareremployment_id = lv_weareremploymentid
            and    wi.product_id = lv_sourceproductid
            and    wi.sizedefinition_id = lv_sourcesizeid;
          end;
        end if;
        begin
          --select lv_phaseinwearerinventoryid
          --PRODUCT_ID, SIZEDEFINITION_ID, WEAREREMPLOYMENT_ID
          gv_message := 'select phase in wearerinventory for customer ' ||
                        to_char(y.customernumber) || ' phase in product ' || y.phasein_productcode ||
                        ' phase in size ' || y.phasein_sizecode || ' wearer employment ' ||
                        y.weareremploymentnumber;
          select wi.wearerinventory_id
          into   lv_phaseinwearerinventoryid
          from   wearerinventory wi
          where  wi.weareremployment_id = lv_weareremploymentid
          and    wi.product_id = lv_destinationproductid
          and    wi.sizedefinition_id = lv_destinationsizeid;
          --start correcting
          --the max inventory must be equal to the circulating inventory
          gv_message := 'correct the phase in wearerinventory for customer ' ||
                        to_char(y.customernumber) || ' phase in product ' || y.phasein_productcode ||
                        ' phase in size ' || y.phasein_sizecode || ' wearer employment ' ||
                        y.weareremploymentnumber;
          update wearerinventory wi
          set    wi.maxinventory = wi.circinventory, wi.systemuser_id = pack_import.lvnsystemuserid,
                 wi.timestamp = sysdate
          where  wi.wearerinventory_id = lv_phaseinwearerinventoryid;
        exception
          when no_data_found then
            begin
              --insert into wearerinventory
              gv_message := 'insert into wearerinventory for customer ' ||
                            to_char(y.customernumber) || ' phase in product ' ||
                            y.phasein_productcode || ' phase in size ' || y.phasein_sizecode ||
                            ' wearer employment ' || y.weareremploymentnumber;
              select seq_wearerinventory.nextval into lv_phaseinwearerinventoryid from dual;
              insert into wearerinventory
                (wearerinventory_id, weareremployment_id, product_id, sizedefinition_id,
                 finishingmethod_id, emblemtemplate_id, specialgrade_id, maxinventory,
                 freeofchargeqty, circinventory, changesperweek, systemuser_id, timestamp,
                 maxfreeofcharge, dateactive, dateinactive, swingsuitstatus, season_id, returnedqty,
                 qtytobereturnedreplacement, qtytobereturneddecreasemax, temporaryrentstopstartdate,
                 temporaryrentstopenddate, remark, dispensecredit, personalizedgarment,
                 losschargedate, losschargeinvoiceline_id, issuedquit, selectflagreturn,
                 wearerinvoicecategory_id)
                select lv_phaseinwearerinventoryid, wi.weareremployment_id, lv_destinationproductid,
                       lv_destinationsizeid, wi.finishingmethod_id, wi.emblemtemplate_id,
                       wi.specialgrade_id, 0, wi.freeofchargeqty, 0, wi.changesperweek,
                       pack_import.lvnsystemuserid, sysdate, wi.maxfreeofcharge,
                       y.phasein_dateactive_wil, wi.dateinactive, wi.swingsuitstatus, wi.season_id,
                       wi.returnedqty, wi.qtytobereturnedreplacement, wi.qtytobereturneddecreasemax,
                       wi.temporaryrentstopstartdate, wi.temporaryrentstopenddate, wi.remark,
                       wi.dispensecredit, wi.personalizedgarment, wi.losschargedate,
                       wi.losschargeinvoiceline_id, wi.issuedquit, wi.selectflagreturn,
                       wi.wearerinvoicecategory_id
                from   wearerinventory wi
                where  wi.wearerinventory_id = lv_wearerinventoryid;
            end;
        end;
        begin
          --insert into phaseoutwearerinventory
          gv_message := 'insert into phaseoutwearerinventory for wearer inventory ' ||
                        lv_wearerinventoryid || ' paseinwearerinventory id ' ||
                        lv_phaseinwearerinventoryid;
          insert into phaseoutwearerinventory
            (phaseoutwearerinventory_id, phaseinwearerinventory_id, systemuser_id, timestamp,
             productconversionsize_id)
          values
            (lv_wearerinventoryid, lv_phaseinwearerinventoryid, pack_import.lvnsystemuserid,
             sysdate, lv_productconversionsizeid);
        exception
          when dup_val_on_index then
            null;
        end;
        --insert into productconvwrinventory
        gv_message := 'insert into productconvwrinventory for product conversion ' ||
                      lv_productconversionid || ' wearer inventory id ' || lv_wearerinventoryid;
        begin
          insert into productconvwrinventory
            (productconvwrinventory_id, productconversion_id, wearerinventory_id,
             destinationwisizedefinition_id, destinationwiemblemtemplate_id, systemuser_id,
             timestamp)
          values
            (seq_productconvwrinventory.nextval, lv_productconversionid, lv_wearerinventoryid,
             lv_destinationsizeid, null, pack_import.lvnsystemuserid, sysdate);
        exception
          when dup_val_on_index then
            null;
        end;
        --commit
        commit;
        lv_counter := lv_counter + 1;
      exception
        when no_data_found then
          begin
            rollback;
            pack_import.write_log(gv_message || ' does not exists.', 3);
          end;
        when others then
          begin
            rollback;
            pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 5);
          end;
      end;
    end loop; --y
    if lv_counter > 0 then
      begin
        pack_import.write_log(lv_counter || ' phaseoutwearerinventory rows succesfully processed');
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        gv_message := 'pack_import_productsizeconv.import_phaseoutwearerinventory: Failed to import.';
        pack_import.write_log(gv_message || substr(sqlerrm, 1, 512), 5);
      end;
  end import_phaseoutwearerinventory;
  procedure phaseout is
  begin
    import_productconversionsize;
    import_phaseoutwearerinventory;
  end phaseout;
end pack_import_productsizeconv;
/
create or replace package pack_import_purchaseorder is
  -- Author  : JVL
  -- Created : 12-july-2016
  -- Version : 1.0
  -- Purpose : Create purchaseorder header and lines.
  -- Updated : ABS-139491 PO conversion, check if exists
  procedure cfbimportpurchaseorder;
end pack_import_purchaseorder;
/
create or replace package body pack_import_purchaseorder is
  procedure cfbimportpurchaseorder is
    lvnerrormsg     varchar2(1000);
    lvcounter       number := 0;
    lvlinecounter   number := 0;
    lv_poheaderid   number;
    lv_stockroom_id stockroom.stockroom_id%type;
    lv_status_id    status.status_id%type;
    lv_cust_id      customer.customer_id%type;
    lv_currency_id  currency.currency_id%type;
    lv_orderprio_id orderpriority.orderpriority_id%type;
    fpnqualitygradeid qualitygrade.qualitygrade_id%type;
  begin
    lvcounter := 0;
    select min(op.orderpriority_id)
      into lv_orderprio_id
      from orderpriority op;
    -- inserting purchaseorders.
    for x in (select i.purchaseordernumber,
                     s.supplier_id,
                     b.businessunit_id,
                     i.stockroomcode,
                     i.orderdate,
                     i.requesteddate,
                     i.status,
                     i.ordertype,
                     i.purchaseordertype,
                     i.origin,
                     i.priority,
                     i.confirmeddate,
                     i.customernumber,
                     i.approvaldate,
                     i.currencycode,
                     i.orderamount,
                     i.remark,
                     i.processedtoworkorder,
                     i.exportdate,
                     i.exportbatchnumber
                from I_PURCHASEORDERHEADER i, supplier s, businessunit b
               where s.suppliernumber = i.suppliernumber
                 and b.code = i.businessunitcode) loop
      begin
        lv_stockroom_id := null;
        if x.stockroomcode is not null then
          lvnerrormsg := 'cfbimportpurchaseorder get stock room code ' ||
                         nvl(x.stockroomcode, 'NULL');
          begin
            select s.stockroom_id
              into lv_stockroom_id
              from stockroom s
             where s.code = x.stockroomcode;
          exception
            when no_data_found then
              begin
                lv_stockroom_id := null;
                pack_import.write_log('  stockroom' || x.stockroomcode ||
                                      ' not found ' ||
                                      ' for purchaseorder ' ||
                                      x.purchaseordernumber);
              end;
          end;
        end if;
        lv_cust_id := null;
        if x.customernumber is not null then
          lvnerrormsg := 'cfbimportpurchaseorder get customernumber ' ||
                         nvl(x.customernumber, 'NULL');
          begin
            select c.customer_id
              into lv_cust_id
              from customer c
             where c.customernumber = x.customernumber;
          exception
            when no_data_found then
              begin
                lv_cust_id := null;
                pack_import.write_log('  customer' || x.customernumber ||
                                      ' not found ' ||
                                      ' for purchaseorder ' ||
                                      x.purchaseordernumber);
              end;
          end;
        end if;
        lvnerrormsg := 'cfbimportpurchaseorder select status';
        if x.status is null then
          x.status := 5;
        end if;
        select s.status_id
          into lv_status_id
          from STATUS s
         where s.statustype = 'PO'
           and s.code = lpad(x.status, 2, 0);
        lvnerrormsg := 'cfbimportpurchaseorder select currency';
        select cc.currency_id
          into lv_currency_id
          from currency cc
         where cc.code = x.currencycode;
        lvnerrormsg := 'cfbimportpurchaseorder insert into purchaseorder';
        --insert
        insert into purchaseorderheader
          (purchaseorderheader_id,
           purchaseordernumber,
           supplier_id,
           businessunit_id,
           stockroom_id,
           orderdate,
           requesteddate,
           status_id,
           ordertype,
           exportdate,
           exportbatchnumber,
           confirmeddate,
           customer_link_id,
           systemuser_id,
           timestamp,
           approvaldate,
           approvaluser_id,
           exportuser_id,
           confirmeduser_id,
           firstreceivingdate,
           lastreceivingdate,
           currency_id,
           origin,
           canceldate,
           orderamount,
           orderuser_id,
           remark,
           purchaseordertype,
           priority,
           executedby,
           allowphaseddelivery,
           orderpriority_id,
           creationbusinessunit_id)
        values
          (seq_purchaseorderheader.nextval,
           x.purchaseordernumber,
           x.supplier_id,
           x.businessunit_id,
           lv_stockroom_id,
           x.orderdate,
           x.requesteddate,
           lv_status_id,
           x.ordertype,
           x.exportdate,
           x.exportbatchnumber,
           x.confirmeddate,
           lv_cust_id,
           pack_import.lvnsystemuserid,
           sysdate,
           x.approvaldate,
           pack_import.lvnsystemuserid,
           pack_import.lvnsystemuserid,
           pack_import.lvnsystemuserid,
           sysdate,
           sysdate,
           lv_currency_id,
           x.origin,
           to_date('31-12-2099', 'dd-mm-yyyy'),
           x.orderamount,
           pack_import.lvnsystemuserid,
           x.remark,
           x.purchaseordertype,
           x.priority,
           1,
           'N',
           lv_orderprio_id,
           x.businessunit_id)
        returning purchaseorderheader_id into lv_poheaderid;
        lvcounter := lvcounter + 1;
        lvnerrormsg := 'cfbimportpurchaseorderline loop i_purchaseorderline';
        for y in (select   p.product_id,
                           s.sizedefinition_id,
                           il.requestedgrade,
                           il.quantityordered,
                           il.quantitycancelled,
                           il.quantityconfirmed,
                           il.purchaseprice,
                           il.confirmeddate,
                           il.remark,
                           il.uniqueitem
                      from i_purchaseorderline il,
                           product             p,
                           sizedefinition      s
                     where p.code = il.productcode
                       and s.code = il.sizecode
                       and il.purchaseordernumber = x.purchaseordernumber) loop
            begin
              --get qualitygrade
              lvnerrormsg := 'cfbimportpurchaseorderline get qualitygrade ' ||
                             nvl(y.requestedgrade, 'NULL');
              select q.qualitygrade_id
                into fpnqualitygradeid
                from qualitygrade q
               where q.code = y.requestedgrade;
              --insert purchaseorderline
              lvnerrormsg := 'cfbimportworkorderline insert workorderline';
               insert into purchaseorderline
                (purchaseorderline_id,
                 purchaseorderheader_id,
                 product_link_id,
                 sizedefinition_link_id,
                 quantityordered,
                 quantityreceived,
                 quantitycancelled,
                 systemuser_id,
                 timestamp,
                 quantityorderedstock,
                 quantityordereddirectissue,
                 quantityreceiveddirectissue,
                 purchaseprice,
                 confirmeddate,
                 uniqueitem,
                 requestedgrade_id,
                 remark)
              values
                (seq_purchaseorderline.nextval,
                 lv_poheaderid,
                 y.product_id,
                 y.sizedefinition_id,
                 y.quantityordered,
                 0,
                 y.quantitycancelled,
                 pack_import.lvnsystemuserid,
                 sysdate,
                 y.quantityordered,
                 0,
                 0,
                 y.purchaseprice,
                 y.confirmeddate,
                 y.uniqueitem,
                 fpnqualitygradeid,
                 y.remark);
              lvlinecounter := lvlinecounter + 1;
            end;
          end loop;
      end;
    end loop;
    commit;
    if lvcounter > 0 then
      pack_import.write_log(lvcounter || ' purchaseorders imported.');
      if lvlinecounter > 0 then
        pack_import.write_log(lvcounter || 'purchaseorderlines imported.');
      end if;
    end if;
  exception
    when others then
      begin
        rollback;
        lvnerrormsg := 'CFbImportPurchaseOrder: Fail to import.' ||
                       lvnerrormsg;
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimportpurchaseorder;
end pack_import_purchaseorder;
/
create or replace package pack_import_residential is
  -- Author  : PVD
  -- Created : 14-Dec-2005
  -- Version : 1.2 increase departmentroom.sequencenumber when inserting departmentroom
  -- Purpose : Import residential csv files into ABSSolute
  procedure import_custresidentialsettings;
  procedure import_residentialplpc;
  procedure import_client;
  procedure import_uniqueresitem;
  procedure convert_i_nobudgetclient;
end pack_import_residential;
/
create or replace package body pack_import_residential is
  --Private variable declarations
  lerrormsg varchar2(512);
  function import_flag(pflagcode flag.code%type, pflagdescription flag_desc.description%type)
    return flag.flag_id%type is
    lflag_id flag.flag_id%type;
  begin
    begin
      --determine the right flag
      select flag_id
      into   lflag_id
      from   flag
      where  code = pflagcode
      and    flagtype = 4;
    exception
      when no_data_found then
        begin
          --when it does not exist, insert the flag
          pack_import.cfbcreate_flag(lflag_id, 4, pflagcode, 1, 'ff 0 0', 'Y', null, 'Y', 'N', null,
                                     'N');
          pack_import.cfbcreate_flag_desc(lflag_id, pflagdescription);
        exception
          when others then
            begin
              lerrormsg := 'Error adding flag: ' || pflagcode || ' ';
              pack_import.write_log(lerrormsg || substr(sqlerrm, 1, 512), 3);
            end;
        end;
    end;
    return lflag_id;
  exception
    when others then
      begin
        lerrormsg := 'Error adding flag: ' || pflagcode || ' ';
        pack_import.write_log(lerrormsg || substr(sqlerrm, 1, 512), 3);
        return null;
      end;
  end import_flag;
  procedure import_custresidentialsettings is
    lcounter                   number := 0;
    lcustomerid                customer.customer_id%type;
    llabellayoutid             labellayout.labellayout_id%type;
    lclientdelnoteformlayoutid formlayout.formlayout_id%type;
    lclientinvoiceformlayoutid formlayout.formlayout_id%type;
    ldeliverynotelayoutid      formlayout.formlayout_id%type;
    lprintpriceondelnote       customerresidentialsettings.printpriceondelnote%type;
    procedure addresidentialdeliverydays(fp_customerid     in customer.customer_id%type,
                                         fp_customernumber in customer.customernumber%type,
                                         fp_monday         in varchar2,
                                         fp_tuesday        in varchar2,
                                         fp_wednesday      in varchar2,
                                         fp_thursday       in varchar2,
                                         fp_friday         in varchar2,
                                         fp_saterday       in varchar2,
                                         fp_sunday         in varchar2) is
      procedure insert_tom5_delday(fp_dayid in number) is
      begin
        --insert_tom5_delday
        insert into customerdeliveryday
          (customer_id, day_id, timestamp, systemuser_id, deliverytype, typeofmerchadise)
        values
          (fp_customerid, fp_dayid, sysdate, pack_import.lvnsystemuserid, 'D', 5);
        --check if del day tom=1 exists, if not create it
        pack_import.add_check_customerdeliveryday(fp_customerid, fp_dayid, 'D', 1);
      end insert_tom5_delday;
    begin
      --addresidentialdeliverydays for the different days from i_customerresidentialsettings
      if fp_monday = 'Y' then
        insert_tom5_delday(1);
      end if;
      if fp_tuesday = 'Y' then
        insert_tom5_delday(2);
      end if;
      if fp_wednesday = 'Y' then
        insert_tom5_delday(3);
      end if;
      if fp_thursday = 'Y' then
        insert_tom5_delday(4);
      end if;
      if fp_friday = 'Y' then
        insert_tom5_delday(5);
      end if;
      if fp_saterday = 'Y' then
        insert_tom5_delday(6);
      end if;
      if fp_sunday = 'Y' then
        insert_tom5_delday(7);
      end if;
    exception
      when dup_val_on_index then
        null; --no problem is already there
      when others then
        begin
          pack_import.write_log(' Warning error during insert into customerdeliveryday for residential customer ' ||
                                to_char(fp_customernumber) || ', ' || substr(sqlerrm, 1, 512), 2);
        end;
    end addresidentialdeliverydays;
  begin
    pack_import.write_log('Start import_custresidentialsettings');
    for x in (select *
              from   i_customerresidentialsettings i
              where  not exists (select s.customer_id
                      from   customerresidentialsettings s, customer c
                      where  s.customer_id = c.customer_id
                      and    c.customernumber = i.customernumber)) loop
      begin
        --customer
        lerrormsg := ' customer ' || x.customernumber;
        select c.customer_id
        into   lcustomerid
        from   customer c
        where  c.customernumber = x.customernumber;
        --customerlabelprice
        if x.customerlabelprice is not null then
          begin
            lerrormsg := 'insert into customerlabellayoutprice customerlabelprice ';
            insert into customerlabellayoutprice
              (customerlabellayoutprice_id, labeltype, customer_id, price, startdate, systemuser_id,
               timestamp)
            values
              (seq_customerlabellayoutprice.nextval, 3, lcustomerid, x.customerlabelprice,
               trunc(sysdate) - 1, pack_import.lvnsystemuserid, sysdate);
          exception
            when dup_val_on_index then
              begin
                lerrormsg := 'Error adding customerlabelprice into customerlabellayoutprice, price already exists';
                pack_import.write_log(lerrormsg, 3);
              end;
          end;
        end if;
        --customerpatchprice
        if x.customerpatchprice is not null then
          begin
            lerrormsg := 'insert into customerlabellayoutprice customerpatchprice ';
            insert into customerlabellayoutprice
              (customerlabellayoutprice_id, labeltype, customer_id, price, startdate, systemuser_id,
               timestamp)
            values
              (seq_customerlabellayoutprice.nextval, 5, lcustomerid, x.customerpatchprice,
               trunc(sysdate) - 1, pack_import.lvnsystemuserid, sysdate);
          exception
            when dup_val_on_index then
              begin
                lerrormsg := 'Error adding customerpatchprice into customerlabellayoutprice, price already exists';
                pack_import.write_log(lerrormsg, 3);
              end;
          end;
        end if;
        --labellayout
        begin
          lerrormsg := ' error with labellayout ' || x.labellayout;
          select l.labellayout_id
          into   llabellayoutid
          from   labellayout l
          where  l.code = x.labellayout
          and    l.labeltype = 3;
        exception
          when no_data_found then
            begin
              --insert labellayout
              select seq_labellayout.nextval into llabellayoutid from dual;
              insert into labellayout
                (labellayout_id, code, description, labeltype, defaultlayout, systemuser_id,
                 timestamp, layoutreceiveonstock)
              values
                (llabellayoutid, x.labellayout, x.labellayoutdescription, 3, 'N',
                 pack_import.lvnsystemuserid, sysdate, 'N');
            exception
              when others then
                begin
                  lerrormsg := 'Error adding labellayout: ' || x.labellayout || ' ';
                  pack_import.write_log(lerrormsg || substr(sqlerrm, 1, 512), 3);
                end;
            end;
        end;
        --clientdelnoteformlayout
        begin
          lerrormsg := ' error with formlayout/delnoteformlayout (DC) ' || x.delnoteformlayout;
          select f.formlayout_id
          into   lclientdelnoteformlayoutid
          from   formlayout f
          where  f.formtype = 'DC'
          and    f.code = x.delnoteformlayout;
        exception
          when no_data_found then
            begin
              --insert clientdelnoteformlayout
              pack_import.cbcreate_formlayout(lclientdelnoteformlayoutid, 'DC', x.delnoteformlayout,
                                              null, 'N', x.delnoteformlayout);
            exception
              when others then
                begin
                  lerrormsg := 'Error adding formlayout (DC): ' || x.delnoteformlayout || ' ';
                  pack_import.write_log(lerrormsg || substr(sqlerrm, 1, 512), 3);
                end;
            end;
        end;
        --clientinvoiceformlayout
        begin
          lerrormsg := ' error with formlayout/clientinvoiceformlayout (IC) ' ||
                       x.clientinvoiceformlayout;
          select f.formlayout_id
          into   lclientinvoiceformlayoutid
          from   formlayout f
          where  f.formtype = 'IC'
          and    f.code = x.clientinvoiceformlayout;
        exception
          when no_data_found then
            begin
              pack_import.cbcreate_formlayout(lclientinvoiceformlayoutid, 'IC',
                                              x.clientinvoiceformlayout, null, 'N',
                                              x.clientinvoiceformlayout);
            exception
              when others then
                begin
                  lerrormsg := 'Error adding formlayout (IC): ' || x.clientinvoiceformlayout || ' ';
                  pack_import.write_log(lerrormsg || substr(sqlerrm, 1, 512), 3);
                end;
            end;
        end;
        if x.printpriceondelnote = 'Y' then
          lprintpriceondelnote := 1;
        else
          lprintpriceondelnote := 0;
        end if;
        if x.deliverynotelayout is null then
          ldeliverynotelayoutid := null;
        else
          --deliverynotelayout
          begin
            lerrormsg := ' error with formlayout/deliverynotelayout (DN) ' || x.deliverynotelayout;
            select f.formlayout_id
            into   ldeliverynotelayoutid
            from   formlayout f
            where  f.formtype = 'DN'
            and    f.code = x.deliverynotelayout;
          exception
            when no_data_found then
              begin
                --insert clientdelnoteformlayout
                pack_import.cbcreate_formlayout(ldeliverynotelayoutid, 'DN', x.deliverynotelayout,
                                                null, 'N', x.deliverynotelayout);
              exception
                when others then
                  begin
                    lerrormsg := 'Error adding deliverynotelayout (DN): ' || x.deliverynotelayout || ' ';
                    pack_import.write_log(lerrormsg || substr(sqlerrm, 1, 512), 3);
                  end;
              end;
          end;
        end if;
        begin
          --insert customerresidentialsettings
          lerrormsg := ' insert customerresidentialsettings ';
          insert into customerresidentialsettings
            (customer_id, customerclients, labellayout_id, firsttimefreeofchargelabels, remark,
             printstickeratpackingstation, printlatepieces, systemuser_id, timestamp,
             inscanbulkallowed, acceptallproduct, acceptotherclients, presortcustomer, sortorder,
             outscanbulk, returnitems, printqtyreceived, printidcode, printpriceondelnote,
             clientdelnoteformlayout_id, clientinvoiceformlayout_id, outscansort,
             printclientdeliverynote, deliverynotelayout_id)
          values
            (lcustomerid, x.customerclients, llabellayoutid, x.firsttimefreeofchargelabels,
             x.remark, x.printstickersatpackingstation, x.printlatepieces,
             pack_import.lvnsystemuserid, sysdate, x.inscanbulkallowed, x.acceptallproducts,
             x.acceptotherclients, x.resortcustomer, x.sortorder, x.outscanbulk, x.returnitems,
             x.printqtyreceived, x.printidcode, lprintpriceondelnote, lclientdelnoteformlayoutid,
             lclientinvoiceformlayoutid, x.outscansort, x.printclientdeliverynote,
             ldeliverynotelayoutid);
          --count number of records inserted
          lcounter := lcounter + 1;
        exception
          when dup_val_on_index then
            null; --no problem when it is already there
        end;
        addresidentialdeliverydays(lcustomerid, x.customernumber, x.delivery_mo, x.delivery_tu,
                                   x.delivery_we, x.delivery_th, x.delivery_fr, x.delivery_sa,
                                   x.delivery_su);
        commit;
      exception
        when no_data_found then
          begin
            rollback;
            lerrormsg := 'Error' || lerrormsg || ' not found!';
            pack_import.write_log(lerrormsg || substr(sqlerrm, 1, 512), 3);
          end;
        when others then
          begin
            rollback;
            pack_import.write_log('Error others ' || lerrormsg || ' ' || substr(sqlerrm, 1, 512), 3);
          end;
      end;
    end loop;
    pack_import.write_log('    Succesfully imported ' || to_char(lcounter) ||
                          ' customerresidentialsettings records.');
    pack_import.write_log('End import_custresidentialsettings');
  exception
    when others then
      begin
        rollback;
        lerrormsg := 'Error during import_custresidentialsettings' || lerrormsg;
        pack_import.write_log(lerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end import_custresidentialsettings;
  procedure import_residentialplpc is
    lcounter                      number := 0;
    lproductlistpercustomerid     productlistpercustomer.productlistpercustomer_id%type;
    lproductid                    product.product_id%type;
    lsizedefinitionid             sizedefinition.sizedefinition_id%type;
    lcustomerid                   customer.customer_id%type;
    lfinishingmethodid            finishingmethod.finishingmethod_id%type;
    lcountrowscwpn                integer := 0;
    lcountrowscwpo                integer := 0;
    lcountrowspgpc                integer := 0;
    lpricelistpercustomerid       pricelistpercustomer.pricelistpercustomer_id%type;
    lv_customerbudgetdefinitionid customerbudgetdefinition.customerbudgetdefinition_id%type;
    lproductgroupid               product.productgroup_id%type;
  begin
    pack_import.write_log('Start import_residentialplpc');
    begin
      --add missing plpc records from i_uniqueresitem
      insert into i_residentialplpc
        (customernumber, productcode, typeofmerchandise, sizecode, finishingmethodcode, dateactive,
         dateinactive, codeuniquely, comes_from_i_residentialitem)
        select i.customernumber, i.productcode,
               (select p.typeofmerchandise from product p where p.code = i.productcode), i.sizecode,
               i.finishingmethodcode, nvl(min(i.assigndate), trunc(sysdate) - 1),
               to_date('31-12-2099', 'dd-mm-yyyy'), 'Y', 1 -->comes_from_i_residentialitem
        from   i_uniqueresitem i
        where  i.productcode is not null
        and    not exists
         (select z.customernumber, z.productcode, z.sizecode, z.finishingmethodcode
                from   i_residentialplpc z
                where  z.customernumber = i.customernumber
                and    z.productcode = i.productcode
                and    z.sizecode = i.sizecode
                and    z.finishingmethodcode = i.finishingmethodcode)
        group  by i.customernumber, i.productcode, i.sizecode, i.finishingmethodcode
        order  by i.customernumber, i.productcode, i.sizecode, i.finishingmethodcode;
      commit;
    exception
      when others then
        begin
          lerrormsg := 'Error during adding missing plpc records during import_residentialplpc!';
          pack_import.write_log(lerrormsg || ' ' || substr(sqlerrm, 1, 512), 3);
        end;
    end;
    -- finishing method
    lcounter := 0;
    for fx in (select i.finishingmethodcode
               from   i_residentialplpc i
               where  i.comes_from_i_residentialitem = 0 --only import PLPC finishingmethods
               and    not exists
                (select f.code from finishingmethod f where f.code = i.finishingmethodcode)
               group  by i.finishingmethodcode) loop
      begin
        insert into finishingmethod
          (finishingmethod_id, code, active, systemuser_id, timestamp)
        values
          (seq_finishingmethod.nextval, fx.finishingmethodcode, 'Y', pack_import.lvnsystemuserid,
           sysdate);
        insert into finishingmethod_desc
          (finishingmethod_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_finishingmethod.currval, pack_import.lvnlanguageid, fx.finishingmethodcode,
           pack_import.lvnsystemuserid, sysdate);
        lcounter := lcounter + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          pack_import.write_log('import_residentialplpc: Fail to import finishing method code ' ||
                                fx.finishingmethodcode || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    if lcounter > 0 then
      begin
        pack_import.write_log('imported ' || to_char(lcounter) ||
                              ' new i_residentialplpc finishingmethodcodes');
      end;
    end if;
    lcounter := 0;
    for x in (select *
              from   i_residentialplpc i
              where  not exists (select l.productlistpercustomer_id
                      from   productlistpercustomer l, customer c, product p,
                             sizedefinition s, finishingmethod f
                      where  l.customer_id = c.customer_id
                      and    c.customernumber = i.customernumber
                      and    l.product_id = p.product_id
                      and    p.code = i.productcode
                      and    l.sizedefinition_id = s.sizedefinition_id
                      and    s.code = i.sizecode
                      and    l.finishingmethod_id = f.finishingmethod_id
                      and    f.code = i.finishingmethodcode)) loop
      begin
        --customer
        lerrormsg := ' customer ' || x.customernumber;
        select c.customer_id
        into   lcustomerid
        from   customer c
        where  c.customernumber = x.customernumber;
        --product and productgroup
        lerrormsg := ' product ' || x.productcode || ' with TOM 5';
        select p.product_id, p.productgroup_id
        into   lproductid, lproductgroupid
        from   product p
        where  p.code = x.productcode
        and    p.typeofmerchandise = 5;
        --size
        lerrormsg := ' sizedefinition ' || x.sizecode;
        select s.sizedefinition_id
        into   lsizedefinitionid
        from   sizedefinition s
        where  s.code = x.sizecode;
        --finishingmethod
        lerrormsg := ' finishingmethod ' || x.finishingmethodcode;
        select f.finishingmethod_id
        into   lfinishingmethodid
        from   finishingmethod f
        where  f.code = x.finishingmethodcode;
        begin
          --get lv_customerbudgetdefinitionid
          if x.budgetcode is null then
            lv_customerbudgetdefinitionid := null;
          else
            begin
              select cbd.customerbudgetdefinition_id
              into   lv_customerbudgetdefinitionid
              from   customerbudgetdefinition cbd
              where  cbd.customer_id = lcustomerid
              and    cbd.code = x.budgetcode;
            exception
              when no_data_found then
                begin
                  lv_customerbudgetdefinitionid := null;
                  pack_import.write_log(' customerbudgetdefinition code ' || x.budgetcode ||
                                        ' for customer ' || x.customernumber || ' does not exist.',
                                        3);
                end;
            end;
          end if; --lv_customerbudgetdefinitionid
        end;
        --plpc insert
        lerrormsg := ' insert productlistpercustomer ';
        pack_import.cfbcreate_productlistpercust(lproductlistpercustomerid, lproductid,
                                                 x.dateactive, x.dateinactive, lfinishingmethodid,
                                                 x.codeuniquely, 0, lcustomerid, 'N',
                                                 lsizedefinitionid, 'N', 'Y', 0, 4, 1, 0, 'N', 0, 0,
                                                 0, 0, 'N', 'N', 0, 0, 0, x.customcode,
                                                 x.customdescription, 0, null, null, null, null,
                                                 null, 1, 0, 0, 'N', null, null, 'N', 'Y', 'N', 'N',
                                                 null, 0, 0, 0, 'N', null, null, 0, null, 'N', null,
                                                 null, null, 0, 0, 0, null, null, null, null, 'N', 0,
                                                 null, null, 0, x.budgetusage,
                                                 lv_customerbudgetdefinitionid);
        --update plpc selfpayment
        lerrormsg := ' update plpc selfpayment ';
        update productlistpercustomer l
        set    l.selfpayment = x.selfpayment
        where  l.productlistpercustomer_id = lproductlistpercustomerid;
        --count number of records inserted
        commit;
        lcounter := lcounter + 1;
        -- insert customerwashprice
        if x.washpricestartdate is not null and x.washpricenew is not null then
          begin
            begin
              insert into customerwashprice
                (customerwashprice_id, productlistpercustomer_id, timestamp, systemuser_id, price,
                 startdate)
              values
                (seq_customerwashprice.nextval, lproductlistpercustomerid, sysdate,
                 pack_import.lvnsystemuserid, x.washpricenew, x.washpricestartdate);
              --pricelistpercustomer
              pack_import.cfbcreate_pricelistpercustomer(lpricelistpercustomerid, lcustomerid, 1,
                                                         null, null, x.dateactive, x.dateinactive,
                                                         null, null, 1);
              commit;
              lcountrowscwpn := lcountrowscwpn + 1;
            exception
              when dup_val_on_index then
                null;
              when others then
                lerrormsg := 'CFbImportPLCust: Fail to import customerwashprice for customernumber ' ||
                             x.customernumber || ' ,productcode:' || x.productcode || ' ,size: ' ||
                             x.sizecode || ' ,finishingmethod: ' || x.finishingmethodcode;
                pack_import.write_log(lerrormsg || ' ' || substr(sqlerrm, 1, 512), 3);
            end;
            if x.washpriceold > 0 then
              begin
                insert into customerwashprice
                  (customerwashprice_id, productlistpercustomer_id, timestamp, systemuser_id, price,
                   startdate)
                values
                  (seq_customerwashprice.nextval, lproductlistpercustomerid, sysdate,
                   pack_import.lvnsystemuserid, x.washpriceold, x.washpricestartdate - 1);
                commit;
                lcountrowscwpo := lcountrowscwpo + 1;
              exception
                when dup_val_on_index then
                  null;
                when others then
                  lerrormsg := 'CFbImportPLCust: Fail to import old customerwashprice for customernumber ' ||
                               x.customernumber || ' ,productcode:' || x.productcode || ' ,size: ' ||
                               x.sizecode || ' ,finishingmethod: ' || x.finishingmethodcode;
                  pack_import.write_log(lerrormsg || ' ' || substr(sqlerrm, 1, 512), 3);
              end;
            end if;
          end;
        end if;
        if x.discountpercentagewash is not null then
          begin
            insert into customerwashdiscount
              (customerwashdiscount_id, productlistpercustomer_id, timestamp, systemuser_id,
               discount, startdate)
            values
              (seq_customerwashdiscount.nextval, lproductlistpercustomerid, sysdate,
               pack_import.lvnsystemuserid, x.discountpercentagewash,
               coalesce(x.washpricestartdate, x.dateactive));
          exception
            when others then
              begin
                lerrormsg := 'CFbImportPLCust: Fail to import old customerwashdiscount for customernumber ' ||
                             x.customernumber || ' ,productcode:' || x.productcode || ' ,size: ' ||
                             x.sizecode || ' ,finishingmethod: ' || x.finishingmethodcode;
                pack_import.write_log(lerrormsg || ' ' || substr(sqlerrm, 1, 512), 3);
              end;
          end;
        end if;
        begin
          insert into productgrouppercustomer
          (productgroup_id, customer_id, invoicegroupingcode, customcode,
           customdescritpion,systemuser_id, timestamp, active)
          values
          (lproductgroupid, lcustomerid, null, null, null, 1, sysdate, 'Y');
           lcountrowspgpc := lcountrowspgpc + 1;
            exception
               when dup_val_on_index then
                  null;
               when others then
                  lerrormsg := 'import_residentialplpc: Fail to import productgrouppercustomer for customernumber ' ||
                                x.customernumber || ' ,productcode:' || x.productcode;
                  pack_import.write_log(lerrormsg || ' ' || substr(sqlerrm, 1, 512), -3);
         end;
      exception
        when dup_val_on_index then
          null; --no problem if plpc is already there
        when no_data_found then
          begin
            rollback;
            lerrormsg := 'Error' || lerrormsg || ' not found!';
            pack_import.write_log(lerrormsg || substr(sqlerrm, 1, 512), 3);
          end;
      end;
    end loop;
    pack_import.write_log('    Succesfully imported ' || to_char(lcounter) ||
                          ' residential plpc records.');
    if lcountrowscwpn > 0 then
      pack_import.write_log(lcountrowscwpn || ' customerwashpricenew rows imported.');
    end if;
    if lcountrowscwpo > 0 then
      pack_import.write_log(lcountrowscwpo || ' customerwashpriceold rows imported.');
    end if;
    pack_import.write_log(lcountrowspgpc || ' productgrouppercustomer rows imported.');
    pack_import.write_log('End import_residentialplpc');
  exception
    when others then
      begin
        rollback;
        lerrormsg := 'Error during import_residentialplpc' || lerrormsg;
        pack_import.write_log(lerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end import_residentialplpc;
  procedure import_client is
    lcounter                 number := 0;
    lcounterresidential      number := 0;
    lcounterprivate          number := 0;
    lcustomerid              customer.customer_id%type;
    lcustomerclients         customerresidentialsettings.customerclients%type;
    ldepartmentid            department.department_id%type;
    lflagid                  flag.flag_id%type;
    lclientid                client.client_id%type;
    ldepartmentroomid        departmentroom.departmentroom_id%type;
    lclientcategoryid        clientcategory.clientcategory_id%type;
    ldeliveryaddressid       address.address_id%type;
    ldeliverypointid         deliverypoint.deliverypoint_id%type;
    ldeliverypointclientid   deliverypoint.deliverypoint_id%type;
    ldistributionpointid     distributionpoint.distributionpoint_id%type;
    lcostcenterid            costcenter.costcenter_id%type;
    lclientinvoicecategoryid clientinvoicecategory.clientinvoicecategory_id%type;
    lcontactaddressid        address.address_id%type;
  begin
    pack_import.write_log('Start import_client');
    for x in (select *
              from   i_client i
              where  not exists (select cl.client_id
                      from   client cl, customer c
                      where  cl.customer_id = c.customer_id
                      and    c.customernumber = i.customernumber
                      and    cl.clientnumber = i.clientnumber)
              order  by i.customernumber, i.departmentnumber, i.distributionpointnumber, i.roomnumber,
                        i.clientnumber) loop
      begin
        --customer
        lerrormsg := ' customer residentialsettings ' || x.customernumber;
        select c.customer_id, s.customerclients
        into   lcustomerid, lcustomerclients
        from   customer c, customerresidentialsettings s
        where  c.customernumber = x.customernumber
        and    c.customer_id = s.customer_id;
        --department
        lerrormsg := ' customer/department ' || x.customernumber || '/' || x.departmentnumber;
        select d.department_id
        into   ldepartmentid
        from   department d
        where  d.customer_id = lcustomerid
        and    d.departmentnumber = x.departmentnumber;
        --flag
        lerrormsg := ' flags ';
        if x.flagcode is null then
          lflagid := null;
        else
          begin
            lflagid := import_flag(x.flagcode, x.flagdesription);
          end;
        end if;
        --clientcategory
        lerrormsg := ' clientcategory ';
        if x.clientcategorycode is null then
          lclientcategoryid := null;
        else
          begin
            select cc.clientcategory_id
            into   lclientcategoryid
            from   clientcategory cc
            where  cc.customer_id = lcustomerid
            and    cc.categorycode = x.clientcategorycode;
          exception
            when no_data_found then
              begin
                --insert clientcategory
                select seq_clientcategory.nextval into lclientcategoryid from dual;
                insert into clientcategory
                  (clientcategory_id, customer_id, categorycode, description, systemuser_id,
                   timestamp)
                values
                  (lclientcategoryid, lcustomerid, x.clientcategorycode,
                   nvl(x.clientinvoicecategorydesc, '-'), pack_import.lvnsystemuserid, sysdate);
              exception
                when others then
                  begin
                    lerrormsg := 'Error adding clientcategory: ' || x.clientcategorycode || ' ';
                    pack_import.write_log(lerrormsg || substr(sqlerrm, 1, 512), 3);
                  end;
              end;
          end;
        end if;
        --insert client
        lerrormsg := ' insert client ';
        select seq_client.nextval into lclientid from dual;
        insert into client
          (client_id, customer_id, clientnumber, legacycode, name, searchname, firstname, gender,
           email, phonenumber, mobilephonenumber, flag_id, flagstartdate, dateactive, dateinactive,
           remark, systemuser_id, timestamp, presortnumber, budgetclient, publicservicenumber,
           adminnumber)
        values
          (lclientid, lcustomerid, x.clientnumber, x.legacycode, x.name, x.searchname, x.firstname,
           x.gender, x.clientemail, x.clientphonenumber, x.clientmobilephone, lflagid,
           x.flagstartdate, x.dateactive, x.dateinactive, x.remark, pack_import.lvnsystemuserid,
           sysdate, x.presortnumber, x.budgetclient, x.publicservicenumber, x.adminnumber);
        --clientinvoicecategory
        lerrormsg := ' clientinvoicecategory ';
        begin
          select i.clientinvoicecategory_id
          into   lclientinvoicecategoryid
          from   clientinvoicecategory i
          where  i.customer_id = lcustomerid
          and    i.code = nvl(x.clientinvoicecategorycode, '-');
        exception
          when no_data_found then
            begin
              select seq_clientinvoicecategory.nextval into lclientinvoicecategoryid from dual;
              insert into clientinvoicecategory
                (clientinvoicecategory_id, customer_id, code, description, active, defaultcategory,
                 invoiceto, minimuminvoiceamount, invoiceweight, minimuminvoiceweight, invoicelabels,
                 systemuser_id, timestamp, paymentterms_id, creditsqueezeperc)
              values
                (lclientinvoicecategoryid, lcustomerid, nvl(x.clientinvoicecategorycode, '-'),
                 nvl(x.clientinvoicecategorydesc, '-'), 'Y', 'N', x.invoiceto, 0, 0, 0, 0,
                 pack_import.lvnsystemuserid, sysdate, null, 0);
            exception
              when others then
                begin
                  lerrormsg := 'Error adding customer/clientinvoicecategory: ' ||
                               to_char(x.customernumber) || '/' || to_char(x.clientnumber) || ' ';
                  pack_import.write_log(lerrormsg || substr(sqlerrm, 1, 512), 3);
                end;
            end;
        end;
        --insert clientbilling info
        lerrormsg := ' insert clientbilling info ';
        insert into clientbillinginfo
          (client_id, clientinvoicecategory_id, sendinvoiceto, bankaccountnumber, ibannumber,
           systemuser_id, timestamp, nofreeofchargelabel, debtornumber, bankinstitution_id,
           laundrybankinstitution_id, paymenttype, selfpayment)
        values
          (lclientid, lclientinvoicecategoryid, x.sendinvoiceto, x.bankaccoutnumber, x.ibannumber,
           pack_import.lvnsystemuserid, sysdate, x.freelabelsissued, null, null, null, x.paymenttype,
           nvl(x.selfpayment, 0));
        --0 = residential
        if lcustomerclients = 0 then
          begin
            --initialize
            ldeliverypointid       := null;
            ldeliverypointclientid := null;
            --department room
            lerrormsg := ' get distributionpoint for departmentid ' || ldepartmentid;
            select min(dp.distributionpoint_id)
            into   ldistributionpointid
            from   distributionpoint dp
            where  dp.department_id = ldepartmentid;
            --department room
            lerrormsg := ' department room ';
            begin
              select r.departmentroom_id
              into   ldepartmentroomid
              from   departmentroom r
              where  r.department_id = ldepartmentid
              and    r.roomnumber = nvl(x.roomnumber, '-');
            exception
              when no_data_found then
                begin
                  select seq_departmentroom.nextval into ldepartmentroomid from dual;
                  insert into departmentroom
                    (departmentroom_id, department_id, distributionpoint_id, roomnumber, active,
                     systemuser_id, timestamp, sequencenumber)
                    select ldepartmentroomid, ldepartmentid, ldistributionpointid,
                           nvl(x.roomnumber, '-'), 'Y', pack_import.lvnsystemuserid, sysdate,
                           nvl(max(dpr.sequencenumber), 0) + 1
                    from   departmentroom dpr
                    where  dpr.department_id = ldepartmentid;
                exception
                  when others then
                    begin
                      lerrormsg := 'Error adding customer/department/room: ' ||
                                   to_char(x.customernumber) || '/' || to_char(x.departmentnumber) || '/' ||
                                   to_char(x.clientnumber) || ' ';
                      pack_import.write_log(lerrormsg || substr(sqlerrm, 1, 512), 3);
                    end;
                end;
            end;
            --insert clientresident
            lerrormsg := ' clientresident ';
            insert into clientresident
              (client_id, labelname, birthdate, deceaseddate, departmentroom_id, clientcategory_id,
               systemuser_id, timestamp, laundryservicesparticipant)
            values
              (lclientid, x.labelname, x.birthdate, x.dateoutofservice, ldepartmentroomid,
               lclientcategoryid, pack_import.lvnsystemuserid, sysdate, 'Y');
            lcounterresidential := lcounterresidential + 1;
          end;
        else
          --1 = private client
          begin
            lerrormsg := ' clientprivateperson ';
            --initialize
            ldeliverypointclientid := null;
            ldepartmentroomid      := null;
            begin
              --select deliverypoint
              lerrormsg := ' select deliverypoint ';
              select p.deliverypoint_id
              into   ldeliverypointid
              from   deliverypoint p
              where  p.customer_id = lcustomerid
              and    p.code =
                     substr(nvl(to_char(x.deliverypointnumber), to_char(x.clientnumber)), 1, 12);
            exception
              when no_data_found then
                begin
                  lerrormsg := ' insert address/deliverypoint ';
                  --insert address
                  select seq_address.nextval into ldeliveryaddressid from dual;
                  insert into address
                    (address_id, street, zipcode, city, state, systemuser_id, county, timestamp,
                     street2)
                  values
                    (ldeliveryaddressid, x.clientstreet, nvl(x.clientzipcode, '-'),
                     nvl(x.clientcity, '-'), null, pack_import.lvnsystemuserid, null, sysdate, null);
                  --insert deliverypoint
                  pack_import.cfbcreate_deliverypoint(ldeliverypointid, lcustomerid,
                                                      substr(nvl(to_char(x.deliverypointnumber),
                                                                  to_char(x.clientnumber)), 1, 12),
                                                      to_char(x.clientnumber), ldeliveryaddressid,
                                                      null);
                  ldeliverypointclientid := ldeliverypointid;
                exception
                  when others then
                    begin
                      lerrormsg := 'Error adding address/deliverypoint for customer/deliverypoint: ' ||
                                   to_char(x.customernumber) || '/' ||
                                   substr(nvl(to_char(x.deliverypointnumber),
                                              to_char(x.clientnumber)), 1, 12) || ' ';
                      pack_import.write_log(lerrormsg || substr(sqlerrm, 1, 512), 3);
                    end;
                end;
            end;
            --insert distributionpoint
            lerrormsg := ' select/insert distributionpoint ';
            select min(c.costcenter_id)
            into   lcostcenterid
            from   costcenter c
            where  c.customer_id = lcustomerid;
            pack_import.cfbcreate_distributionpoint(ldistributionpointid,
                                                    nvl(x.distributionpointnumber, x.clientnumber),
                                                    to_char(nvl(x.distributionpointnumber,
                                                                 x.clientnumber)), null, null,
                                                    sysdate, sysdate, 'Y', ldepartmentid,
                                                    ldeliverypointid, lcostcenterid, null, null,
                                                    null);
            insert into clientprivateperson
              (client_id, distributionpoint_id, deliverypoint_id, systemuser_id, timestamp)
            values
              (lclientid, ldistributionpointid, ldeliverypointclientid, pack_import.lvnsystemuserid,
               sysdate);
            --count number of records inserted
            commit;
            lcounterprivate := lcounterprivate + 1;
          end;
        end if;
        --insert client link
        lerrormsg := ' insert client link ';
        insert into client_link
          (client_link_id, client_id, customer_link_id, deliverypoint_link_id, clientnumber, name,
           departmentroom_id, systemuser_id, timestamp)
        values
          (lclientid, lclientid, lcustomerid, ldeliverypointid, x.clientnumber, x.name,
           ldepartmentroomid, pack_import.lvnsystemuserid, sysdate);
        --client contact person
        if x.contactname is not null then
          begin
            lerrormsg := ' address/client contact person ';
            --insert address
            select seq_address.nextval into lcontactaddressid from dual;
            insert into address
              (address_id, street, zipcode, city, state, systemuser_id, county, timestamp, street2)
            values
              (lcontactaddressid, x.contactstreet, nvl(x.contactzipcode, '-'),
               nvl(x.contactcity, '-'), null, pack_import.lvnsystemuserid, null, sysdate, null);
            --insert into clientcontactperson
            insert into clientcontactperson
              (clientcontactperson_id, client_id, contactpersonnumber, name, phone, mobilephone,
               fax, email, invoicecontactperson, address_id, contacttype, systemuser_id, timestamp)
            values
              (seq_clientcontactperson.nextval, lclientid, x.clientnumber, x.contactname,
               x.contactphone, null, null, null, x.contactinvoicereceiver, lcontactaddressid, 0,
               pack_import.lvnsystemuserid, sysdate);
          end;
        end if;
        --count number of records inserted
        commit;
        lcounter := lcounter + 1;
      exception
        when no_data_found then
          begin
            rollback;
            lerrormsg := 'Error' || lerrormsg || ' not found!';
            pack_import.write_log(lerrormsg || substr(sqlerrm, 1, 512), 3);
          end;
        when others then
          begin
            rollback;
            pack_import.write_log('Error' || lerrormsg || ' ' || substr(sqlerrm, 1, 512), 3);
          end;
      end;
    end loop;
    if lcounterprivate > 0 then
      pack_import.write_log('    imported ' || to_char(lcounterprivate) ||
                            ' client private records.');
    end if;
    if lcounterresidential > 0 then
      pack_import.write_log('    imported ' || to_char(lcounterresidential) ||
                            ' client residential records.');
    end if;
    pack_import.write_log('    Succesfully totally imported ' || to_char(lcounter) ||
                          ' client records.');
    convert_i_nobudgetclient;
    pack_import.write_log('End import_client');
  exception
    when others then
      begin
        rollback;
        lerrormsg := 'Error during import_client' || lerrormsg;
        pack_import.write_log(lerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end import_client;
  procedure import_uniqueresitem is
    lcounter                 number := 0;
    lbusinessunitid          businessunit.businessunit_id%type;
    lcustomerid              customer.customer_id%type;
    lclientid                client.client_id%type;
    lstatusid                status.status_id%type;
    lstayid                  stay.stay_id%type;
    luniqueresidentialitemid uniqueresidentialitem.uniqueresidentialitem_id%type;
    lproductid               product.product_id%type;
    lsizeid                  sizedefinition.sizedefinition_id%type;
    lfinishingmethodid       finishingmethod.finishingmethod_id%type;
    lwashprocessid           washingprocess.washingprocess_id%type;
    lcolorid                 color.color_id%type;
    lflagid                  flag.flag_id%type;
  begin
    pack_import.write_log('Start import_uniqueresitem');
    for x in (select *
              from   i_uniqueresitem i
              where  not exists (select u.uniqueresidentialitem_id
                      from   uniqueresidentialitem u, businessunit b
                      where  u.businessunit_id = b.businessunit_id
                      and    b.code = i.businessunitcode
                      and    u.primaryid = i.primaryid
                      and    u.sequencenumber = i.sequencenumber)) loop
      begin
        --businessunit
        lerrormsg := ' businessunit ' || x.businessunitcode;
        select b.businessunit_id
        into   lbusinessunitid
        from   businessunit b
        where  b.code = x.businessunitcode;
        --customer
        lerrormsg := ' customer ' || to_char(x.customernumber);
        select c.customer_id
        into   lcustomerid
        from   customer c
        where  c.customernumber = x.customernumber;
        --client
        lerrormsg := ' client/customer ' || to_char(x.clientnumber) || '/' ||
                     to_char(x.customernumber);
        select c.client_id
        into   lclientid
        from   client c
        where  c.clientnumber = x.clientnumber
        and    c.customer_id = lcustomerid;
        --status
        lerrormsg := ' status (type ''UR'') ' || x.status;
        select s.status_id
        into   lstatusid
        from   status s
        where  s.code = x.status
        and    s.statustype = 'UR';
        --stay
        lerrormsg := ' stay (type 5) nr ' || x.stay;
        select s.stay_id
        into   lstayid
        from   stay s
        where  s.staytype = 5
        and    s.staynr = to_number(x.stay);
        --insert uniqueresidentialitem
        lerrormsg := ' insert uniqueresidentialitem ' || x.primaryid;
        select seq_uniqueresidentialitem.nextval into luniqueresidentialitemid from dual;
        insert into uniqueresidentialitem
          (uniqueresidentialitem_id, businessunit_id, primaryid, sequencenumber, client_id,
           printdate, status_id, statuschangedate, laststatus_id, stay_id, laststaydate, laststay_id,
           lastinscandate, lastoutscandate, lastrewashdate, lastrepairdate, numberofwashes,
           numberofrepairs, numberofrewashes, lastchangedate, remark, price, systemuser_id,
           timestamp)
        values
          (luniqueresidentialitemid, lbusinessunitid, x.primaryid, x.sequencenumber, lclientid,
           nvl(x.printdate, x.assigndate), lstatusid, x.statuschangedate, null, lstayid,
           x.staychangedate, null, x.lastinscandate, x.lastoutscandate, x.lastrewashdate,
           x.lastrepairdate, x.numberofwashes, x.numberofrepairs, x.numberofrewashes,
           x.lastchangedate, x.remark, x.price, pack_import.lvnsystemuserid, sysdate);
        insert into uniqueresidentialitem_link
          (uniqueresidentialitem_link_id, uniqueresidentialitem_id, raggedresidentialitem_id,
           systemuser_id, timestamp)
        values
          (luniqueresidentialitemid, luniqueresidentialitemid, null, pack_import.lvnsystemuserid,
           sysdate);
        --product/size/finishingmet..
        if x.productcode is null then
          begin
            lproductid         := null;
            lsizeid            := null;
            lfinishingmethodid := null;
            lwashprocessid     := null;
            lcolorid           := null;
          end;
        else
          begin
            --product
            lerrormsg := ' product ' || x.productcode;
            select p.product_id into lproductid from product p where p.code = x.productcode;
            --size
            lerrormsg := ' size ' || x.sizecode;
            select s.sizedefinition_id
            into   lsizeid
            from   sizedefinition s
            where  s.code = x.sizecode;
            --finishingmethod
            lerrormsg := ' finishingmethod ' || x.finishingmethodcode;
            select f.finishingmethod_id
            into   lfinishingmethodid
            from   finishingmethod f
            where  f.code = x.finishingmethodcode;
            --washingprocess
            if x.wasprocesscode is null then
              lwashprocessid := null;
            else
              begin
                lerrormsg := ' washingprocess ' || x.wasprocesscode;
                select p.washingprocess_id
                into   lwashprocessid
                from   washingprocess p
                where  p.code = x.wasprocesscode;
              exception
                when no_data_found then
                  begin
                    select seq_washingprocess.nextval into lwashprocessid from dual;
                    insert into washingprocess
                      (washingprocess_id, code, systemuser_id, timestamp, color)
                    values
                      (lwashprocessid, x.wasprocesscode, pack_import.lvnsystemuserid, sysdate,
                       'FFFF00');
                    insert into washingprocess_desc
                      (washingprocess_id, language_id, description, systemuser_id, timestamp)
                    values
                      (lwashprocessid, pack_import.lvnlanguageid, 'Conversion added',
                       pack_import.lvnsystemuserid, sysdate);
                  end;
              end;
            end if;
            -- add productwashingprocess
            pack_import.cfbcreate_productwashingproc(lproductid, lwashprocessid);
            --color
            if x.colorcode is null then
              lcolorid := null;
            else
              begin
                lerrormsg := ' colorcode ' || x.colorcode;
                select c.color_id into lcolorid from color c where c.code = x.colorcode;
              end;
            end if;
            --insert uniqueresidentialitemproduct
            lerrormsg := ' insert uniqueresidentialitemproduct ';
            insert into uniqueresidentialitemproduct
              (uniqueresidentialitem_id, product_id, sizedefinition_id, finishingmethod_id,
               specificcolor_id, specificwashingprocess_id, assigndate, systemuser_id, timestamp)
            values
              (luniqueresidentialitemid, lproductid, lsizeid, lfinishingmethodid, lcolorid,
               lwashprocessid, nvl(x.assigndate, sysdate), pack_import.lvnsystemuserid, sysdate);
          end;
        end if;
        --flagcode
        lerrormsg := ' flags ';
        if x.flagcode is null then
          lflagid := null;
        else
          begin
            lflagid := import_flag(x.flagcode, x.flagdescription);
            insert into uniqueresidentialitemflag
              (uniqueresidentialitem_id, flag_id, startdate, freetextitem, systemuser_id, timestamp)
            values
              (luniqueresidentialitemid, lflagid, nvl(x.flagstartdate, sysdate), x.flagremark,
               pack_import.lvnsystemuserid, sysdate);
          end;
        end if;
        --count number of records inserted
        commit;
        lcounter := lcounter + 1;
      exception
        when no_data_found then
          begin
            rollback;
            lerrormsg := 'Error' || lerrormsg || ' not found!';
            pack_import.write_log(lerrormsg, 3);
          end;
      end;
    end loop;
    pack_import.write_log('    Succesfully imported ' || to_char(lcounter) ||
                          ' unique residential item records.');
    pack_import.write_log('End import_uniqueresitem');
    pack_import_plcustomer.cfbaddcustomeractivities;
  exception
    when others then
      begin
        rollback;
        lerrormsg := 'Error during import_uniqueresitem ' || lerrormsg;
        pack_import.write_log(lerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end import_uniqueresitem;
  procedure convert_i_nobudgetclient is
    lv_counter         number := 0;
    lv_customerid      customer.customer_id%type;
    lv_clientid        client.client_id%type;
    lv_custbudgetdefid customerbudgetdefinition.customerbudgetdefinition_id%type;
  begin
    --convert_i_nobudgetclient
    lerrormsg := 'convert_i_nobudgetclient';
    for xnd in (select * from i_nobudgetclient) loop
      begin
        --get customer
        lerrormsg := 'convert_i_nobudgetclient get customer ' || xnd.customernumber;
        select c.customer_id
        into   lv_customerid
        from   customer c
        where  c.customernumber = xnd.customernumber;
        --get client
        lerrormsg := 'convert_i_nobudgetclient get client ' || xnd.clientnumber || ' for customer ' ||
                     xnd.customernumber;
        select t.client_id
        into   lv_clientid
        from   client t
        where  t.customer_id = lv_customerid
        and    t.clientnumber = xnd.clientnumber;
        --get customer budgetdefinition
        lerrormsg := 'get customer budgetcode ' || xnd.budgetcode || ' for customer ' ||
                     xnd.customernumber;
        select cbd.customerbudgetdefinition_id
        into   lv_custbudgetdefid
        from   customerbudgetdefinition cbd
        where  cbd.customer_id = lv_customerid
        and    cbd.code = xnd.budgetcode;
        --insert into nobudgetclient
        lerrormsg := 'insert into nobudgetclient';
        insert into nobudgetclient
          (customerbudgetdefinition_id, client_id, systemuser_id, timestamp)
        values
          (lv_custbudgetdefid, lv_clientid, pack_import.lvnsystemuserid, sysdate);
        --count
        lv_counter := lv_counter + 1;
      exception
        when no_data_found then
          pack_import.write_log('Error during import nobudgetclient, no data found ' || lerrormsg,
                                3);
        when dup_val_on_index then
          null; --no problem if it is already there
      end;
    end loop; --xnd
    commit;
    if lv_counter > 0 then
      pack_import.write_log(lv_counter || ' nobudgetclient rows imported.');
    end if;
  exception
    when others then
      begin
        rollback;
        lerrormsg := 'convert_i_nobudgetclient: Failed to import.';
        pack_import.write_log(lerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end convert_i_nobudgetclient;
end pack_import_residential;
/
create or replace package pack_import_soilticket is
  -- Author  : TATIANA
  -- Created : 4/14/2003 7:32:40 PM
  -- Version : 1.0
  -- Updated : 4/17/2004  added cfbimport_soilreasonability
  -- Purpose :
  procedure cfbsoilticket;
  procedure cfbsoilticketline;
  procedure cfbimport_soilreasonability;
end pack_import_soilticket;
/
create or replace package body pack_import_soilticket is
  errormsg     varchar2(256);
  countrows    integer;
  countrowsu   integer;
  soilticketid soilticket.soilticket_id%type;
  importd      date;
  exportd      date;
  procedure cfbsoilticket is
    processed soilticket.processed%type;
  begin
    countrows  := 0;
    countrowsu := 0;
    for vcursor in (select i.*, c.customer_id, r.route_id, b.businessunit_id, b.code,
                           rt.routecontrol_id, s.soilticket_id, rt.soilcountstatus
                    from   i_soilticket i, customer c, route r, businessunit b, routecontrol rt,
                           soilticket s
                    where  i.customernumber = c.customernumber
                    and    i.routenumber = r.routenumber
                    and    to_char(i.businessunitnumber) = b.code
                    and    rt.route_id = r.route_id
                    and    rt.originaldrivingdate = i.invoicedate
                    and    rt.plant_id = b.plant_id
                    and    i.soilticketnumber = s.soilticketnumber(+)) loop
      begin
        if vcursor.exportdate is null then
          exportd := to_date('31/12/2099', 'DD/MM/YYYY');
        else
          exportd := vcursor.exportdate;
        end if;
        if vcursor.importdate is null then
          importd := to_date('31/12/2099', 'DD/MM/YYYY');
        else
          importd := vcursor.importdate;
        end if;
        if vcursor.soilticket_id is not null then
          begin
            update soilticket
            set    customer_id = vcursor.customer_id, routecontrol_id = vcursor.routecontrol_id,
                   processbusinessunit_id = vcursor.businessunit_id,
                   routestopnumber = vcursor.stopnumber, invoicenumber = vcursor.invoicenumber,
                   invoicedate = vcursor.invoicedate, countdate = vcursor.countdate,
                   importdate = importd, exportdate = exportd,
                   systemuser_id = pack_import.lvnsystemuserid, timestamp = sysdate
            where  soilticket_id = vcursor.soilticket_id;
            countrowsu := countrowsu + 1;
          exception
            when dup_val_on_index then
              null;
            when others then
              errormsg := 'CFbSoilTicket: Fail to update soilticket number ' ||
                          vcursor.soilticketnumber;
              pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
          end;
        else
          begin
            soilticketid := -1;
            if (vcursor.soilcountstatus = 3) then
              processed := 'Y';
            else
              processed := 'N';
            end if;
            insert into soilticket
              (soilticket_id, soilticketnumber, customer_id, routecontrol_id,
               processbusinessunit_id, routestopnumber, invoicenumber, invoicedate, countdate,
               importdate, exportdate, employee_id, systemuser_id, timestamp, processed, stop_id)
            values
              (seq_soilticket.nextval, vcursor.soilticketnumber, vcursor.customer_id,
               vcursor.routecontrol_id, vcursor.businessunit_id, vcursor.stopnumber,
               vcursor.invoicenumber, vcursor.invoicedate, vcursor.countdate, importd, exportd, null,
               pack_import.lvnsystemuserid, sysdate, processed, null);
            select seq_soilticket.currval into soilticketid from dual;
            countrows := countrows + 1;
          exception
            when dup_val_on_index then
              null;
            when others then
              errormsg := 'CFbSoilTicket: Fail to import soilticket number ' ||
                          vcursor.soilticketnumber;
              pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
          end;
        end if;
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(countrows || ' soilticket rows imported.');
    end if;
    if countrowsu > 0 then
      pack_import.write_log(countrowsu || ' soilticket rows updated.');
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('cfbsoilticket failed: ' || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbsoilticket;
  --soilticketline
  procedure cfbsoilticketline is
    soilticketlineid soilticketline.soilticketline_id%type;
    sizestarid       sizedefinition.sizedefinition_id%type;
  begin
    update i_soilticketline
    set    productcode = ltrim(rtrim(productcode)), sizecode = ltrim(rtrim(sizecode)),
           finishingmethodcode = ltrim(rtrim(finishingmethodcode));
    select sizedefinition_id into sizestarid from sizedefinition where code = '*';
    countrows  := 0;
    countrowsu := 0;
    for vcursor in (select i.*, s.soilticket_id, p.product_id, z.sizedefinition_id,
                           f.finishingmethod_id, pl.delayedevenexchange, sl.soilticketline_id
                    from   i_soilticketline i, soilticket s, product p, sizedefinition z,
                           finishingmethod f, productlistpercustomer pl, soilticketline sl
                    where  i.soilticketnumber = s.soilticketnumber
                    and    i.productcode = p.code
                    and    i.sizecode = z.code
                    and    i.finishingmethodcode = f.code
                    and    pl.customer_id = s.customer_id
                    and    pl.product_id = p.product_id
                    and    pl.finishingmethod_id = f.finishingmethod_id
                    and    pl.sizedefinition_id = z.sizedefinition_id
                    and    s.soilticket_id = sl.soilticket_id(+)) loop
      begin
        if vcursor.soilticketline_id is not null then
          begin
            update soilticketline
            set    countlightframe = vcursor.countlightframe, countkeypad = vcursor.countkeypad,
                   countconverted = vcursor.countconverted, countabused = vcursor.countabused,
                   delayedevenexchange = vcursor.delayedevenexchange, inventory = vcursor.inventory,
                   invoicelinenumber = vcursor.invoicelinenumver, soilweight = vcursor.soilweight,
                   systemuser_id = pack_import.lvnsystemuserid, timestamp = sysdate
            where  soilticketline_id = vcursor.soilticketline_id;
            countrowsu := countrowsu + 1;
          exception
            when dup_val_on_index then
              null;
            when others then
              errormsg := 'CFbSoilTicketLine: Fail to update line for soilticketnumber/productcode/sizecode/finishingmethcode ' ||
                          vcursor.soilticketnumber || '/' || vcursor.productcode || '/' ||
                          vcursor.sizecode || '/' || vcursor.finishingmethodcode;
              pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
          end;
        else
          begin
            insert into soilticketline
              (soilticketline_id, soilticket_id, product_id, sizedefinition_id, finishingmethod_id,
               countlightframe, countkeypad, countconverted, countabused, delayedevenexchange,
               inventory, invoicelinenumber, soilweight, systemuser_id, timestamp, unrelatedloan)
            values
              (seq_soilticketline.nextval, vcursor.soilticket_id, vcursor.product_id,
               vcursor.sizedefinition_id, vcursor.finishingmethod_id, vcursor.countlightframe,
               vcursor.countkeypad, vcursor.countconverted, vcursor.countabused,
               vcursor.delayedevenexchange, vcursor.inventory, vcursor.invoicelinenumver,
               vcursor.soilweight, pack_import.lvnsystemuserid, sysdate, 'N')
            returning soilticketline_id into soilticketlineid;
            countrows := countrows + 1;
          exception
            when dup_val_on_index then
              null;
            when others then
              errormsg := 'CFbSoilTicketLine: Fail to import line for soilticketnumber/productcode/sizecode/finishingmethcode ' ||
                          vcursor.soilticketnumber || '/' || vcursor.productcode || '/' ||
                          vcursor.sizecode || '/' || vcursor.finishingmethodcode;
              pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
          end;
        end if;
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(countrows || ' soilticketline rows imported.');
    end if;
    if countrowsu > 0 then
      pack_import.write_log(countrowsu || ' soilticketline rows updated.');
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('cfbsoilticketline failed: ' || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbsoilticketline;
  procedure cfbimport_soilreasonability is
    fpnprocessbusinessunit_id businessunit.businessunit_id%type;
    fpncustomer_link_id       customer_link.customer_link_id%type;
    fpnroute_id               route.route_id%type;
    fpnproduct_link_id        product_link.product_link_id%type;
    fpnsizedefinition_link_id sizedefinition_link.sizedefinition_link_id%type;
    fpnfinishingmethod_id     finishingmethod.finishingmethod_id%type;
  begin
    countrows := 0;
    for x in (select * from i_soilreasonability) loop
      begin
        -- determine business unit
        select b.businessunit_id
        into   fpnprocessbusinessunit_id
        from   businessunit b
        where  b.code = to_char(x.businessunitnumber);
        -- determine customer.
        select c.customer_id
        into   fpncustomer_link_id
        from   customer c
        where  c.customernumber = x.customernumber;
        -- determine 1st route of customer and link it
        select min(r.route_id)
        into   fpnroute_id
        from   route r, routestop s
        where  r.route_id = s.route_id
        and    s.customer_id = fpncustomer_link_id;
        -- determine product
        select p.product_id into fpnproduct_link_id from product p where p.code = x.productcode;
        -- determine sizedefinition
        select s.sizedefinition_id
        into   fpnsizedefinition_link_id
        from   sizedefinition s
        where  s.code = x.sizecode;
        -- determine finishingmethod
        select f.finishingmethod_id
        into   fpnfinishingmethod_id
        from   finishingmethod f
        where  f.code = x.finishingmethodcode;
        -- insert soilreasonability
        insert into soilreasonability
          (processbusinessunit_id, customer_link_id, route_id, product_link_id,
           sizedefinition_link_id, finishingmethod_id, daynumber, currentqty, pickupdate,
           inventoryqty, pickupqty1, pickupqty2, pickupqty3, pickupqty4, pickupqty5, pickupqty6,
           pickupqty7, pickupqty8, pickupqty9, pickupqty10, pickupqty11, pickupqty12, pickupqty13,
           soilticketnumber, systemuser_id, timestamp)
        values
          (fpnprocessbusinessunit_id, fpncustomer_link_id, fpnroute_id, fpnproduct_link_id,
           fpnsizedefinition_link_id, fpnfinishingmethod_id, x.daynumber, null, x.pickupdate,
           x.inventoryqty, x.pickupqty1, x.pickupqty2, x.pickupqty3, x.pickupqty4, x.pickupqty5,
           x.pickupqty6, x.pickupqty7, x.pickupqty8, x.pickupqty9, x.pickupqty10, x.pickupqty11,
           x.pickupqty12, x.pickupqty13, x.soilticketnumber, pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(countrows || ' soilreasonability rows imported.');
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('cfbimport_soilreasonability failed: ' || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimport_soilreasonability;
end pack_import_soilticket;
/
create or replace package pack_import_sterilizationlot is
-- Version : 1.0
 procedure cfbimport_sterilizationlot;
 procedure cfbimport_cleanroombatch;
 procedure cfbimport_cleanroombatchcustomer;
 procedure cfbimport_cleanroomuidelivery;
end pack_import_sterilizationlot;
/
create or replace package body pack_import_sterilizationlot is
    lverrormsg varchar2(512);
    procedure cfbimport_sterilizationlot is
      lvcounter         number := 0;
      lvbusinessunit_id businessunit.businessunit_id%type;
    begin
      for x in (select *
                  from i_externalsterilizationlot i
                 where not exists
                 (select e.externalsterilizationlot_id
                          from externalsterilizationlot e
                          join businessunit bu
                            on e.businessunit_id = bu.businessunit_id
                         where i.lotnumber = e.lotnumber
                           and i.businessunit = bu.code)) loop
        begin
          --get businessunit_id
          lverrormsg := 'error, businessunit ' || x.businessunit;
          select bu.businessunit_id
            into lvbusinessunit_id
            from businessunit bu
           where x.businessunit = bu.code;
          insert into externalsterilizationlot
            (externalsterilizationlot_id,
             businessunit_id,
             lotnumber,
             creationdate,
             creationuser_id,
             status,
             sterilizationdate,
             sterilizationlottype,
             systemuser_id,
             timestamp)
          values
            (seq_externalsterilizationlot.nextval,
             lvbusinessunit_id,
             x.lotnumber,
             x.creationdate,
             pack_import.lvnsystemuserid,
             x.status,
             x.sterilizationdate,
             x.sterilizationlottype,
             pack_import.lvnsystemuserid,
             sysdate);
          lvcounter := lvcounter + 1;
        exception
          when no_data_found then
            begin
              lverrormsg := lverrormsg || ' does not exist';
              pack_import.write_log(lverrormsg, 2);
            end;
        end;
      end loop;
      commit;
      if lvcounter > 0 then
        pack_import.write_log(lvcounter ||
                              ' sterilizationlot rows imported.');
      end if;
    exception
      when others then
        begin
          rollback;
          lverrormsg := 'cfbimport_sterilizationlot: Failed to import.';
          pack_import.write_log(lverrormsg || substr(sqlerrm, 1, 512), 3);
        end;
    end cfbimport_sterilizationlot;
    function get_departmentid(fp_departmentnumber in department.departmentnumber%type,
                            fp_customerid       in customer.customer_id%type)
    return department.department_id%type is
    lv_departmentid department.department_id%type;
    begin
    --get_departmentid
    lverrormsg := ' department number ' || nvl(to_char(fp_departmentnumber), 'NULL');
    if fp_departmentnumber is null then
      return null;
    end if;
    select t.department_id
    into   lv_departmentid
    from   department t
    where  t.departmentnumber = fp_departmentnumber
    and    t.customer_id = fp_customerid;
    return lv_departmentid;
   end get_departmentid;
    procedure cfbimport_cleanroombatch is
      lvcounter                number := 0;
      lvbusinessunit_id        businessunit.businessunit_id%type;
      lvplantdepartment_id     plantdepartment.plantdepartment_id%type;
      lvcreationworkstation_id workstation.workstation_id%type;
      lvlastupdatedworkstation workstation.workstation_id%type;
      lvcreationuserId         systemuser.systemuser_id%type;
    begin
      for x in (select *
                  from i_cleanroombatch i
                 where not exists
                 (select c.cleanroombatchnumber
                          from cleanroombatch c
                          join businessunit bu
                            on c.businessunit_id = bu.businessunit_id
                         where i.cleanroombatchnumber =
                               c.cleanroombatchnumber
                           and i.businessunit = bu.code)) loop
        begin
          --get businessunit_id
      lverrormsg := 'Businessunit ' || x.businessunit;
          select bu.businessunit_id
            into lvbusinessunit_id
            from businessunit bu
           where x.businessunit = bu.code;
          --get plantdepartment_id
      lverrormsg := 'Plant deparment ' || x.plantdepartmentcode;
          select pd.plantdepartment_id
            into lvplantdepartment_id
            from plantdepartment pd
           where x.plantdepartmentcode = pd.code
             and pd.plant_id =
                 (select bu.plant_id
                    from businessunit bu
                   where bu.businessunit_id = lvbusinessunit_id);
          --get workstation_id
          lverrormsg := 'Creation workstation  ' || x.creationworkstation;
          select w.workstation_id
            into lvcreationworkstation_id
            from workstation w
           where w.code = x.creationworkstation;
          --get workstation_id
          lverrormsg := 'Last Update workstation  ' || x.lastupdateworkstation;
          select w.workstation_id
            into lvlastupdatedworkstation
            from workstation w
           where w.code = x.lastupdateworkstation;
          --get creationuser_id
          lverrormsg := 'Creation User  ' || x.creationuser;
          select s.systemuser_id
            into lvcreationuserId
            from systemuser s
           where s.username = upper(trim(x.creationuser));
          insert into cleanroombatch
            (cleanroombatch_id,
             businessunit_id,
             plantdepartment_id,
             cleanroombatchnumber,
             batchstatus,
             creationworkstation_id,
             lastupdatedworkstation_id,
             creationdate,
             creationuser_id,
             systemuser_id,
             timestamp)
          values
            (seq_cleanroombatch.nextval,
             lvbusinessunit_id,
             lvplantdepartment_id,
             x.cleanroombatchnumber,
             2,
             lvcreationworkstation_id,
             lvlastupdatedworkstation,
             x.creationdate,
             lvcreationuserId,
             pack_import.lvnsystemuserid,
             sysdate);
           lvcounter := lvcounter + 1;
        exception
          when no_data_found then
            begin
              lverrormsg := lverrormsg || ' does not exist';
              pack_import.write_log(lverrormsg, 2);
            end;
        end;
      end loop;
      if lvcounter > 0 then
     begin
      commit;
        pack_import.write_log(lvcounter ||' cleanroombatch rows imported.');
     end;
      end if;
    exception
      when others then
        begin
          rollback;
          lverrormsg := 'cfbimport_cleanroombatch: Failed to import.';
          pack_import.write_log(lverrormsg || substr(sqlerrm, 1, 512), 3);
        end;
    end cfbimport_cleanroombatch;
    procedure cfbimport_cleanroombatchcustomer is
      lvcleanroombatchId    cleanroombatch.cleanroombatch_id%type;
      lvreasoncodeId        reasoncode.reasoncode_id%type;
      lvrouteID             route.route_id%type;
      lvdistributionPointId distributionpoint.distributionpoint_id%type;
      lv_plantid            plant.plant_id%type;
      lvcustomer_id         customer.customer_id%type;
      lvdept_id             department.department_id%type;
      lvcounter             number := 0;
    begin
      for x in (select w.businessunit,
                       w.customernumber,
                       w.deliverydate,
                       w.creationreasoncode,
                       w.routenumber,
                       w.cleanroombatchnumber,
                       w.consumptionpointnumber,
                       w.departmentnumber
                  from i_cleanroombatch w
                ) loop
        begin
          --get Plant ID
      lverrormsg := 'Business Unit  ' || x.businessunit;
          select bu.plant_id
            into lv_plantid
            from businessunit bu
           where bu.code = x.businessunit;
      --get cleanroombatch_id
      lverrormsg := 'Cleanroom Batch Number  ' || x.cleanroombatchnumber;
          select cb.cleanroombatch_id
            into lvcleanroombatchId
            from cleanroombatch cb
           where cb.cleanroombatchnumber = x.cleanroombatchnumber;
        --get customer id
       lverrormsg := 'Cleanroom Batch Customer Number ' || x.customernumber;
        select c.customer_id
             into lvcustomer_id
             from  customer c
        where c.customernumber = x.customernumber;
        --Determine first distributionpointID for customer
        if x.consumptionpointnumber is null and x.departmentnumber is null then
           lverrormsg := 'ConsumptionPoint for Customer Number ' || x.customernumber;
            select min(dp.distributionpoint_id)
            into lvdistributionPointId
            from distributionpoint dp
            join department d
              on dp.department_id = d.department_id
            join customer c
              on c.customer_id = lvcustomer_id;
         else
         -- get department id
          lverrormsg := 'Department Number ' || x.departmentnumber || ' for Customer Number ' || x.customernumber;
          lvdept_id := get_departmentid(x.departmentnumber,lvcustomer_id);
          lverrormsg := 'ConsumptionPoint ' || x.consumptionpointnumber || ' for Customer ' || x.customernumber || ' and Department '|| x.departmentnumber;
          select dp.distributionpoint_id
           into lvdistributionPointId
          from  distributionpoint dp
          where dp.distributionpointnumber = x.consumptionpointnumber
          and   dp.department_id = lvdept_id;
         end if;
         --get creationreasonID
          lverrormsg := 'Creation Reason code  ' || x.creationreasoncode;
          select r.reasoncode_id
            into lvreasoncodeId
            from reasoncode r
           where r.code = x.creationreasoncode;
          --Determine routeID
          lverrormsg := 'Route Number  ' || x.routenumber;
          select r.route_id
            into lvrouteID
            from route r
           where r.routenumber = x.routenumber
             and r.plant_id = lv_plantID
             and r.drivingday_id = getabsdaynumber(x.deliverydate);
           insert into cleanroombatchcustomer
            (cleanroombatchcustomer_id,
             cleanroombatch_id,
             distributionpoint_link_id,
             creationreasoncode_id,
             deliveryroute_id,
             deliverydate,
             systemuser_id,
             timestamp,
             customer_link_id)
          values
            (seq_cleanroombatchcustomer.nextval,
             lvcleanroombatchId,
             lvdistributionPointId,
             lvreasoncodeId,
             lvrouteID,
             x.deliverydate,
             pack_import.lvnsystemuserid,
             sysdate,
             lvcustomer_id
             );
          lvcounter := lvcounter + 1;
        exception
        when dup_val_on_index then
         null;
        when no_data_found then
         begin
          pack_import.write_log(lverrormsg || ' does not exist!', 3);
          end;
         when others then
         begin
          lverrormsg := 'cfbimport_cleanroombatchcustomer : Failed to import.';
          pack_import.write_log(lverrormsg || substr(sqlerrm, 1, 512), 3);
         end;
      end;
     end loop;
    if lvcounter > 0 then
      begin
      commit;
      pack_import.write_log(lvcounter || ' cleanroombatchcustomer rows imported.');
      end;
    end if;
   exception
    when others then
      begin
        rollback;
        pack_import.write_log('Error cfbimport_cleanroombatchcustomer: ' || sqlerrm, 5);
      end;
    end cfbimport_cleanroombatchcustomer;
  procedure cfbimport_cleanroomuidelivery is
    lv_deliverypoint_id     deliverypoint.deliverypoint_id%type;
    lv_distributionpoint_id distributionpoint.distributionpoint_id%type;
    lv_packingnote_id       packingnote.packingnote_id%type;
    lv_plantdept_id         plantdepartment.plantdepartment_id%type;
    lv_customer_id          customer.customer_id%type;
    lv_cleanroombatchid     cleanroombatch.cleanroombatch_id%type;
    lv_cleanroombatchnumber cleanroombatch.cleanroombatchnumber%type;
    lv_uniqueitem_id        uniqueitem.uniqueitem_id%type;
    lv_businessunit_id      businessunit.businessunit_id%type;
    lv_weareremployment_id  weareremployment.weareremployment_id%type;
    lv_product_id           product.product_id%type;
    lv_sizedefinition_id    sizedefinition.sizedefinition_id%type;
    lv_finishingmethod_id   finishingmethod.finishingmethod_id%type;
    countcleanroomuidelivery number := 0;
    countdvscan       number := 0;
    countrows               number := 0;
    procedure convertdeliveryscan is
    begin
      for x in (select y.scandatetime,
                       y.primaryid,
                       y.packingnotenumber,
                       y.idcodesequencenumber,
                       y.businessunit
                  from i_cleanroomuidelivery y) loop
        begin
          --Determine packingnoteid
          lverrormsg := 'Packing Note ' || x.packingnotenumber ||
                        ' for cleanroombatch ';
          select pn.packingnote_id
            into lv_packingnote_id
            from cleanroombatchpackingnote p
            join packingnote pn
              on p.packingnote_id = pn.packingnote_id
           where pn.notenumber = x.packingnotenumber
             and pn.cleanroombatch = 'Y';
          --Determine plant department id
          lverrormsg := 'Plant department for cleanroombatch ';
          select cb.plantdepartment_id,
                 cb.cleanroombatch_id,
                 cb.cleanroombatchnumber
            into lv_plantdept_id,
                 lv_cleanroombatchid,
                 lv_cleanroombatchnumber
            from cleanroombatch cb
            join cleanroombatchpackingnote p
              on cb.cleanroombatch_id = p.cleanroombatch_id
           where p.packingnote_id = lv_packingnote_id;
          --Determine customer id
          lverrormsg := 'Customer Id for cleanroombatch number ' ||
                        lv_cleanroombatchnumber;
          select crbc.customer_link_id, crbc.distributionpoint_link_id
            into lv_customer_id, lv_distributionpoint_id
            from cleanroombatchcustomer crbc
           where crbc.cleanroombatch_id = lv_cleanroombatchid;
          --Determine first delivery point for customer
          lverrormsg := 'Delivery point for customer  ' || lv_customer_id;
          select min(dp.deliverypoint_id)
            into lv_deliverypoint_id
            from deliverypoint dp
           where dp.customer_id = lv_customer_id
             and dp.active = 'Y';
          -- Determine business unit ID
          lverrormsg := 'Businessunit ' || x.businessunit;
          select bu.businessunit_id
            into lv_businessunit_id
            from businessunit bu
           where x.businessunit = bu.code;
          --Determine the uniqueitem id
          lverrormsg := 'Primary id ' || x.primaryid || ' for Business Unit ' ||
                        x.businessunit;
          select u.uniqueitem_id,un.weareremployment_id,
                 u.product_id,
                 u.sizedefinition_id,
                 u.finishingmethod_id
            into lv_uniqueitem_id,
                 lv_weareremployment_id,
                 lv_product_id,
                 lv_sizedefinition_id,
                 lv_finishingmethod_id
            from uniqueitem u
            join uniqueitemnonpool un
              on un.uniqueitem_id = u.uniqueitem_id
           where u.primaryid = x.primaryid
             and u.idcodesequencenumber = x.idcodesequencenumber
             and u.businessunit_id =
                 (select bu.businessunit_id
                    from businessunit bu
                   where bu.code = x.businessunit);
          --insert deliveryscan record
          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,
             packingnote_id,
             fromstock,
             systemuser_id,
             timestamp,
             plantdepartment_id,
             chargewashing)
          values
            (lv_businessunit_id,
             lv_uniqueitem_id,
             x.scandatetime,
             lv_customer_id,
             lv_weareremployment_id,
             lv_distributionpoint_id,
             lv_deliverypoint_id,
             lv_product_id,
             lv_sizedefinition_id,
             lv_finishingmethod_id,
             lv_packingnote_id,
             'N',
             pack_import.lvnsystemuserid,
             sysdate,
             lv_plantdept_id,
             'Y');
          countrows := countrows + 1;
        exception
          when dup_val_on_index then
            null;
          when no_data_found then
            begin
              pack_import.write_log(lverrormsg || ' does not exist!', 3);
            end;
          when others then
            begin
              lverrormsg := 'convertdeliveryscan : Failed to import.';
              pack_import.write_log(lverrormsg || substr(sqlerrm, 1, 512),3);
            end;
        end;
      end loop;
      if countrows > 0 then
        begin
         commit;
        end;
      end if;
    exception
      when others then
        begin
          rollback;
          pack_import.write_log('Error convertdeliveryscan: ' || sqlerrm,5);
        end;
    end convertdeliveryscan;
  begin
    --initialisation
    select count(1) into countcleanroomuidelivery from i_cleanroomuidelivery;
    if countcleanroomuidelivery > 0 then
      select count(*) into countdvscan from deliveryscan;
      -- start conversion
      convertdeliveryscan;
    --log messages related to conversion, checking converted numbers
    pack_import.write_log(to_char(countcleanroomuidelivery) || ' cleanroomuidelivery records in i-table.');
    pack_import.write_log(to_char(countdvscan) || ' already existed in deliveryscan.');
    pack_import.write_log(to_char(countrows) || ' deliveryscans imported this run.');
    end if;
  if countrows > 0 then
    select count(*) into countdvscan from deliveryscan;
    pack_import.write_log(to_char(countdvscan) ||' now in deliveryscan.');
    end if;
  end cfbimport_cleanroomuidelivery;
  end pack_import_sterilizationlot;
/
create or replace package pack_import_stock is
  -- Author  : PVD
  -- Created : 10-May-2004 12:31:01
  -- Update  : 20-Apr-2005
  -- Purpose : Import the stockroom data
  -- Version 1.4
  function get_stockroomid(fp_stockroomcode in stockroom.code%type) return number;
  procedure create_stockroomlocation(fpnstockroom_id                in stockroom.stockroom_id%type,
                                     fpslocationcode                in stockroomlocation.locationcode%type,
                                     fpsrowcode                     in stockroomlocation.rowcode%type, --can be null!
                                     fpsareacode                    in stockroomlocation.areacode%type, --can be null!
                                     fpnstockroomlocation_id        out stockroomlocation.stockroomlocation_id%type,
                                     fp_pickingsequence             in stockroomlocation.pickingsequence%type default 0,
                                     fp_volume                      in stockroomlocation.volume%type default 9999,
                                     fp_makeempty                   in stockroomlocation.makeempty%type default 'N',
                                     fp_overflowlocation            in stockroomlocation.overflowlocation%type default 'N',
                                     fp_standardcheckinlocation     in stockroomlocation.standardcheckinlocation%type default 'N',
                                     fp_standardprewashlocation     in stockroomlocation.standardprewashlocation%type default 'N',
                                     fp_standardwmsoverflowlocation in stockroomlocation.standardwmsoverflowlocation%type default 'N',
                                     fp_uniqueid                    in stockroomlocation.uniqueid%type default null);
  procedure import_stockdefinitionperitem;
  procedure import_stockroomquantity;
  procedure add_missing_stockroomsuppliers;
  procedure update_stockquantity_unqiue;
  procedure import_stdlocationperprodsize;
  procedure import_stockroomlocations;
end pack_import_stock;
/
create or replace package body pack_import_stock is
  fpnsupplier_id        number := 0;
  lvnerrormsg           abslog.message%type;
  gv_reasonconver_id    reasoncode.reasoncode_id%type;
  gv_stocktransactionid stocktransaction.stocktransaction_id%type;
  procedure create_stocktransaction(fp_stockreservationpergradeid in stocktransaction.stockreservationpergrade_id%type,
                                    fp_uniquestock_yn             in stocktransaction.uniquestock%type,
                                    fp_quantity                   in stocktransaction.quantity%type,
                                    fp_fromstockroomlocationid    in stocktransaction.fromstockroomlocation_id%type,
                                    fp_tostockroomlocation_id     in stocktransaction.tostockroomlocation_id%type) is
  begin
    -- create stocktransaction
    if fp_quantity <> 0 then
      begin
        --no need to create stocktransaction for quantity = 0!
        -- stock transaction = 84 stock correction
        insert into stocktransaction
          (stocktransaction_id, stockreservationpergrade_id, transactiondate, reasoncode_id,
           transactiontype_id, uniquestock, quantity, systemuser_id, timestamp, exported, delayed,
           transactiontimestamp, fromstockroomlocation_id, tostockroomlocation_id, remark,
           documenttype, documentnumber, documentnumberprefix, stockvaluationmethod,
           calculationprice)
        values
          (seq_stocktransaction.nextval, fp_stockreservationpergradeid, sysdate, gv_reasonconver_id,
           84, fp_uniquestock_yn, fp_quantity, pack_import.lvnsystemuserid, sysdate, 'N', 'N',
           sysdate, fp_fromstockroomlocationid, fp_tostockroomlocation_id, 'Conversion added', 0, 0,
           null, 0, 0)
        returning stocktransaction_id into gv_stocktransactionid;
      end;
    else
      begin
        gv_stocktransactionid := null;
      end;
    end if;
  end create_stocktransaction;
  function get_stockroomid(fp_stockroomcode in stockroom.code%type) return number is
    lv_stockroomid stockroom.stockroom_id%type;
  begin
    -- determine the stock room
    lvnerrormsg := ' stockroomcode ' || nvl(fp_stockroomcode, 'NULL');
    if fp_stockroomcode is null then
      return null;
    else
      begin
        select s.stockroom_id into lv_stockroomid from stockroom s where s.code = fp_stockroomcode;
        return lv_stockroomid;
      end;
    end if;
  exception
    when no_data_found then
      begin
        pack_import.write_log('No data found ' || lvnerrormsg, 3);
        return null;
      end;
  end get_stockroomid;
  procedure create_stockroomlocation(fpnstockroom_id                in stockroom.stockroom_id%type,
                                     fpslocationcode                in stockroomlocation.locationcode%type,
                                     fpsrowcode                     in stockroomlocation.rowcode%type, --can be null!
                                     fpsareacode                    in stockroomlocation.areacode%type, --can be null!
                                     fpnstockroomlocation_id        out stockroomlocation.stockroomlocation_id%type,
                                     fp_pickingsequence             in stockroomlocation.pickingsequence%type default 0,
                                     fp_volume                      in stockroomlocation.volume%type default 9999,
                                     fp_makeempty                   in stockroomlocation.makeempty%type default 'N',
                                     fp_overflowlocation            in stockroomlocation.overflowlocation%type default 'N',
                                     fp_standardcheckinlocation     in stockroomlocation.standardcheckinlocation%type default 'N',
                                     fp_standardprewashlocation     in stockroomlocation.standardprewashlocation%type default 'N',
                                     fp_standardwmsoverflowlocation in stockroomlocation.standardwmsoverflowlocation%type default 'N',
                                     fp_uniqueid                    in stockroomlocation.uniqueid%type default null) is
    lv_stockroomid stockroom.stockroom_id%type;
  begin
    fpnstockroomlocation_id := null;
    -- check if stockroom exist. it must exist.
    lvnerrormsg := 'stockroom_id ' || fpnstockroom_id;
    select s.stockroom_id
    into   lv_stockroomid
    from   stockroom s
    where  s.stockroom_id = fpnstockroom_id;
    begin
      -- get the stockroom location.
      lvnerrormsg := 'get/create_stockroomlocation';
      select l.stockroomlocation_id
      into   fpnstockroomlocation_id
      from   stockroomlocation l
      where  l.stockroom_id = lv_stockroomid
      and    trim(upper(l.locationcode)) = trim(upper(fpslocationcode))
      and    (trim(upper(l.rowcode)) = trim(upper(fpsrowcode)) or
            (trim(l.rowcode) is null and trim(fpsrowcode) is null))
      and    (trim(upper(l.areacode)) = trim(upper(fpsareacode)) or
            (trim(l.areacode) is null and trim(fpsareacode) is null));
    exception
      when no_data_found then
        begin
          insert into stockroomlocation
            (stockroomlocation_id, stockroom_id, rowcode, locationcode, areacode, uniqueid,
             pickingsequence, volume, systemuser_id, makeempty, timestamp, overflowlocation,
             standardcheckinlocation, standardprewashlocation, standardwmsoverflowlocation)
          values
            (seq_stockroomlocation.nextval, fpnstockroom_id, upper(fpsrowcode),
             upper(fpslocationcode), upper(fpsareacode), fp_uniqueid, nvl(fp_pickingsequence, 0),
             nvl(fp_volume, 9999), pack_import.lvnsystemuserid, nvl(fp_makeempty, 'N'), sysdate,
             nvl(fp_overflowlocation, 'N'), nvl(fp_standardcheckinlocation, 'N'),
             nvl(fp_standardprewashlocation, 'N'), nvl(fp_standardwmsoverflowlocation, 'N'))
          returning stockroomlocation_id into fpnstockroomlocation_id;
          commit;
          pack_import.write_log(fpslocationcode || ' stock room location created.');
        end;
    end;
  exception
    when others then
      lvnerrormsg := 'Error create_stockroomlocation: ';
      pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      raise;
  end create_stockroomlocation;
  procedure import_stockdefinitionperitem is
    lvncustomerid customer.customer_id%type;
    lvnsupplierid supplier.supplier_id%type;
  begin
    for x in (select i.*, sr.stockroom_id, p.product_id, s.sizedefinition_id
              from   i_stockdefinitionperitem i, stockroom sr, product p, sizedefinition s
              where  i.stockroomcode = sr.code
              and    i.productcode = p.code
              and    i.sizecode = s.code) loop
      begin
        --get customer
        if x.customernumber is null then
          lvncustomerid := null;
        else
          lvnerrormsg := 'customer ' || x.customernumber;
          select c.customer_id
          into   lvncustomerid
          from   customer c
          where  c.customernumber = x.customernumber;
        end if;
        --get supplier
        lvnerrormsg := 'supplier ' || x.defaultsuppliernumber;
        select sp.supplier_id
        into   lvnsupplierid
        from   supplier sp
        where  sp.suppliernumber = x.defaultsuppliernumber;
        --insert stockdefinitionperitem
        insert into stockdefinitionperitem
          (stockdefinitionperitem_id, stockroom_id, product_id, sizedefinition_id, customer_id,
           customerowned, minqtynew, minqtyused, maxqtynew, maxqtyused, systemuser_id, timestamp,
           defaultsupplier_id)
        values
          (seq_stockdefinitionperitem.nextval, x.stockroom_id, x.product_id, x.sizedefinition_id,
           lvncustomerid, x.customerowned, x.minqtynew, x.minqtyused, x.maxqtynew, x.maxqtyused,
           pack_import.lvnsystemuserid, sysdate, lvnsupplierid);
      exception
        when dup_val_on_index then
          null; --no update!
        when no_data_found then
          begin
            lvnerrormsg := ' Error Import_stockdefinitionperitem ' || lvnerrormsg || ' not found!';
          end;
      end;
    end loop;
  exception
    when others then
      begin
        lvnerrormsg := 'Error import_stockdefinitionperitem ';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end import_stockdefinitionperitem;
  procedure import_stockroomquantity is
    error_customerrelatedstock exception;
    fpnstockroom_id                stockroom.stockroom_id%type;
    fpnstockroomlocation_id        stockroomlocation.stockroomlocation_id%type;
    fpnproduct_id                  product.product_id%type;
    fpnsizedefinition_id           sizedefinition.sizedefinition_id%type;
    fpncustomer_id                 customer.customer_id%type;
    fpnstockdefinitionperitem_id   stockdefinitionperitem.stockdefinitionperitem_id%type;
    lvncounter                     number;
    lvndupcnt                      number;
    fpnqualitygrade_id             qualitygrade.qualitygrade_id%type;
    fpnstockreservationpergrade_id stockreservationpergrade.stockreservationpergrade_id%type;
    fpnsupplier_id                 supplier.supplier_id%type;
    fpndummy                       number;
    lv_currencyid                  currency.currency_id%type;
  begin
    --first import stockdefinitionperitem
    import_stockdefinitionperitem;
    --secondly import stockroomlocations
    import_stockroomlocations;
    -- check customer related stock
    for y in (select z.stockroomcode, z.locationcode, z.rowcode, z.areacode, z.productcode,
                     count(distinct z.customernumber)
              from   (select u.stockroomcode, u.locationcode, u.rowcode, u.stockroomareacode areacode,
                              u.productcode, nvl(u.relatedcustomernumber, 0) customernumber
                       from   i_uniqueitem u
                       where  u.stockroomcode is not null
                       and    u.locationcode is not null
                       group  by u.stockroomcode, u.locationcode, u.rowcode, u.stockroomareacode,
                                 u.productcode, nvl(u.relatedcustomernumber, 0)
                       union
                       select q.stockroomcode, q.locationcode, q.rowcode, q.areacode, q.productcode,
                              nvl(q.customernumber, 0) customernumber
                       from   i_stockroomquantity q
                       where  q.stockroomcode is not null
                       and    q.locationcode is not null
                       group  by q.stockroomcode, q.locationcode, q.rowcode, q.areacode, q.productcode,
                                 nvl(q.customernumber, 0)) z
              group  by z.stockroomcode, z.locationcode, z.rowcode, z.areacode, z.productcode
              having count(distinct z.customernumber) > 1) loop
      begin
        lvnerrormsg := 'Error: There are stockrooms locations that have both customerrelated and not customer related stock!';
        raise error_customerrelatedstock;
      end;
    end loop; --y  check customer related stock
    lvncounter := 0;
    lvndupcnt  := 0;
    for x in (select * from i_stockroomquantity) loop
      begin
        -- determine the stock room
        fpnstockroom_id := get_stockroomid(x.stockroomcode);
        -- create stockroom location
        lvnerrormsg := ' could not be created/retrieved locationcode ' || x.locationcode;
        create_stockroomlocation(fpnstockroom_id, x.locationcode, x.rowcode, x.areacode,
                                 fpnstockroomlocation_id, x.pickingsequence, x.volume);
        -- get supplier
        lvnerrormsg := ' suppliernumber ' || x.suppliernumber;
        if x.suppliernumber is null then
          fpnsupplier_id := null;
        else
          select s.supplier_id
          into   fpnsupplier_id
          from   supplier s
          where  s.suppliernumber = x.suppliernumber;
        end if;
        begin
          -- test stockroom supplier
          lvnerrormsg := 'suppliernumber  ' || x.suppliernumber || ' stockroomcode ' ||
                         x.stockroomcode;
          select l.stockroom_id
          into   fpndummy
          from   stockroomsupplier l
          where  l.supplier_id = fpnsupplier_id
          and    l.stockroom_id = fpnstockroom_id;
        exception
          when no_data_found then
            begin
              insert into stockroomsupplier
                (stockroom_id, supplier_id, buyercode, systemuser_id, timestamp)
              values
                (fpnstockroom_id, fpnsupplier_id, null, pack_import.lvnsystemuserid, sysdate);
            end;
        end;
        -- get product
        lvnerrormsg := ' productcode ' || x.productcode;
        select p.product_id into fpnproduct_id from product p where p.code = trim(x.productcode);
        -- get size
        lvnerrormsg := ' sizecode ' || x.sizecode;
        select s.sizedefinition_id
        into   fpnsizedefinition_id
        from   sizedefinition s
        where  s.code = trim(x.sizecode);
        begin
          -- test supplier product
          lvnerrormsg := 'suppliernumber  ' || x.suppliernumber || ' productcode ' || x.productcode;
          select r.supplier_id
          into   fpndummy
          from   supplier r
          where  r.supplier_id = fpnsupplier_id
          and    (exists (select s.supplier_id
                          from   supplierproduct s
                          where  s.supplier_id = r.supplier_id
                          and    s.supplier_id = fpnsupplier_id
                          and    s.supplierproductcode = trim(x.productcode)) or exists
                 (select 1
                   from   supplierproduct s
                   join   productsizepersupproduct psps
                   on     psps.supplierproduct_id = s.supplierproduct_id
                   where  s.supplier_id = r.supplier_id
                   and    s.supplier_id = fpnsupplier_id
                   and    psps.product_id = fpnproduct_id));
        exception
          when no_data_found then
            begin
              -- create supplier product
              insert into supplierproduct
                (supplierproduct_id, supplier_id, supplierproductcode, supplierproductdescription,
                 suppliersizecode,
                 --product_id,
                 --sizedefinition_id,
                 deliverydays, minorderqty, boxquantity, uniqueitem, active, remark, systemuser_id,
                 timestamp)
              values
                (seq_supplierproduct.nextval, fpnsupplier_id, trim(x.productcode),
                 trim(x.productcode), trim(x.sizecode),
                 --fpnproduct_id,
                 --fpnsizedefinition_id,
                 1, 1, 1, 'N', 'Y', null, pack_import.lvnsystemuserid, sysdate);
              -- create supplier product price
              insert into supplierproductprice
                (supplierproductprice_id, supplierproduct_id, startdate, purchaseprice,
                 systemuser_id, timestamp)
              values
                (seq_supplierproductprice.nextval, seq_supplierproduct.currval,
                 to_date('1-1-2000', 'dd-mm-yyyy'), 0, pack_import.lvnsystemuserid, sysdate);
            end;
        end;
        -- get customer
        lvnerrormsg := ' customernumber ' || x.customernumber;
        if x.customernumber is null then
          fpncustomer_id := null;
        else
          select c.customer_id
          into   fpncustomer_id
          from   customer c
          where  c.customernumber = x.customernumber;
        end if;
        -- get quality grade.
        if x.qualitygradecode is null then
          begin
            lvnerrormsg := ' no (or more then 1) default qualitygradecode defined.';
            select g.qualitygrade_id
            into   fpnqualitygrade_id
            from   qualitygrade g
            where  g.defaultqualitygrade = 'Y';
          end;
        else
          begin
            fpnqualitygrade_id := pack_import.getqualitygradeid(x.qualitygradecode);
          end;
        end if;
        begin
          -- create stockdefinitionperitem
          lvnerrormsg := ' insert/select stockdefinitionperitem failed ';
          insert into stockdefinitionperitem
            (stockdefinitionperitem_id, stockroom_id, product_id, sizedefinition_id, customer_id,
             customerowned, minqtynew, minqtyused, maxqtynew, maxqtyused, systemuser_id, timestamp,
             defaultsupplier_id)
          values
            (seq_stockdefinitionperitem.nextval, fpnstockroom_id, fpnproduct_id,
             fpnsizedefinition_id, fpncustomer_id, x.customerowned, 0, 0, 999, 999,
             pack_import.lvnsystemuserid, sysdate, fpnsupplier_id)
          returning stockdefinitionperitem_id into fpnstockdefinitionperitem_id;
        exception
          when dup_val_on_index then
            if fpncustomer_id is null then
              select d.stockdefinitionperitem_id
              into   fpnstockdefinitionperitem_id
              from   stockdefinitionperitem d
              where  d.stockroom_id = fpnstockroom_id
              and    d.product_id = fpnproduct_id
              and    d.sizedefinition_id = fpnsizedefinition_id
              and    d.customerowned = x.customerowned
              and    d.customer_id is null;
            else
              select d.stockdefinitionperitem_id
              into   fpnstockdefinitionperitem_id
              from   stockdefinitionperitem d
              where  d.stockroom_id = fpnstockroom_id
              and    d.product_id = fpnproduct_id
              and    d.sizedefinition_id = fpnsizedefinition_id
              and    d.customer_id = fpncustomer_id
              and    d.customerowned = x.customerowned;
            end if;
        end;
        begin
          -- create stockreservationpergrade
          lvnerrormsg := ' insert/select stockreservationpergrade failed ';
          insert into stockreservationpergrade
            (stockreservationpergrade_id, stockdefinitionperitem_id, qualitygrade_id,
             qtyuniquereserved, qtynonuniquereserved, qtyuniquewiithmodifreserved, qtynonunique,
             qtyuniqueordered, qtynonuniqueordered, systemuser_id, timestamp,
             qtyuniqueordereddirectissue, qtynonuniqueordereddirectissue)
          values
            (seq_stockreservationpergrade.nextval, fpnstockdefinitionperitem_id, fpnqualitygrade_id,
             0, 0, 0, 0,
             0, 0, pack_import.lvnsystemuserid, sysdate, 0, 0)
          returning stockreservationpergrade_id into fpnstockreservationpergrade_id;
        exception
          when dup_val_on_index then
            select sg.stockreservationpergrade_id
            into fpnstockreservationpergrade_id
            from stockreservationpergrade sg
            where sg.stockdefinitionperitem_id = fpnstockdefinitionperitem_id
            and sg.qualitygrade_id = fpnqualitygrade_id;
        end;
        begin
          -- create stockquantity
          lvnerrormsg           := 'Error import_stock; insert stockquantity failed! ';
          gv_stocktransactionid := null;
          insert into stockquantity
            (stockreservationpergrade_id, stockroomlocation_id, qtyunique,
             qtyuniquewithmodifications, systemuser_id, timestamp, qtynonunique)
          values
            (fpnstockreservationpergrade_id, fpnstockroomlocation_id, 0, 0,
             pack_import.lvnsystemuserid, sysdate, x.quantitynonunique);
          --create_stocktransaction
          create_stocktransaction(fpnstockreservationpergrade_id, 'N', x.quantitynonunique, null,
                                  fpnstockroomlocation_id);
          -- count number of i_stockroomquantity records imported.
          lvncounter := lvncounter + 1;
        exception
          when dup_val_on_index then
              begin
                update stockquantity q
                set    q.qtynonunique = x.quantitynonunique,
                       q.systemuser_id = pack_import.lvnsystemuserid, q.timestamp = sysdate
                where  q.stockreservationpergrade_id = fpnstockreservationpergrade_id
                and    q.stockroomlocation_id = fpnstockroomlocation_id
                and    q.qtynonunique = 0; --only update if there was NO None Unique stock before!
                if sql%rowcount = 0 then
                  begin
                    lvndupcnt := lvndupcnt + 1;
                  end;
                else
                  begin
                    --create_stocktransaction
                    create_stocktransaction(fpnstockreservationpergrade_id, 'N',
                                            x.quantitynonunique, null, fpnstockroomlocation_id);
                    -- count number of i_stockroomquantity records imported.
                    lvncounter := lvncounter + 1;
                  end;
                end if;
              end;
        end;
        if x.avgpurchaseprice is not null and x.stockvalue_currency is not null then
          begin
            --get currency id
            lvnerrormsg := 'currency ' || x.stockvalue_currency;
            select cy.currency_id
            into   lv_currencyid
            from   currency cy
            where  cy.code = x.stockvalue_currency;
            --create_avgpurchaseprice
            lvnerrormsg := 'create_avgpurchaseprice';
            create_avgpurchaseprice(fpnstockroom_id, 1, 2, fpnproduct_id, fpnsizedefinition_id,
                                    fpnqualitygrade_id, x.customerowned, fpncustomer_id,
                                    x.avgpurchaseprice, lv_currencyid, null, null,
                                    gv_stocktransactionid, null, pack_import.lvnsystemuserid,
                                    lvnerrormsg);
            if lvnerrormsg <> 'Ok' then
              begin
                pack_import.write_log('create_avgpurchaseprice ' || lvnerrormsg, -3);
              end;
            end if;
          end;
        end if;
      exception
        when no_data_found then
          lvnerrormsg := 'Error import_stock; ' || lvnerrormsg || ' does not exist!';
          pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    commit;
    if lvncounter <> 0 then
      pack_import.write_log('Import_stockroomquantity ' || to_char(lvncounter) ||
                            ' records from i_stockroomquantity inserted.');
    end if;
    if lvndupcnt <> 0 then
      pack_import.write_log('Import_stockroomquantity ' || to_char(lvndupcnt) ||
                            ' records from i_stockroomquantity did already exist and were NOT updated.');
    end if;
    import_stdlocationperprodsize;
  exception
    when error_customerrelatedstock then
      begin
        pack_import.write_log('Error during Import_stockroomquantity ' || lvnerrormsg, 3);
      end;
    when others then
      begin
        rollback;
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end import_stockroomquantity;
  procedure add_missing_stockroomsuppliers is
    lv_counter number := 0;
  begin
    --add missing stockroom suppliers
    lvnerrormsg := 'add missing stockroomsuppliers ';
    insert into stockroomsupplier
      (stockroom_id, supplier_id, buyercode, systemuser_id, timestamp)
      select sti.stockroom_id, sti.defaultsupplier_id, null, pack_import.lvnsystemuserid, sysdate
      from   stockdefinitionperitem sti
      where  not exists (select 1
              from   stockroomsupplier s
              where  s.supplier_id = sti.defaultsupplier_id
              and    s.stockroom_id = sti.stockroom_id)
      group  by sti.stockroom_id, sti.defaultsupplier_id;
    lv_counter := sql%rowcount;
    commit;
    if lv_counter > 0 then
      begin
        pack_import.write_log(to_char(lv_counter) || ' missing stockroomsupplier records added');
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end add_missing_stockroomsuppliers;
  procedure update_uniqueitemstock is
    stockroomlocationid stockroomlocation.stockroomlocation_id%type;
    statusstockid       status.status_id%type;
    stockroomid         stockroom.stockroom_id%type;
  begin
    -- check and update if needed all unique items on stock
    pack_import.write_log('Import Stock Update Uniqueitemstock');
    -- determine status
    select s.status_id
    into   statusstockid
    from   status s
    where  s.statustype = 'UI'
    and    s.code = '10';
    -- check stockroomlocations for all converted uniqueitems on stock
    for c1 in (select ui.businessunit_id, bu.code
               from   uniqueitem ui, uniqueitemfixedinfo uif, product p, businessunit bu,
                      i_uniqueitem i
               where  ui.uniqueitem_id = uif.uniqueitem_id
               and    ui.primaryid = i.primaryid
               and    i.businessunit = bu.code
               and    ui.product_id = p.product_id
               and    ui.businessunit_id = bu.businessunit_id
               and    ui.status_id = statusstockid
               and    p.recordpassivestock = 'Y'
               and    uif.stockroomlocation_id is null
               group  by ui.businessunit_id, bu.code) loop
      begin
        -- determine stockroom location
        stockroomlocationid := null;
        for c2 in (select sl.stockroomlocation_id
                   from   stockroomsservicingbu sbu, stockroomlocation sl
                   where  sbu.stockroom_id = sl.stockroom_id
                   and    sbu.businessunit_id = c1.businessunit_id
                   order  by sbu.priority asc) loop
          stockroomlocationid := c2.stockroomlocation_id;
          exit;
        end loop;
        -- create stockroomlocationid if needed
        if (stockroomlocationid is null) then
          pack_import.write_log('No stock room location - found for BU ' || c1.code);
          begin
            select sbu.stockroom_id
            into   stockroomid
            from   stockroomsservicingbu sbu
            where  sbu.businessunit_id = c1.businessunit_id
            and    sbu.priority = (select min(x.priority)
                                   from   stockroomsservicingbu x
                                   where  x.businessunit_id = sbu.businessunit_id);
            --get stockroomlocation
            create_stockroomlocation(stockroomid, '-', '-', null, stockroomlocationid, 9999, 9999,
                                     'Y', 'Y');
            pack_import.write_log('Stock room location - created for BU ' || c1.code);
          exception
            when others then
              null;
          end;
        end if;
        -- update uniqueitemfixed with location
        if (stockroomlocationid is not null) then
          begin
            update uniqueitemfixedinfo uif
            set    uif.stockroomlocation_id = stockroomlocationid, uif.timestamp = sysdate,
                   uif.systemuser_id = pack_import.lvnsystemuserid
            where  uif.stockroomlocation_id is null
            and    exists (select ui.uniqueitem_id
                    from   uniqueitem ui, product p, i_uniqueitem i
                    where  ui.uniqueitem_id = uif.uniqueitem_id
                    and    i.primaryid = ui.primaryid
                    and    i.businessunit = c1.code
                    and    ui.product_id = p.product_id
                    and    ui.businessunit_id = c1.businessunit_id
                    and    p.recordpassivestock = 'Y'
                    and    ui.status_id = statusstockid);
            pack_import.write_log(sql%rowcount || ' unique items updated for Businessunit code ' ||
                                  c1.code);
          end;
        end if;
      end;
    end loop;
    commit;
  exception
    when others then
      rollback;
      lvnerrormsg := 'Error update_uniqueitemstock: ';
      pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
  end update_uniqueitemstock;
  procedure update_stockquantity_unqiue is
    statusstockid   status.status_id%type;
    stockdefitemid  stockdefinitionperitem.stockdefinitionperitem_id%type;
    stockresgradeid stockreservationpergrade.stockreservationpergrade_id%type;
    stdlocperprodid standardlocationperproduct.standardlocationperproduct_id%type;
    qtyui           stockquantity.qtyunique%type;
    qtyuim          stockquantity.qtyuniquewithmodifications%type;
    countlines      int := 0;
    newline         boolean;
    countstockdef   int := 0;
    countstockres   int := 0;
    countstockqty   int := 0;
    countstdloc     int := 0;
  begin
    -- check and update if needed all unique items on stock
    update_uniqueitemstock;
    -- get the right status.
    select s.status_id
    into   statusstockid
    from   status s
    where  s.statustype = 'UI'
    and    s.code = '10';
    for c in (select /*+full(ui) full(uifi) full(sl)*/
               sl.stockroom_id, sl.stockroomlocation_id, ui.product_id, ui.sizedefinition_id,
               ui.relatedcustomer_id, ui.customerowned, uifi.qualitygrade_id,
               (select p.supplier_id from product p where p.product_id = ui.product_id) supplier_id,
               sl.overflowlocation,
               sum((select count(1)
                    from   dual
                    where  not exists (select uim.uniqueitem_id
                            from   uniqueitemmodification uim, modification m
                            where  uim.uniqueitem_id = ui.uniqueitem_id
                            and    uim.modification_id = m.modification_id
                            and    m.stockwithstandardsize = 'N'))) cui,
               sum((select count(distinct uim.uniqueitem_id)
                    from   uniqueitemmodification uim, modification m
                    where  uim.uniqueitem_id = ui.uniqueitem_id
                    and    uim.modification_id = m.modification_id
                    and    m.stockwithstandardsize = 'N')) cuim
              from   uniqueitem ui, uniqueitemfixedinfo uifi, stockroomlocation sl
              where  ui.uniqueitem_id = uifi.uniqueitem_id
              and    uifi.stockroomlocation_id = sl.stockroomlocation_id
              and    uifi.qualitygrade_id is not null
              and    ui.status_id = statusstockid
              group  by sl.stockroom_id, sl.stockroomlocation_id, ui.product_id, ui.sizedefinition_id,
                        ui.relatedcustomer_id, ui.customerowned, uifi.qualitygrade_id,
                        sl.overflowlocation) loop
      begin
        newline := false;
        -- stockdefinitionperitem
        begin
          if (c.relatedcustomer_id is not null) then
            select sdpi.stockdefinitionperitem_id
            into   stockdefitemid
            from   stockdefinitionperitem sdpi
            where  sdpi.stockroom_id = c.stockroom_id
            and    sdpi.product_id = c.product_id
            and    sdpi.sizedefinition_id = c.sizedefinition_id
            and    sdpi.customer_id = c.relatedcustomer_id
            and    sdpi.customerowned = c.customerowned;
          else
            select sdpi.stockdefinitionperitem_id
            into   stockdefitemid
            from   stockdefinitionperitem sdpi
            where  sdpi.stockroom_id = c.stockroom_id
            and    sdpi.product_id = c.product_id
            and    sdpi.sizedefinition_id = c.sizedefinition_id
            and    sdpi.customer_id is null
            and    sdpi.customerowned = c.customerowned;
          end if;
        exception
          when no_data_found then
            insert into stockdefinitionperitem
              (stockdefinitionperitem_id, stockroom_id, product_id, sizedefinition_id, customer_id,
               customerowned, minqtynew, minqtyused, maxqtynew, maxqtyused, defaultsupplier_id,
               systemuser_id, timestamp)
            values
              (seq_stockdefinitionperitem.nextval, c.stockroom_id, c.product_id,
               c.sizedefinition_id, c.relatedcustomer_id, c.customerowned, 0, 0, 999, 999,
               c.supplier_id, pack_import.lvnsystemuserid, sysdate)
            returning stockdefinitionperitem_id into stockdefitemid;
            countstockdef := countstockdef + 1;
            newline       := true;
        end;
        -- stockreservationpergrade
        begin
          select srpg.stockreservationpergrade_id
          into   stockresgradeid
          from   stockreservationpergrade srpg
          where  srpg.stockdefinitionperitem_id = stockdefitemid
          and    srpg.qualitygrade_id = c.qualitygrade_id;
        exception
          when no_data_found then
            insert into stockreservationpergrade
              (stockreservationpergrade_id, stockdefinitionperitem_id, qualitygrade_id,
               qtyuniquereserved, qtynonuniquereserved, qtyuniquewiithmodifreserved, qtynonunique,
               qtyuniqueordered, qtynonuniqueordered, qtyuniqueordereddirectissue,
               qtynonuniqueordereddirectissue, systemuser_id, timestamp)
            values
              (seq_stockreservationpergrade.nextval, stockdefitemid, c.qualitygrade_id, 0, 0, 0, 0,
               0, 0, 0, 0, pack_import.lvnsystemuserid, sysdate)
            returning stockreservationpergrade_id into stockresgradeid;
            countstockres := countstockres + 1;
            newline       := true;
        end;
        -- stockquantity
        begin
          select sq.qtyunique, sq.qtyuniquewithmodifications
          into   qtyui, qtyuim
          from   stockquantity sq
          where  sq.stockreservationpergrade_id = stockresgradeid
          and    sq.stockroomlocation_id = c.stockroomlocation_id;
          if (c.cui != qtyui or c.cuim != qtyuim) then
            update stockquantity
            set    qtyunique = c.cui, qtyuniquewithmodifications = c.cuim,
                   systemuser_id = pack_import.lvnsystemuserid, timestamp = sysdate
            where  stockreservationpergrade_id = stockresgradeid
            and    stockroomlocation_id = c.stockroomlocation_id;
            --create_stocktransaction
            --stock correction
            create_stocktransaction(stockresgradeid, 'Y', ((c.cui - qtyui) + (c.cuim - qtyuim)),
                                    null, c.stockroomlocation_id);
            countstockqty := countstockqty + 1;
            newline       := true;
          end if;
        exception
          when no_data_found then
            insert into stockquantity
              (stockreservationpergrade_id, stockroomlocation_id, qtyunique,
               qtyuniquewithmodifications, systemuser_id, timestamp)
            values
              (stockresgradeid, c.stockroomlocation_id, c.cui, c.cuim, pack_import.lvnsystemuserid,
               sysdate);
            --create_stocktransaction
            create_stocktransaction(stockresgradeid, 'Y', (c.cui + c.cuim), null,
                                    c.stockroomlocation_id);
            countstockqty := countstockqty + 1;
            newline       := true;
        end;
        -- standardlocationperproduct
        if (c.overflowlocation != 'Y') then
          begin
            select slpp.standardlocationperproduct_id
            into   stdlocperprodid
            from   standardlocationperproduct slpp
            where  slpp.stockroomlocation_id = c.stockroomlocation_id
            and    slpp.product_id = c.product_id;
          exception
            when no_data_found then
              insert into standardlocationperproduct
                (standardlocationperproduct_id, stockroomlocation_id, product_id, priority,
                 customerowned, customer_id, allowedgrade, definepersize, active, systemuser_id,
                 timestamp)
              values
                (seq_standardlocationperproduct.nextval, c.stockroomlocation_id, c.product_id, 1,
                 c.customerowned, c.relatedcustomer_id, 'B', 'N', 'Y', pack_import.lvnsystemuserid,
                 sysdate);
              countstdloc := countstdloc + 1;
              newline     := true;
          end;
        end if;
        --if newline then dbms_output.new_line; end if;
        countlines := countlines + 1;
      end;
    end loop;
    commit;
    if countstockdef > 0 then
      pack_import.write_log(countstockdef || ' stock definition per item lines inserted.');
    end if;
    if countstockres > 0 then
      pack_import.write_log(countstockres || ' stock reservation per grade lines inserted.');
    end if;
    if countstockqty > 0 then
      pack_import.write_log(countstockqty || ' stock quantity lines inserted or updated.');
    end if;
    if countstdloc > 0 then
      pack_import.write_log(countstdloc || ' standard location per product lines inserted.');
    end if;
  exception
    when others then
      rollback;
      lvnerrormsg := 'Error update_stockquantity: ';
      pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
  end update_stockquantity_unqiue;
  procedure import_stdlocationperprodsize is
    lv_count                     number := 0;
    lv_errorcount                number := 0;
    lv_stockroomid               stockroom.stockroom_id%type;
    lv_stockroomlocationid       stockroomlocation.stockroomlocation_id%type;
    lv_productid                 product.product_id%type;
    lv_sizeid                    sizedefinition.sizedefinition_id%type;
    lv_definepersize             standardlocationperproduct.definepersize%type;
    lv_customerid                customer.customer_id%type;
    lv_standardlocationperprodid standardlocationperproduct.standardlocationperproduct_id%type;
  begin
    --import_stdlocationperproductsize
    lvnerrormsg := 'import_stdlocationperprodsize process table i_stdlocationperproductsize';
    for stp in (select * from i_stdlocationperproductsize ips) loop
      begin
        --get_stockroomid
        lv_stockroomid := get_stockroomid(stp.stockroomcode);
        --get productid
        lvnerrormsg := ' get product code ' || nvl(stp.productcode, 'NULL');
        select p.product_id into lv_productid from product p where p.code = stp.productcode;
        --get sizeid
        if stp.sizecode is null then
          begin
            lv_sizeid        := null;
            lv_definepersize := 'N';
          end;
        else
          begin
            lvnerrormsg := ' size code ' || stp.sizecode;
            begin
              select s.sizedefinition_id
              into   lv_sizeid
              from   sizedefinition s
              where  s.code = stp.sizecode;
            exception
              when no_data_found then
                begin
                  pack_import.cfbcreate_sizedefinition(lv_sizeid, stp.sizecode, 'N', null, null,
                                                       null, 'N');
                  pack_import.cfbcreate_sizedefinition_desc(lv_sizeid, stp.sizecode);
                end;
            end;
            lv_definepersize := 'Y';
          end;
        end if; --sizecode
        if stp.customernumber is null then
          begin
            lv_customerid := null;
          end;
        else
          begin
            lvnerrormsg := ' customer number ' || to_char(stp.customernumber);
            select c.customer_id
            into   lv_customerid
            from   customer c
            where  c.customernumber = stp.customernumber;
          end;
        end if; -- customer
        --get stockroomlocation
        create_stockroomlocation(lv_stockroomid, stp.locationcode, stp.rowcode, stp.areacode,
                                 lv_stockroomlocationid);
        --select standardlocationperproduct
        begin
          lvnerrormsg := 'import_stdlocationperprodsize, select standardlocationperproduct';
          select spp.standardlocationperproduct_id
          into   lv_standardlocationperprodid
          from   standardlocationperproduct spp
          where  spp.stockroomlocation_id = lv_stockroomlocationid
          and    spp.product_id = lv_productid;
        exception
          when no_data_found then
            begin
              --insert standardlocationperproduct
              lvnerrormsg := 'import_stdlocationperprodsize, insert into standardlocationperproduct';
              insert into standardlocationperproduct
                (standardlocationperproduct_id, stockroomlocation_id, product_id, priority,
                 customerowned, customer_id, allowedgrade, definepersize, active, systemuser_id,
                 timestamp, standardtruckload)
              values
                (seq_standardlocationperproduct.nextval, lv_stockroomlocationid, lv_productid,
                 stp.priority, stp.customerowned, lv_customerid, stp.allowedgrade, lv_definepersize,
                 'Y', pack_import.lvnsystemuserid, sysdate, stp.standardtruckload)
              returning standardlocationperproduct_id into lv_standardlocationperprodid;
            end;
        end;
        if lv_sizeid is not null then
          begin
            lvnerrormsg := 'import_stdlocationperprodsize, insert into standardlocationpersize';
            insert into standardlocationpersize
              (standardlocationperproduct_id, sizedefinition_id, systemuser_id, timestamp,
               standardtruckload)
            values
              (lv_standardlocationperprodid, lv_sizeid, pack_import.lvnsystemuserid, sysdate,
               stp.standardtruckload);
          exception
            when dup_val_on_index then
              --no problem when it did already exist!
              null;
          end;
        end if;
        commit;
        lv_count := lv_count + 1;
      exception
        when no_data_found then
          begin
            rollback;
            lv_errorcount := lv_errorcount + 1;
            pack_import.write_log('Error during import i_stdlocationperproductsize ' ||
                                  lvnerrormsg || ' not found!', 3);
          end;
        when others then
          begin
            rollback;
            lv_errorcount := lv_errorcount + 1;
            pack_import.write_log(lvnerrormsg || ' see debug info ', 3);
            pack_import.write_log(sqlerrm, 5);
          end;
      end;
    end loop; --stp
    if lv_errorcount > 0 then
      begin
        pack_import.write_log('Warning import_stdlocationperprodsize ' || to_char(lv_errorcount) ||
                              ' errors during import from i_stdlocationperproductsize', 3);
      end;
    end if; --lv_count
    if lv_count > 0 then
      begin
        pack_import.write_log('import_stdlocationperprodsize succesfully processed ' ||
                              to_char(lv_count) || ' records from i_stdlocationperproductsize');
      end;
    end if; --lv_count
  end import_stdlocationperprodsize;
  procedure import_stockroomlocations is
    lv_stockroomlocationid stockroomlocation.stockroomlocation_id%type;
    lv_count               number := 0;
  begin
    for xx in (select st.stockroom_id, stli.rowcode, stli.locationcode, stli.areacode,
                      stli.pickingsequence, stli.volume, stli.uniqueid, stli.makeempty,
                      stli.overflowlocation, stli.standardcheckinlocation,
                      stli.standardprewashlocation, stli.standardwmsoverflowlocation
               from   i_stockroomlocation stli
               join   stockroom st
               on     st.code = stli.stockroomcode
               where  not exists
                (select 1
                       from   stockroomlocation l
                       where  l.stockroom_id = st.stockroom_id
                       and    trim(upper(l.locationcode)) = trim(upper(stli.locationcode))
                       and    (trim(upper(l.rowcode)) = trim(upper(stli.rowcode)) or
                             (trim(l.rowcode) is null and trim(stli.rowcode) is null))
                       and    (trim(upper(l.areacode)) = trim(upper(stli.areacode)) or
                             (trim(l.areacode) is null and trim(stli.areacode) is null)))) loop
      begin
        --create_stockroomlocation
        create_stockroomlocation(xx.stockroom_id, xx.locationcode, xx.rowcode, xx.areacode,
                                 lv_stockroomlocationid, xx.pickingsequence, xx.volume, xx.makeempty,
                                 xx.overflowlocation, xx.standardcheckinlocation,
                                 xx.standardprewashlocation, xx.standardwmsoverflowlocation,
                                 xx.uniqueid);
        --count
        lv_count := lv_count + 1;
      end;
    end loop; --i_stockroomlocation
    if lv_count > 0 then
      begin
        commit;
        pack_import.write_log('import_stockroomlocations ' || to_char(lv_count) ||
                              ' stockroomlocations imported');
      end;
    end if; --lv_count
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('Error import_stockroomlocations: ' || substr(sqlerrm, 1, 512), 3);
      end;
  end import_stockroomlocations;
begin
  begin
    --get conver reason code
    lvnerrormsg := 'get gv_reasonconver_id';
    select reasoncode_id into gv_reasonconver_id from reasoncode where code = 'CONVER';
  exception
    when no_data_found then
      begin
        pack_import.cfbcreate_reasoncode(gv_reasonconver_id, 'CONVER', 'N', 'Y', 'Y', 'Y', 'N', 0,
                                         'N', 'N', 0, 'N', 0, 'Y', 'N');
        pack_import.cfbcreate_reasoncode_desc(gv_reasonconver_id, '-');
        commit;
      end;
  end;
end pack_import_stock;
/
create or replace package pack_import_supplier is
  -- Author  : PVD
  -- Created : 23-Apr-2004 10:55:43
  -- Version : 1.0
  -- Purpose :
  -- Updated : July-2018 for supplierdelday
  --            ABS-73871 I_SUPPLIER add field STATE to conversion
  --13-Mar-2023 ABS-149315 I-tables: extend with ADRESSLINE 3 and 40 characters
  procedure cfbimport_supplier;
  procedure cfbimport_supplierproducts;
end pack_import_supplier;
/
create or replace package body pack_import_supplier is
  lvnerrormsg varchar2(256);
  procedure cfbimport_supplier is
    lvncountrows  number := 0;
    lv_addressid  address.address_id%type;
    lv_supplierid supplier.supplier_id%type;
    procedure create_supplierdelday is
      lv_supplierdeldayid supplierdelday.supplierdelday_id%type;
    begin
      --create_supplierdelday
      insert into supplierdelday
        (supplierdelday_id, supplier_id, deliverydays, systemuser_id, timestamp)
      values
        (seq_supplierdelday.nextval, lv_supplierid, 1, pack_import.lvnsystemuserid, sysdate)
      returning supplierdelday_id into lv_supplierdeldayid;
      --update supplier defaultsupplierdelday_id
      update supplier s
      set    s.defaultsupplierdelday_id = lv_supplierdeldayid
      where  s.supplier_id = lv_supplierid
      and    s.defaultsupplierdelday_id is null;
    end create_supplierdelday;
  begin
    -- supplier from i_supplier
    for x in (select i.*, ct.country_id, cu.currency_id, l.language_id
              from   i_supplier i
              join   country ct
              on     ct.code = i.country
              join   currency cu
              on     cu.code = i.currencycode
              left   outer join languages l
              on     l.code = i.languagecode
              where  not exists (select s.suppliernumber
                      from   supplier s
                      where  s.suppliernumber = i.suppliernumber)
              order  by i.suppliernumber) loop
      begin
        -- insert address then supplier.
        insert into address
          (address_id, street, zipcode, city, state, systemuser_id, county, timestamp, street2, street3)
        values
          (seq_address.nextval, x.street, nvl(x.zipcode, '-'), nvl(x.city, '-'), x.state,
           pack_import.lvnsystemuserid, null, sysdate, x.street2, x.street3)
        returning address_id into lv_addressid;
        insert into supplier
          (supplier_id, suppliernumber, name, fax, phone, email, website, address_id,
           creditornumber, orderformremark, systemuser_id, timestamp, currency_id,
           averageshipmentcosts, sendpurchaseorder, printpriceonpo, discountpercdays,
           discountwithindays, discountpercoverall, paymentterms, deliveryterms, country_id,
           filelayout, formlayout_id, finexport, suppliertype, supplyingstockroom_id,
           defaultdeliverydays, dateactive, dateinactive, language_id)
        values
          (seq_supplier.nextval, x.suppliernumber, x.name, x.fax, x.phone, x.email, x.website,
           lv_addressid, null, x.orderformremark, pack_import.lvnsystemuserid, sysdate,
           x.currency_id, nvl(x.averageshipmentcosts, 0), x.sendpurchaseorder,
           nvl(x.printpriceonpo, 'Y'), 0, 0, 0, x.paymentterms, x.deliveryterms, x.country_id, 0,
           null, 'N', x.suppliertype, null, 1, x.dateactive, x.dateinactive, x.language_id)
        returning supplier_id into lv_supplierid;
        --create_supplierdelday
        create_supplierdelday;
        --count rows
        lvncountrows := lvncountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          lvnerrormsg := 'cfbimport_supplier from i_supplier: Fail to import supplier number ' ||
                         to_char(x.suppliernumber);
          pack_import.write_log(lvnerrormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    commit;
    -- supplier from i_supplierproduct
    for x in (select p.suppliernumber
              from   i_supplierproduct p
              where  not exists (select s.suppliernumber
                      from   supplier s
                      where  s.suppliernumber = p.suppliernumber)
              and    not exists
               (select 1 from i_supplier i where i.suppliernumber = p.suppliernumber)
              group  by p.suppliernumber) loop
      begin
        -- insert address then supplier.
        insert into address
          (address_id, street, zipcode, city, state, systemuser_id, county, timestamp, street2)
        values
          (seq_address.nextval, null, '-', '-', null, pack_import.lvnsystemuserid, null, sysdate,
           null)
        returning address_id into lv_addressid;
        insert into supplier
          (supplier_id, suppliernumber, name, address_id, currency_id, systemuser_id, timestamp,
           averageshipmentcosts, sendpurchaseorder, country_id, dateactive)
        values
          (seq_supplier.nextval, x.suppliernumber, to_char(x.suppliernumber), lv_addressid,
           pack_import.lvncurrencydefaultid, pack_import.lvnsystemuserid, sysdate, 0, 0,
           pack_import.lvncountrydefaultid, trunc(sysdate) - 1)
        returning supplier_id into lv_supplierid;
        --create_supplierdelday
        create_supplierdelday;
        --count rows
        lvncountrows := lvncountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          lvnerrormsg := 'cfbimport_supplier from i_supplierproduct: Fail to import supplier number ' ||
                         to_char(x.suppliernumber);
          pack_import.write_log(lvnerrormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    commit;
    if lvncountrows > 0 then
      pack_import.write_log(lvncountrows || ' supplier rows imported.');
    end if;
  end cfbimport_supplier;
  procedure cfbimport_supplierproducts is
    lvnproduct_id       product.product_id%type;
    lvnsize_id          sizedefinition.sizedefinition_id%type;
    lvsupplierproductid supplierproduct.supplierproduct_id%type;
    lvnsupplier_id      supplier.supplier_id%type;
    lvncounter          number := 0;
  begin
    --Fix carriage return character
    update i_supplierproduct sp
    set    sp.remark = replace(sp.remark, '|', chr(10))
    where  sp.remark <> replace(sp.remark, '|', chr(10));
    commit;
    -- first import missing suppliers.
    cfbimport_supplier;
    for x in (select *
              from   i_supplierproduct i
              where   not exists (select z.productsizepersupproduct_id
                      from   productsizepersupproduct z, supplierproduct p,
                             supplier s, product t, sizedefinition y
                      where  z.supplierproduct_id = p.supplierproduct_id
                      and    p.supplier_id = s.supplier_id
                      and    s.suppliernumber = i.suppliernumber
                      and    p.supplierproductcode = i.supplierproductcode
                      and    p.suppliersizecode = i.suppliersizecode
                      and    z.product_id = t.product_id
                      and    z.sizedefinition_id = y.sizedefinition_id
                      and    t.code = i.laundryproductcode
                      and    y.code = i.laundrysizecode)) loop
      begin
        -- determine the supplier
        select s.supplier_id
        into   lvnsupplier_id
        from   supplier s
        where  s.suppliernumber = x.suppliernumber;
        begin
          -- determine product and size
          if x.laundryproductcode is not null then
            select p.product_id
            into   lvnproduct_id
            from   product p
            where  p.code = trim(x.laundryproductcode);
            if x.laundrysizecode is not null then
              begin
                select s.sizedefinition_id
                into   lvnsize_id
                from   sizedefinition s
                where  s.code = trim(x.laundrysizecode);
              end;
            else
              begin
                lvnsize_id := null;
              end;
            end if;
          else
            begin
              lvnproduct_id := null;
              lvnsize_id    := null;
            end;
          end if;
        exception
          when no_data_found then
            begin
              lvnproduct_id := null;
              lvnsize_id    := null;
            end;
        end;
        begin
          select min(s.supplierproduct_id)
          into   lvsupplierproductid
          from   supplierproduct s
          where  s.supplier_id = lvnsupplier_id
          and    s.supplierproductcode = x.supplierproductcode
          and    s.suppliersizecode = x.suppliersizecode;
          if lvsupplierproductid is null then
            -- create supplier product
            insert into supplierproduct
              (supplierproduct_id, supplier_id, supplierproductcode, supplierproductdescription,
               suppliersizecode, deliverydays, minorderqty, boxquantity, uniqueitem, active, remark,
               systemuser_id, timestamp)
            values
              (seq_supplierproduct.nextval, lvnsupplier_id, x.supplierproductcode,
               x.supplierproductdescription, x.suppliersizecode, x.deliverydays, x.minorderqty,
               x.boxquantity, x.uniqueitem, x.active, x.remark, pack_import.lvnsystemuserid, sysdate)
            returning supplierproduct_id into lvsupplierproductid;
            lvncounter := lvncounter + 1;
          end if;
          if lvnproduct_id is not null and lvnsize_id is not null then
            begin
              -- create productsizepersupproduct
              insert into productsizepersupproduct
                (productsizepersupproduct_id, supplierproduct_id, product_id, sizedefinition_id,
                 systemuser_id, timestamp)
              values
                (seq_productsizepersupproduct.nextval, lvsupplierproductid, lvnproduct_id,
                 lvnsize_id, pack_import.lvnsystemuserid, sysdate);
            exception
              when dup_val_on_index then
                null; -- no problem.
            end;
          end if;
          begin
            -- create supplier product price
            insert into supplierproductprice
              (supplierproductprice_id, supplierproduct_id, startdate, purchaseprice, systemuser_id,
               timestamp)
            values
              (seq_supplierproductprice.nextval, lvsupplierproductid,
               x.supplierproductprice_startdate, x.supplierproductprice, pack_import.lvnsystemuserid,
               sysdate);
          exception
            when dup_val_on_index then
              null; -- no problem.
          end;
        exception
          when dup_val_on_index then
            null; -- no problem.
        end;
      end;
    end loop;
    begin
      -- add missing product size
      for x in (select p.product_id, p.sizedefinition_id
                from   productsizepersupproduct p
                where  not exists (select s.product_id, s.sizedefinition_id
                        from   productsize s
                        where  s.product_id = p.product_id
                        and    s.sizedefinition_id = p.sizedefinition_id)
                group  by p.product_id, p.sizedefinition_id) loop
        pack_import.cfbcreate_productsize(x.product_id, x.sizedefinition_id, 'N', 1, 0, null);
      end loop;
    exception
      when others then
        lvnerrormsg := 'cfbimport_supplierproducts: Failed to add missing productsizes.';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
    end;
    commit;
    if lvncounter > 0 then
      pack_import.write_log(lvncounter || ' supplierproduct rows imported.');
    end if;
  exception
    when others then
      rollback;
      lvnerrormsg := 'cfbimport_supplierproducts: Failed to import.';
      pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
  end cfbimport_supplierproducts;
end pack_import_supplier;
/
create or replace package pack_import_uniqueitem is
  -- Author  : PVD
  -- Created : 15-mei-2003 12:03:34
  -- Version : 1.0
  -- Purpose : Import unique articles from I_UNIQUEITEM table
  -- Added   : I_UNIQUEITEMIMAGE
  procedure cfbaddmiscustactivities;
  procedure import_uniqueitemflag;
  procedure import_activestocklocation;
  procedure copy_uniquepool;
  procedure convertuniqueitem(fpnnumberofuniqueitems out integer);
  procedure convertuniqueorpack;
  procedure convertuniqueorsterile;
  procedure convertuniqueloss;
  procedure convert_uniqueitememblem;
  procedure convert_uniqueitemimage;
end pack_import_uniqueitem;
/
create or replace package body pack_import_uniqueitem is
  -- Private variable declarations
  lvnerrormsg        varchar2(256);
  fpnbusinessunit_id number := 0;
  fpnsupplier_id     number := 0;
  fpncurrency_id     number := 0;
  fpnragreason_id    number := 0;
  procedure cfbaddmiscustactivities is
    lvncounter number := 0;
  begin
    insert into businessunitactivities
      (businessunit_id, activity_id, systemuser_id, timestamp, invoicedbybusinessunit_id)
      select c.defaultbusinessunit_id, g.activity_id, pack_import.lvnsystemuserid, sysdate,
             max(c.defaultinvoicebusinessunit_id)
      from   productlistpercustomer l, customer c, product p, productgroup g
      where  l.customer_id = c.customer_id
      and    l.product_id = p.product_id
      and    p.productgroup_id = g.productgroup_id
      and    not exists (select 1
              from   businessunitactivities x
              where  x.businessunit_id = c.defaultbusinessunit_id
              and    x.activity_id = g.activity_id)
      and    exists (select i.customernumber
              from   i_uniqueitem i
              where  i.customernumber = c.customernumber
              and    i.productcode = p.code)
      group  by c.defaultbusinessunit_id, g.activity_id;
    lvncounter := sql%rowcount;
    if lvncounter > 0 then
      begin
        commit;
        pack_import.write_log(to_char(lvncounter) ||
                              ' missing businessunitactivities added (based on plpc) during unique item conversion');
      end;
    end if;
    insert into customeractivities
      (customer_id, processbusinessunit_id, activity_id, invoicebusinessunit_id, systemuser_id,
       timestamp, cutoffdate, finalinvoicecreated, invoicefrequency_id)
      select c.customer_id, max(c.defaultbusinessunit_id), g.activity_id,
             max(c.defaultinvoicebusinessunit_id), pack_import.lvnsystemuserid, sysdate, null, 'N',
             max(c.invoicefrequency_id)
      from   productlistpercustomer l, customer c, product p, productgroup g
      where  l.customer_id = c.customer_id
      and    l.product_id = p.product_id
      and    p.productgroup_id = g.productgroup_id
      and    not exists (select x.customer_id, x.activity_id
              from   customeractivities x
              where  x.customer_id = c.customer_id
              and    x.activity_id = g.activity_id)
      and    exists (select i.customernumber
              from   i_uniqueitem i
              where  i.customernumber = c.customernumber
              and    i.productcode = p.code)
      group  by c.customer_id, g.activity_id;
    lvncounter := sql%rowcount;
    commit;
    if lvncounter > 0 then
      pack_import.write_log(to_char(lvncounter) ||
                            ' missing customeractivities added (based on plpc) during unique item conversion');
    end if;
  exception
    when others then
      pack_import.write_log('pack_import_uniqueitem.cfbaddmiscustactivities error: ' ||
                            substr(sqlerrm, 1, 512), 3);
  end cfbaddmiscustactivities;
  procedure addmodification(fpnuniqueitem_id  uniqueitem.uniqueitem_id%type,
                            fpnsequencenumber uniqueitemmodification.sequencenumber%type,
                            fpscode           modification.code%type,
                            fpsdescription    modification_desc.description%type) is
    fpnmodification_id modification.modification_id%type;
  begin
    begin
      -- create or retrieve modification
      select modification_id into fpnmodification_id from modification where code = fpscode;
    exception
      when no_data_found then
        -- add modification
        begin
          pack_import.cfbcreate_modification(fpnmodification_id,
                                             --fpnmodification_id,
                                             fpscode,
                                             --fpscode,
                                             'N',
                                             --fpsstockwithstandardsize,
                                             fpscode,
                                             --fpslegacymodificationcode,
                                             'N'); --fpsuseinwebapplication
          pack_import.cfbcreate_modification_desc(fpnmodification_id,
                                                  --fpnmodification_id,
                                                  nvl(fpsdescription, fpscode)
                                                  --fpsdescription,
                                                  );
        exception
          when others then
            --error
            lvnerrormsg := 'Error modification: ' || fpscode;
            pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
        end;
      when others then
        --error
        lvnerrormsg := 'Error modification: ' || fpscode;
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
    end;
    begin
      insert into uniqueitemmodification
        (uniqueitem_id, modification_id, sequencenumber, systemuser_id, timestamp)
      values
        (fpnuniqueitem_id, fpnmodification_id, fpnsequencenumber, pack_import.lvnsystemuserid,
         sysdate);
    exception
      when dup_val_on_index then
        null; --Modification existed so no problem.
    end;
    -- Rests of the error handling for adding modification is in calling procedure.
  end addmodification; --Addmodification
  procedure updatewearerinventory is
    lvncounter number := 0;
  begin
    -- Update the wearer inventory.
    update wearerinventory wi
    set    wi.circinventory =
            ((select count(nu.nonuniqueitem_id)
              from   nonuniqueitem nu
              where  nu.wearerinventory_id = wi.wearerinventory_id
              and    nu.freeitem = 'N') +
            (select count(un.uniqueitem_id)
              from   uniqueitemnonpool un
              where  un.wearerinventory_id = wi.wearerinventory_id
              and    un.freeextragarment = 'N')),
           wi.maxinventory = case
                               when (wi.remark = 'CONV' and
                                    wi.maxinventory <
                                    ((select count(nu.nonuniqueitem_id)
                                       from   nonuniqueitem nu
                                       where  nu.wearerinventory_id = wi.wearerinventory_id
                                       and    nu.freeitem = 'N') +
                                    (select count(un.uniqueitem_id)
                                       from   uniqueitemnonpool un
                                       where  un.wearerinventory_id = wi.wearerinventory_id
                                       and    un.freeextragarment = 'N'))) then
                                ((select count(nu.nonuniqueitem_id)
                                  from   nonuniqueitem nu
                                  where  nu.wearerinventory_id = wi.wearerinventory_id
                                  and    nu.freeitem = 'N') +
                                (select count(un.uniqueitem_id)
                                  from   uniqueitemnonpool un
                                  where  un.wearerinventory_id = wi.wearerinventory_id
                                  and    un.freeextragarment = 'N'))
                               else
                                wi.maxinventory
                             end
    where  wi.circinventory < > ((select count(nu.nonuniqueitem_id)
                                  from   nonuniqueitem nu
                                  where  nu.wearerinventory_id = wi.wearerinventory_id
                                  and    nu.freeitem = 'N') +
           (select count(un.uniqueitem_id)
                                  from   uniqueitemnonpool un
                                  where  un.wearerinventory_id = wi.wearerinventory_id
                                  and    un.freeextragarment = 'N'))
    and    exists (select 1
            from   i_wearer i
            join   customer c
            on     c.customernumber = i.customernumber
            join   wearer w
            on     (w.customer_id = c.customer_id and w.wearernumber = i.wearernumber)
            join   weareremployment we
            on     we.wearer_id = w.wearer_id
            where  we.weareremployment_id = wi.weareremployment_id);
    lvncounter := sql%rowcount;
    commit;
    pack_import.write_log(to_char(lvncounter) || ' records for wearerinventory updated.');
  exception
    when others then
      begin
        lvnerrormsg := 'Error CorrectWearerInventory ';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end updatewearerinventory;
  procedure import_flag(pflagcode          flag.code%type,
                        pflagdescription   flag_desc.description%type,
                        pflagstartdate     uniqueitemflag.startdate%type,
                        pflagfreetext      uniqueitemflag.freetextitem%type,
                        puniqueitemid      uniqueitem.uniqueitem_id%type,
                        ptreatmenttypecode treatmenttype.code%type default null) is
    lflag_id        flag.flag_id%type;
    ltreamenttypeid treatmenttype.treatmenttype_id%type;
  begin
    begin
      -- determine the right flag
      select flag_id
      into   lflag_id
      from   flag
      where  code = pflagcode
      and    flagtype = 1;
    exception
      when no_data_found then
        begin
          pack_import.cfbcreate_flag(lflag_id,
                                     --fpnflag_id,
                                     1,
                                     --fpnflagtype,
                                     pflagcode,
                                     --fpscode,
                                     1,
                                     --fpnpriority,
                                     'ff 0 0',
                                     --fpscolor,
                                     'Y',
                                     --fpsincludeincompletnesscheck,
                                     null,
                                     --fpnsound_id,
                                     'Y',
                                     --fpsshowalways
                                     'N',
                                     --fpsexporttogarmentdispenser
                                     null,
                                     --fpnexportgdcode
                                     'N'); --fpnuseinwebapplication);
          pack_import.cfbcreate_flag_desc(lflag_id, pflagdescription);
        end;
    end;
    if ptreatmenttypecode is null then
      ltreamenttypeid := null;
    else
      pack_import.cfbcreate_treatmenttype(ltreamenttypeid, ptreatmenttypecode);
    end if;
    insert into uniqueitemflag
      (uniqueitem_id, flag_id, startdate, freetextitem, systemuser_id, timestamp, treatmenttype_id)
    values
      (puniqueitemid, lflag_id, nvl(pflagstartdate, trunc(sysdate)), pflagfreetext,
       pack_import.lvnsystemuserid, sysdate, ltreamenttypeid);
  exception
    when dup_val_on_index then
      null;
    when others then
      begin
        lvnerrormsg := 'Error adding flag: ' || pflagcode;
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end import_flag;
  procedure import_uniqueitemflag is
    luniqueitemid uniqueitem.uniqueitem_id%type;
  begin
    for x in (select * from i_uniqueitemflags) loop
      begin
        lvnerrormsg := ' Error import_uniqueitemflag barcode ' || x.primaryid ||
                       ' for businessunit ' || x.businessunit || ' seq.no ' ||
                       to_char(x.idcodesequencenumber) || ' not found for adding flag ' ||
                       x.flagcode;
        select u.uniqueitem_id
        into   luniqueitemid
        from   uniqueitem u
        where  u.primaryid = x.primaryid
        and    u.idcodesequencenumber = x.idcodesequencenumber
        and    u.businessunit_id =
               (select z.businessunit_id from businessunit z where z.code = x.businessunit);
        import_flag(x.flagcode, x.flagdescription, x.flagstartdate, x.flagfreetext, luniqueitemid,
                    x.treatmentcheckschemecode);
      exception
        when no_data_found then
          begin
            pack_import.write_log(lvnerrormsg, 3);
          end;
      end;
    end loop;
  exception
    --Error handling
    when others then
      begin
        lvnerrormsg := 'Error import_uniqueitemflag: ';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end import_uniqueitemflag;
  procedure import_activestocklocation is
    businessunitid businessunit.businessunit_id%type;
    countrows      number := 0;
  begin
    for x in (select * from i_activestocklocation) loop
      begin
        select u.businessunit_id
        into   businessunitid
        from   businessunit u
        where  u.code = x.businessunit;
        --insert data
        insert into activestocklocation
          (activestocklocation_id, businessunit_id, section, location, uniqueid, priority, active,
           maximumlength, maximumwidth, multiplestorageallowed, multiplecustomersallowed,
           multipleproductsizeallowed, systemuser_id, timestamp)
        values
          (seq_activestocklocation.nextval, businessunitid, x.section, x.location, x.uniqueid,
           x.priority, x.active, x.maximumlength, x.maximumwidth, x.multiplestorageallowed,
           x.multiplecustomerallowed, x.multipleproductsizeallowed, pack_import.lvnsystemuserid,
           sysdate);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when no_data_found then
          pack_import.write_log(' import_activestocklocation, error missing businessunit: ' ||
                                x.businessunit || '!', -3);
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(to_char(countrows) ||
                            ' records for import_activestocklocation inserted.');
    end if;
  exception
    when others then
      begin
        rollback;
        lvnerrormsg := 'import_activestocklocation: Fail to import.';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end import_activestocklocation;
  procedure copy_uniquepool is
    lvncounter integer := 0;
  begin
    for x in (select *
              from   i_uniquepool i
              where  not exists (select u.primaryid
                      from   i_uniqueitem u
                      where  u.primaryid = i.primaryid
                      and    u.idcodesequencenumber = i.idcodesequencenumber
                      and    u.businessunit = i.businessunit)) loop
      begin
        insert into i_uniqueitem
          (businessunit, primaryid, idcodesequencenumber, secondaryid, status, stay, customernumber,
           productcode, sizecode, finishingmethodcode, washestotal, repairtotal, customerowned,
           relatedcustomernumber, deliverfromstock, lastinscandate, lastoutscandate, lastscandate,
           statuschangedate, staychangedate, purchasedate, numberofissues, firstissuedate,
           lastissuedate, enddatefullrent, daysincircprevissue, daysinstockprevissue, suppliernumber,
           purchaseprice, currencycode, reasoncode, remark, poolitem, leaseweeks,
           residualvalueamount, replacementprice, section, location, typeofmerchandise,
           qualitygradecode, consumptionpointnumber)
        values
          (x.businessunit, x.primaryid, x.idcodesequencenumber, x.secondaryid, x.status, x.stay,
           x.customernumber, x.productcode, x.sizecode, x.finishingmethodcode, x.washestotal,
           x.repairtotal, x.customerowned, x.relatedcustomernumber, 'Y', x.lastinscandate,
           x.lastoutscandate, x.lastscandate, x.statuschangedate, x.staychangedate, x.purchasedate,
           x.numberofissues, x.firstissuedate, x.lastissuedate, x.enddatefullrent, 0, 0,
           x.suppliernumber, x.purchaseprice, x.currencycode, x.reasoncode, x.remark, x.poolitem,
           x.leaseweeks, x.residualvalueamount, x.replacementprice, x.section, x.location,
           x.typeofmerchandise, x.qualitygradecode, x.consumptionpointnumber);
        lvncounter := lvncounter + 1;
      exception
        when others then
          pack_import.write_log('Error insert copy_uniquepool ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    commit;
    pack_import.write_log(to_char(lvncounter) ||
                          ' records for copied from i_uniquepool to i_unqiueitem.');
  exception
    when others then
      begin
        rollback;
        lvnerrormsg := 'Error copy_uniquepool ';
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end copy_uniquepool;
  procedure convertuniqueorpackcontents is
    lv_sizedefinitionid       sizedefinition.sizedefinition_id%type;
    lv_finishingmethodid      finishingmethod.finishingmethod_id%type;
    lv_uniqueorpackcontentsid uniqueorpackcontents.uniqueorpackcontents_id%type;
    lv_contentuniqueitemid    uniqueitem.uniqueitem_id%type;
    lv_counter                number;
  begin
    for orp in (select iorp.*, u.uniqueitem_id, p.product_id,
                       (select bu.businessunit_id
                         from   businessunit bu
                         where  bu.code = iorp.contentbusinessunit) contentbu_id
                from   i_uniqueorpackcontents iorp
                join   businessunit bu
                on     bu.code = iorp.businessunit
                join   uniqueitem u
                on     (u.poolitem in (1, 3) and u.businessunit_id = bu.businessunit_id and
                       u.primaryid = iorp.primaryid and
                       u.idcodesequencenumber = iorp.idcodesequencenumber)
                join   product p
                on     p.code = iorp.productcode) loop
      begin
        --get lv_sizedefinitionid
        lvnerrormsg := 'size ' || orp.sizedefinitioncode;
        select s.sizedefinition_id
        into   lv_sizedefinitionid
        from   sizedefinition s
        where  s.code = orp.sizedefinitioncode;
        --get lv_finishingmethodid
        lvnerrormsg := 'finishingmethod ' || orp.finishingmethod;
        select f.finishingmethod_id
        into   lv_finishingmethodid
        from   finishingmethod f
        where  f.code = orp.finishingmethod;
        --insert into uniqueorpackcontents
        lvnerrormsg := 'insert into uniqueorpackcontents ';
        insert into uniqueorpackcontents
          (uniqueorpackcontents_id, uniqueitem_id, packsequence, product_id, sizedefinition_id,
           finishingmethod_id, remark, lotnumber, qtynonunique, systemuser_id, timestamp, rownumber,
           positionnumber)
        values
          (seq_uniqueorpackcontents.nextval, orp.uniqueitem_id, orp.packsequence, orp.product_id,
           lv_sizedefinitionid, lv_finishingmethodid, orp.remark, orp.lotnumber, orp.qtynonunique,
           pack_import.lvnsystemuserid, sysdate, orp.rownumber, orp.positionnumber)
        returning uniqueorpackcontents_id into lv_uniqueorpackcontentsid;
        if orp.contentbusinessunit is not null and orp.contentprimaryid is not null and
           orp.contentidcodeseqnumber is not null then
          begin
            --select content barcode
            lvnerrormsg := 'select content barcode ' || orp.contentprimaryid;
            select u.uniqueitem_id
            into   lv_contentuniqueitemid
            from   uniqueitem u
            where  u.poolitem in (1, 3)
            and    u.businessunit_id = orp.contentbu_id
            and    u.primaryid = orp.contentprimaryid
            and    u.idcodesequencenumber = orp.contentidcodeseqnumber;
            --insert into uniqueorpackuniquecontents
            lvnerrormsg := 'insert into uniqueorpackuniquecontents ';
            insert into uniqueorpackuniquecontents
              (uniqueorpackcontents_id, uniqueitem_id, systemuser_id, timestamp)
            values
              (lv_uniqueorpackcontentsid, lv_contentuniqueitemid, pack_import.lvnsystemuserid,
               sysdate);
          end;
        end if;
        lv_counter := lv_counter + 1;
        if remainder(lv_counter, 100) = 0 then
          --commit every 100 records
          commit;
        end if;
      exception
        when others then
          begin
            pack_import.write_log('convertuniqueorpackcontents ' || lvnerrormsg ||
                                  substr(sqlerrm, 1, 512), 3);
          end;
      end;
    end loop; --orp
    commit;
    if lv_counter > 0 then
      begin
        pack_import.write_log('converted ' || to_char(lv_counter) ||
                              ' uniqueorpackcontents records');
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('.convertuniqueorpackcontents ' || lvnerrormsg ||
                              substr(sqlerrm, 1, 512), 3);
      end;
  end convertuniqueorpackcontents;
  procedure convertuniqueitem(fpnnumberofuniqueitems out integer) is
    error_missing_data         exception;
    error_customerrelatedstock exception;
    fpnuniqueitem_id           number := 0;
    fpndistributionpoint_id    number := 0;
    fpnproduct_id              number := 0;
    fpnstatus_id               number := 0;
    fpsstatus_code             varchar2(2) := '';
    fpnstay_id                 number := 0;
    fpnitableuniqueitems       integer := 0;
    fpnsizedefinition_id       number := 0;
    fpnfinishingmethod_id      number := 0;
    fpnqualitygrade_id         number := null;
    fpnreasoncode_id           number := 0;
    fpnissuedbyworkorder_id    number := null;
    fpnweareremployment_id     number := 0;
    fpsprimaryid               uniqueitem.primaryid%type;
    fpnplpc_id                 productlistpercustomer.productlistpercustomer_id%type;
    fpncustomer_id             number := 0;
    fpnrelatedcustomer_id      number := 0;
    fpncustomernumber          number := 0;
    fpnwearer_id               number := 0;
    fpnwearernumber            number := 0;
    fpnwearerinventory_id      number := 0;
    fpnactivestocklocation_id  number := 0;
    fpbimport_allowed          boolean := true;
    fpnstockroom_id            stockroom.stockroom_id%type;
    fpnstockroomlocation_id    stockroomlocation.stockroomlocation_id%type;
    fpncountplpc               integer := 0;
    fpnresidualvalue           uniqueitem.residualvalue%type;
    fpnwearerdateactive        wearer.dateactive%type;
    fpnwearerdateinactive      wearer.dateinactive%type;
    fpnmissingcurrency         number := 0;
    fpnmissingstockroom        number := 0;
    fpncountrows               number := 0;
    fpnlastonstockdate         date := trunc(sysdate);
    fpnlastdeliverynotenumber  number := null;
    fpdummyforpool             wearer.dummyforpool%type;
    type xtab is table of i_uniqueitem%rowtype;
    x                        xtab;
    i                        number;
    last_id                  varchar2(24) := '0';
    last_bu                  varchar2(6) := '0';
    data_exists              boolean := true;
    lv_orpackcontentsallowed product.orpackcontentsallowed%type;
    lv_raggeditems           number := 0;
    cursor c1(pfrom varchar2, pbusinessunit varchar2) is
      select *
      from   i_uniqueitem i
      where  lpad(i.businessunit, 6, '0') || lpad(i.primaryid, 24, '0') >
             lpad(pbusinessunit, 6, '0') || lpad(pfrom, 24, '0')
      and    not exists (select u.primaryid
              from   uniqueitem u, businessunit b
              where  u.primaryid = i.primaryid
              and    u.businessunit_id = b.businessunit_id
              and    i.idcodesequencenumber = u.idcodesequencenumber
              and    b.code = i.businessunit)
      order  by lpad(i.businessunit, 6, '0') || lpad(i.primaryid, 24, '0');
  begin
    -- copy uniquepool
    copy_uniquepool;
    -- check customer related stock
    for y in (select z.stockroomcode, z.locationcode, z.rowcode, z.areacode, z.productcode,
                     count(distinct z.customernumber)
              from   (select u.stockroomcode, u.locationcode, u.rowcode, u.stockroomareacode areacode,
                              u.productcode, nvl(u.relatedcustomernumber, 0) customernumber
                       from   i_uniqueitem u
                       where  u.stockroomcode is not null
                       and    u.locationcode is not null
                       group  by u.stockroomcode, u.locationcode, u.rowcode, u.stockroomareacode,
                                 u.productcode, nvl(u.relatedcustomernumber, 0)
                       union
                       select q.stockroomcode, q.locationcode, q.rowcode, q.areacode, q.productcode,
                              nvl(q.customernumber, 0) customernumber
                       from   i_stockroomquantity q
                       where  q.stockroomcode is not null
                       and    q.locationcode is not null
                       group  by q.stockroomcode, q.locationcode, q.rowcode, q.areacode, q.productcode,
                                 nvl(q.customernumber, 0)) z
              group  by z.stockroomcode, z.locationcode, z.rowcode, z.areacode, z.productcode
              having count(distinct z.customernumber) > 1) loop
      begin
        lvnerrormsg := 'Error: There are stockrooms locations that have both customerrelated and not customer related stock!';
        raise error_customerrelatedstock;
      end;
    end loop; --y  check customer related stock
    -- insert product finishing method
    for x in (select p.product_id, f.finishingmethod_id
              from   i_uniqueitem l, product p, finishingmethod f
              where  p.code = l.productcode
              and    f.code = l.finishingmethodcode
              and    not exists (select pf.product_id, pf.finishingmethod_id
                      from   productfinishingmethod pf
                      where  pf.product_id = p.product_id
                      and    pf.finishingmethod_id = f.finishingmethod_id)
              group  by p.product_id, f.finishingmethod_id) loop
      begin
        pack_import.cfbcreate_prodfinishingmethod(x.product_id, x.finishingmethod_id);
        fpncountrows := fpncountrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          lvnerrormsg := 'CFbImportPLCust: Fail to import product-finishing method ';
          pack_import.write_log(lvnerrormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    commit;
    if fpncountrows > 0 then
      pack_import.write_log(fpncountrows || ' product-finishing method rows imported.');
    end if;
    -- sizes per size type, product size
    fpncountrows := 0;
    for vcursor in (select b.product_id, max(b.sizetype_id) sizetype_id,
                           max(b.packingamount) packingamount,
                           max(b.theoreticalweight) theoreticalweight, c.sizedefinition_id
                    from   i_uniqueitem a, product b, sizedefinition c
                    where  a.productcode = b.code
                    and    a.sizecode = c.code
                    and    not exists
                     (select t.code from databasesettings t where t.code = 'SMG')
                    and    not exists
                     (select ps.product_id, ps.sizedefinition_id
                            from   productsize ps
                            where  ps.product_id = b.product_id
                            and    ps.sizedefinition_id = c.sizedefinition_id)
                    group  by b.product_id, c.sizedefinition_id) loop
      begin
        begin
          -- sizespersizetype
          pack_import.cfbcreate_sizespersizetype(vcursor.sizedefinition_id, vcursor.sizetype_id);
          -- product size
          pack_import.cfbcreate_productsize(vcursor.product_id, vcursor.sizedefinition_id, 'N',
                                            vcursor.packingamount, vcursor.theoreticalweight, null);
          fpncountrows := fpncountrows + 1;
        exception
          when dup_val_on_index then
            null;
          when others then
            lvnerrormsg := 'CFbImportPLCust: Fail to import productsize!';
            pack_import.write_log(lvnerrormsg || ' ' || substr(sqlerrm, 1, 512), -3);
        end;
      end;
    end loop;
    commit;
    if fpncountrows > 0 then
      begin
        pack_import.write_log(fpncountrows || ' product size rows imported.');
      end;
    end if;
    -- set counters
    fpnnumberofuniqueitems := 0;
    select count(*) into fpnitableuniqueitems from uniqueitem;
    -- check currency
    select count(distinct(z.currencycode))
    into   fpnmissingcurrency
    from   i_uniqueitem z
    where  not exists (select c.currency_id from currency c where c.code = z.currencycode);
    -- check stockroom code
    select count(distinct(z.stockroomcode))
    into   fpnmissingstockroom
    from   i_uniqueitem z
    where  not exists (select s.stockroom_id from stockroom s where s.code = z.stockroomcode);
    -- update reason code.
    update reasoncode r
    set    r.garmentreason = 'Y'
    where  r.code = 'R1'
    or     r.code in (select distinct i.reasoncode from i_uniqueitem i);
    commit;
    -- check if conversion can be started yes or no..
    if (fpnmissingcurrency > 0 or fpnmissingstockroom > 0) then
      begin
        raise error_missing_data;
      end;
    end if;
    -- select all unique articles.
    while data_exists loop
      -- Loop needed to flush rollback space.
      -- Started to fill the cursor with the right start id.
      open c1(last_id, last_bu);
      fetch c1 bulk collect
        into x limit 5000;
      for i in 1 .. x.count loop
        begin
          -- start import.
          last_id                   := x(i).primaryid; -- for the loop.
          last_bu                   := x(i).businessunit;
          fpbimport_allowed         := true;
          fpnuniqueitem_id          := 0;
          fpsprimaryid              := x(i).primaryid;
          fpnstockroom_id           := null;
          fpnstockroomlocation_id   := null;
          fpnactivestocklocation_id := null;
          fpnqualitygrade_id        := pack_import.getqualitygradeid(nvl(x(i).qualitygradecode, 'N'));
      fpnlastdeliverynotenumber := x(i).lastdeliverynotenumber;
          begin
            -- Determine the reason code.
            select r.reasoncode_id
            into   fpnreasoncode_id
            from   reasoncode r
            where  r.garmentreason = 'Y'
            and    r.code = nvl(x(i).reasoncode, 'R1');
          exception
            when no_data_found then
              begin
                pack_import.cfbcreate_reasoncode(fpnreasoncode_id,
                                                 --fpnreasoncode_id,
                                                 nvl(x(i).reasoncode, 'R1'),
                                                 --fpscode,
                                                 'N',
                                                 --fpsinternetselectable,
                                                 'Y',
                                                 --fpsallowprepcharges,
                                                 'Y',
                                                 --fpsgarmentreason,
                                                 'Y',
                                                 --fpslinenreason,
                                                 'N',
                                                 --fpsexporttohandheld,
                                                 0,
                                                 --fpncancelinvoice,
                                                 'N',
                                                 --fpsaffectsnextinvoice,
                                                 'N',
                                                 --fpsaffectscurrentinvoice,
                                                 0,
                                                 --fpninvoiceadjustment,
                                                 'N',
                                                 --fpsfirstissue,
                                                 0,
                                                 --fpninventorytrigger,
                                                 'Y',
                                                 --fpschargeresidualvalue
                                                 'N'
                                                 --fpschargerestockingfee
                                                 );
                pack_import.cfbcreate_reasoncode_desc(fpnreasoncode_id,
                                                      --fpnreasoncode_id,
                                                      nvl(x(i).reasoncode, 'R1')
                                                      --fpsdescription,
                                                      );
              end; -- End exception.
          end; -- End reason code.
          begin
            -- Determine currency.
            select currency_id into fpncurrency_id from currency where code = x(i).currencycode;
          exception
            when no_data_found then
              begin
                lvnerrormsg := 'NO_DATA currency: ' || x(i).currencycode;
                pack_import.write_log(lvnerrormsg, -3);
                fpncurrency_id    := null;
                fpbimport_allowed := false;
              end;
          end;
          begin
            -- Determine business unit.
            select businessunit_id
            into   fpnbusinessunit_id
            from   businessunit x
            where  x.code = x(i).businessunit;
          exception
            when no_data_found then
              begin
                lvnerrormsg := 'NO_DATA bunissunit: ' || x(i).businessunit;
                pack_import.write_log(lvnerrormsg, -3);
                fpbimport_allowed  := false;
                fpnbusinessunit_id := null;
              end;
          end;
          begin
            -- Determine the supplier
            select supplier_id
            into   fpnsupplier_id
            from   supplier
            where  suppliernumber = x(i).suppliernumber;
          exception
            when no_data_found then
              begin
                lvnerrormsg := 'NO_DATA supplier number: ' || to_char(x(i).suppliernumber);
                pack_import.write_log(lvnerrormsg, -3);
                fpbimport_allowed := false;
                fpnsupplier_id    := null;
              end;
          end;
          begin
            -- Determine product.
            select p.product_id, p.orpackcontentsallowed
            into   fpnproduct_id, lv_orpackcontentsallowed
            from   product p
            where  p.code = x(i).productcode;
          exception
            when no_data_found then
              begin
                lvnerrormsg := 'NO_DATA productcode: ' || x(i).productcode || ' ID: ' ||
                               fpsprimaryid;
                pack_import.write_log(lvnerrormsg, -3);
                fpbimport_allowed := false;
                fpnproduct_id     := null;
              end;
          end;
          begin
            -- Determine size.
            select sizedefinition_id
            into   fpnsizedefinition_id
            from   sizedefinition
            where  code = x(i).sizecode;
          exception
            when no_data_found then
              begin
                lvnerrormsg := 'NO_DATA sizecode: ' || x(i).sizecode || ' ID: ' || fpsprimaryid;
                pack_import.write_log(lvnerrormsg, -3);
                fpbimport_allowed    := false;
                fpnsizedefinition_id := null;
              end;
          end;
          begin
            --determine status.
            if x(i).poolitem = 3 then
              select status_id, code
              into   fpnstatus_id, fpsstatus_code
              from   status
              where  code = to_char(x(i).status)
              and    statustype = 'OR';
            else
              select status_id, code
              into   fpnstatus_id, fpsstatus_code
              from   status
              where  code = to_char(x(i).status)
              and    statustype = 'UI';
            end if;
          exception
            when no_data_found then
              begin
                lvnerrormsg := 'NO_DATA status: ' || to_char(x(i).status) || ' ID: ' ||
                               fpsprimaryid;
                pack_import.write_log(lvnerrormsg, -3);
                fpbimport_allowed := false;
                fpnstatus_id      := null;
                fpsstatus_code    := null;
              end;
          end;
          begin
            --determine stay.
            if x(i).poolitem = 3 then
              select stay_id
              into   fpnstay_id
              from   stay
              where  staynr = x(i).stay
              and    staytype = 3;
            else
              select stay_id
              into   fpnstay_id
              from   stay
              where  staynr = x(i).stay
              and    staytype = 1;
            end if;
          exception
            when no_data_found then
              begin
                lvnerrormsg := 'NO_DATA stay: ' || to_char(x(i).stay) || ' ID: ' || fpsprimaryid;
                pack_import.write_log(lvnerrormsg, -3);
                fpbimport_allowed := false;
                fpnstay_id        := null;
              end;
          end;
          begin
            -- Select the related customers in ABSSolute.
            if x(i).relatedcustomernumber > 0 then
              begin
                select customer_id
                into   fpnrelatedcustomer_id
                from   customer
                where  customernumber = x(i).relatedcustomernumber;
              exception
                when no_data_found then
                  fpnrelatedcustomer_id := null;
              end;
            else
              fpnrelatedcustomer_id := null;
            end if;
          end;
          if x(i).poolitem <> 0 then
            /*0=stock*/
            -- Check status
            fpnlastonstockdate := null;
            begin
              -- In Circulation or Assigned.
              begin
                --determine finishing method id
                select f.finishingmethod_id
                into   fpnfinishingmethod_id
                from   finishingmethod f
                where  f.code = x(i).finishingmethodcode;
              exception
                when no_data_found then
                  begin
                    lvnerrormsg := x(i).finishingmethodcode || ' ID: ' || fpsprimaryid;
                    lvnerrormsg := ' NO_DATA finishingmethodcode : ' || lvnerrormsg;
                    pack_import.write_log(lvnerrormsg, -3);
                    fpbimport_allowed     := false;
                    fpnfinishingmethod_id := null;
                  end;
              end;
              begin
                -- Select the customers in ABSSolute.
                select customer_id
                into   fpncustomer_id
                from   customer
                where  customernumber = x(i).customernumber;
              exception
                when no_data_found then
                  begin
                    if x(i).poolitem not in (1, 3) then
                      begin
                        lvnerrormsg := 'NO_DATA customer: ' || to_char(x(i).customernumber) ||
                                       ' ID: ' || fpsprimaryid;
                        pack_import.write_log(lvnerrormsg, -3);
                        fpbimport_allowed := false;
                      end;
                    end if;
                    fpncustomer_id := null;
                  end;
              end;
              if (fpncustomer_id is not null and lv_orpackcontentsallowed = 0) then
                -- only if customer id is known check for PLPC!
                -- and only if orpackcontentsallowed = 0, pack contents is allowed with no PLPC
                begin
                  -- check plpc for i_uniqueitem.
                  select min(l.productlistpercustomer_id)
                  into   fpnplpc_id
                  from   productlistpercustomer l
                  where  l.product_id = fpnproduct_id
                  and    l.customer_id = fpncustomer_id
                  and    l.finishingmethod_id = fpnfinishingmethod_id
                  and    (l.sizedefinition_id = fpnsizedefinition_id or
                        l.sizedefinition_id =
                        (select s.sizedefinition_id from sizedefinition s where s.code = '*'));
                  if fpnplpc_id is null then
                    begin
                      if x(i).typeofmerchandise = 2 then
                        pack_import_wearer.insert_missing_plpc(fpncustomer_id, fpnproduct_id,
                                                               fpnfinishingmethod_id, sysdate,
                                                               to_date('31-12-2099', 'dd-mm-yyyy'),
                                                               null, null);
                      else
                        pack_import_wearer.insert_missing_plpc(fpncustomer_id, fpnproduct_id,
                                                               fpnfinishingmethod_id, sysdate,
                                                               to_date('31-12-2099', 'dd-mm-yyyy'),
                                                               null, null, fpnsizedefinition_id);
                      end if;
                      fpncountplpc := fpncountplpc + 1;
                      lvnerrormsg  := '  remark, added missing plpc. ' ||
                                      to_char(x(i).customernumber) || ' ' ||
                                      to_char(x(i).productcode);
                      pack_import.write_log(lvnerrormsg, -3);
                    end;
                  end if;
                exception
                  when others then
                    begin
                      lvnerrormsg := 'Error adding missing plpc for ID: ' || fpsprimaryid;
                      pack_import.write_log(lvnerrormsg, -3);
                      fpbimport_allowed := false;
                    end;
                end;
              end if; --if fpncustomer_id is not null and lv_orpackcontentsallowed = 0
              if x(i).poolitem in (1, 3) then
                begin
                  --pool item
                  if ((x(i).poolitem = 1 and x(i).stay not between 30 and 36) or
                     (x(i).poolitem = 3 and fpncustomer_id is not null)) then
                    begin
                      -- get distribution point for pool, because it is at the customer
                      select min(p.distributionpoint_id)
                      into   fpndistributionpoint_id
                      from   distributionpoint p
                      where  (p.distributionpointnumber = x(i).consumptionpointnumber or x(i).consumptionpointnumber is null)
                      and    p.department_id =
                             (select d.department_id
                               from   department d, i_uniquepool u
                               where  d.customer_id = fpncustomer_id
                               and    nvl(u.departmentnumber, 1) = d.departmentnumber
                               and    u.businessunit = x(i).businessunit
                               and    u.primaryid = fpsprimaryid
                               and    nvl(x(i).idcodesequencenumber, 1) = u.idcodesequencenumber);
                      if fpndistributionpoint_id is null and
                         (x(i).poolitem <> 3 or (x(i).poolitem = 3 and x(i).stay <> 10)) then
                        begin
                          lvnerrormsg := 'NO_DATA distribution for (pool/OR) ID: ' || fpsprimaryid;
                          pack_import.write_log(lvnerrormsg, 2);
                        end;
                      end if;
                    end;
                  else
                    begin
                      fpndistributionpoint_id := null;
                    end;
                  end if;
                  if x(i).location is not null then
                    begin
                      --for pool check if link to active stock is needed
                      select l.activestocklocation_id
                      into   fpnactivestocklocation_id
                      from   activestocklocation l
                      where  l.businessunit_id = fpnbusinessunit_id
                      and    l.section = x(i).section
                      and    l.location = x(i).location;
                    exception
                      when others then
                        begin
                          lvnerrormsg := 'Warning linking activestocklocation for ID: ' ||
                                         fpsprimaryid;
                          pack_import.write_log(lvnerrormsg, 2);
                        end;
                    end;
                  end if;
                end; -- end pool
              else
                begin
                  -- Select wearer.
                  select wearernumber, wearer_id, dateactive, dateinactive, dummyforpool
                  into   fpnwearernumber, fpnwearer_id, fpnwearerdateactive, fpnwearerdateinactive, fpdummyforpool
                  from   wearer
                  where  customer_id = fpncustomer_id
                  and    wearernumber = x(i).wearernumber;
                exception
                  when no_data_found then
                    begin
                      lvnerrormsg := 'NO_DATA wearer: ' || to_char(x(i).wearernumber) || ' ID: ' ||
                                     fpsprimaryid;
                      pack_import.write_log(lvnerrormsg, -3);
                      fpbimport_allowed := false;
                      fpnwearer_id      := null;
                    end;
                end;
                begin
                  -- Select wearer employeement
                  select weareremployment_id
                  into   fpnweareremployment_id
                  from   weareremployment
                  where  wearer_id = fpnwearer_id
                  and    sequencenumber = nvl(x(i).weareremploymentnumber, 1);
                exception
                  when no_data_found then
                    begin
                      lvnerrormsg := 'NO_DATA weareremployeement for wearer: ' ||
                                     to_char(x(i).wearernumber) || ' ID: ' || fpsprimaryid;
                      pack_import.write_log(lvnerrormsg, -3);
                      fpbimport_allowed      := false;
                      fpnweareremployment_id := null;
                    end;
                end;
                fpndistributionpoint_id := null;
                begin
                  -- Select the fpnwearerinventory_id
                  select wearerinventory_id
                  into   fpnwearerinventory_id
                  from   wearerinventory
                  where  product_id = fpnproduct_id
                  and    sizedefinition_id = fpnsizedefinition_id
                  and    finishingmethod_id = fpnfinishingmethod_id
                  and    weareremployment_id = fpnweareremployment_id;
                exception
                  when no_data_found then
                    begin
                      if fpbimport_allowed then
                        --Create wearer inventory in ABSSolute.
                        insert into wearerinventory
                          (wearerinventory_id, weareremployment_id, product_id, sizedefinition_id,
                           finishingmethod_id, emblemtemplate_id, specialgrade_id, maxinventory,
                           freeofchargeqty, circinventory, changesperweek, systemuser_id, timestamp,
                           maxfreeofcharge, dateactive, dateinactive, swingsuitstatus, season_id,
                           returnedqty, qtytobereturnedreplacement, qtytobereturneddecreasemax,
                           temporaryrentstopstartdate, temporaryrentstopenddate, remark,
                           dispensecredit, personalizedgarment)
                        values
                          (seq_wearerinventory.nextval, fpnweareremployment_id, fpnproduct_id,
                           fpnsizedefinition_id, fpnfinishingmethod_id, null, null, 1, 0, 1, 1,
                           pack_import.lvnsystemuserid, sysdate, 0,
                           nvl(fpnwearerdateactive, sysdate),
                           nvl(fpnwearerdateinactive, to_date('31-12-2099', 'DD-MM-YYYY')), 0, null,
                           0, 0, 0, null, null, 'CONV', 0, case when fpdummyforpool = 'Y' then 'N' else 'Y' end)
                        returning wearerinventory_id into fpnwearerinventory_id;
                      end if;
                    exception
                      when dup_val_on_index then
                        begin
                          select wearerinventory_id, finishingmethod_id
                          into   fpnwearerinventory_id, fpnfinishingmethod_id
                          from   wearerinventory
                          where  product_id = fpnproduct_id
                          and    sizedefinition_id = fpnsizedefinition_id
                          and    weareremployment_id = fpnweareremployment_id;
                          pack_import.write_log('Wrong finishingmethod for unique item ID: ' ||
                                                fpsprimaryid ||
                                                ' was updated with wearerinventory finishingmethod',
                                                2);
                        exception
                          when others then
                            begin
                              lvnerrormsg := 'No wearerinv. wearer: ' || to_char(x(i).wearernumber) ||
                                             ' cust: ' || to_char(x(i).customernumber) || ' prod: ' || x(i).productcode ||
                                             'size: ' || x(i).sizecode;
                              pack_import.write_log(lvnerrormsg || ' ID: ' || fpsprimaryid, 3);
                              pack_import.write_log(sqlerrm || ' ID: ' || fpsprimaryid, 5);
                              fpbimport_allowed     := false;
                              fpnwearerinventory_id := null;
                            end;
                        end;
                      when others then
                        begin
                          lvnerrormsg := 'No wearerinv. wearer: ' || to_char(x(i).wearernumber) ||
                                         ' cust: ' || to_char(x(i).customernumber) || ' prod: ' || x(i).productcode ||
                                         'size: ' || x(i).sizecode;
                          pack_import.write_log(lvnerrormsg || ' ID: ' || fpsprimaryid, 3);
                          pack_import.write_log(sqlerrm || ' ID: ' || fpsprimaryid, 5);
                          fpbimport_allowed     := false;
                          fpnwearerinventory_id := null;
                        end;
                    end;
                end; -- if x(i).poolitem = 1 else ..
              end if; -- if x(i).poolitem = 1 then else...
            end;
          else
            begin
              -- stock.poolitem=0
              fpncustomer_id          := null;
              fpncustomernumber       := 0;
              fpnfinishingmethod_id   := null;
              fpnwearer_id            := null;
              fpnwearernumber         := 0;
              fpnweareremployment_id  := null;
              fpndistributionpoint_id := null;
              fpnissuedbyworkorder_id := null;
              fpnwearerinventory_id   := null;
              fpnlastonstockdate      := trunc(sysdate);
              if x(i).stockroomcode is not null then
                begin
                  -- determine the stock room
                  select s.stockroom_id
                  into   fpnstockroom_id
                  from   stockroom s
                  where  s.code = x(i).stockroomcode;
                  --determine the location
                  pack_import_stock.create_stockroomlocation(fpnstockroom_id, x(i).locationcode,
                                                             x(i).rowcode, x(i).stockroomareacode,
                                                             fpnstockroomlocation_id);
                exception
                  when others then
                    begin
                      lvnerrormsg := 'Stockroom / location ' || to_char(x(i).stockroomcode) ||
                                     ' / ' || nvl(x(i).locationcode, 'NULL') || ' ' ||
                                     substr(sqlerrm, 1, 512);
                      pack_import.write_log(lvnerrormsg, -3);
                      fpbimport_allowed       := false;
                      fpnstockroom_id         := null;
                      fpnstockroomlocation_id := null;
                    end;
                end;
              end if;
            end; -- else stock.
          end if;
          -- check customer owned and related customer fields.
          if x(i).customerowned = 'Y' and fpnrelatedcustomer_id is null then
            fpnrelatedcustomer_id := fpncustomer_id;
          end if;
          -- check status / stay combination.
          if fpsstatus_code = '30' and x(i).stay in (23, 30) then
            begin
              fpbimport_allowed := false;
              lvnerrormsg       := 'Wrong status/stay combination for ID: ' || fpsprimaryid ||
                                   ' status ' || fpsstatus_code || ' stay ' || to_char(x(i).stay);
              pack_import.write_log(lvnerrormsg, -3);
            end;
          end if;
          if fpsstatus_code = '10' and x(i).stay not in (10, 11) then
            begin
              fpbimport_allowed := false;
              lvnerrormsg       := 'Wrong status/stay combination for ID: ' || fpsprimaryid ||
                                   ' status ' || fpsstatus_code || ' stay ' || to_char(x(i).stay);
              pack_import.write_log(lvnerrormsg, -3);
            end;
          end if;
          if fpbimport_allowed and (x(i).status <> '40' or x(i).poolitem = 3) then
            begin
              if x(i).replacementprice = 0 then
                fpnresidualvalue := 0;
              else
                fpnresidualvalue := (nvl(x(i).residualvalueamount, 0) /
                                    nvl(x(i).replacementprice, 1) * 100);
              end if;
              -- Inserting the unique items in ABSSolute database.
              insert into uniqueitem
                (uniqueitem_id, primaryid, idcodesequencenumber, statuschangedate, staychangedate,
                 lastinscandate, lastoutscandate, lastscandate, iteminfoupdatedate, poolitem,
                 washestotal, repairstotal, rewashtotal, customerowned, businessunit_id, status_id,
                 prevstatus_id, prevstay_id, stay_id, product_id, sizedefinition_id,
                 finishingmethod_id, relatedcustomer_id, distributionpoint_id,
                 lastdistributionpoint_link_id, planneddeliverydate, deliveryfromstock,
                 startrentfrom, unrelatedloan_id, systemuser_id, timestamp, residualvalue,
                 replacementprice, activestocklocation_id, residualvalueamount, leaseweeks , lastdeliverynotenumber)
              values
                (seq_uniqueitem.nextval, fpsprimaryid, nvl(x(i).idcodesequencenumber, 1),
                 x(i).statuschangedate, x(i).staychangedate, x(i).lastinscandate,
                 x(i).lastoutscandate, x(i).lastscandate, x(i).lastscandate, x(i).poolitem,
                 nvl(x(i).washestotal, 0), nvl(x(i).repairtotal, 0), nvl(x(i).rewashestotal, 0),
                 x(i).customerowned, fpnbusinessunit_id, fpnstatus_id, fpnstatus_id, fpnstay_id,
                 fpnstay_id, fpnproduct_id, fpnsizedefinition_id, fpnfinishingmethod_id,
                 fpnrelatedcustomer_id, fpndistributionpoint_id, fpndistributionpoint_id, null, 'N',
                 nvl(x(i).startrentfrom, 2), null, pack_import.lvnsystemuserid, sysdate,
                 fpnresidualvalue, x(i).replacementprice, fpnactivestocklocation_id,
                 x(i).residualvalueamount, x(i).leaseweeks,fpnlastdeliverynotenumber)
              returning uniqueitem_id into fpnuniqueitem_id;
              insert into uniqueitem_link
                (uniqueitem_link_id, uniqueitem_id, raggeditem_id, systemuser_id, timestamp)
              values
                (fpnuniqueitem_id, fpnuniqueitem_id, null, pack_import.lvnsystemuserid, sysdate);
              if x(i).lastissuedate is not null and x(i).firstissuedate is null then
                x(i).firstissuedate := x(i).lastissuedate;
              else
                if x(i).daysincircprevissue = 0 then
                  x(i).daysincircprevissue := nvl(x(i).lastissuedate - x(i).firstissuedate, 0);
                end if;
              end if;
              insert into uniqueitemfixedinfo
                (uniqueitem_id, purchasedate, lastonstockdate, firstissuedate, lastissuedate,
                 numberofissues, enddatefullrent, daysincircprevissue, daysinstockprevious,
                 purchaseprice, remark, qualitygrade_id, supplier_id, currency_id,
                 issuedbyworkorder_id, reasoncode_id, systemuser_id, timestamp, temporaryid,
                 stockroomlocation_id)
              values
                (fpnuniqueitem_id, x(i).purchasedate, fpnlastonstockdate, x(i).firstissuedate,
                 x(i).lastissuedate, x(i).numberofissues,
                 nvl(x(i).enddatefullrent, to_date('31-12-2099', 'dd-mm-yyyy')),
                 x(i).daysincircprevissue, x(i).daysinstockprevissue, x(i).purchaseprice,
                 x(i).remark, fpnqualitygrade_id, fpnsupplier_id, fpncurrency_id,
                 fpnissuedbyworkorder_id, fpnreasoncode_id, pack_import.lvnsystemuserid, sysdate,
                 'N', fpnstockroomlocation_id);
              if fpsstatus_code in ('20', '30') and x(i).poolitem not in (1, 3) then
                -- only when in circulation
                insert into uniqueitemnonpool
                  (uniqueitem_id, garmentsequencenumber, wearerinventory_id, weareremployment_id,
                   washesthisissue, repairsthisissue, rewashthisissue, freeextragarment,
                   enddatefreeextra, systemuser_id, timestamp)
                values
                  (fpnuniqueitem_id, nvl(x(i).garmentsequencenumber, 1), fpnwearerinventory_id,
                   fpnweareremployment_id, nvl(x(i).washesthisissue, 0),
                   nvl(x(i).repairthisissue, 0), nvl(x(i).rewashesthisissue, 0),
                   nvl(x(i).freeextragarments, 'N'), x(i).enddatefreeextra,
                   pack_import.lvnsystemuserid, sysdate);
              end if;
              if x(i).flagcode is not null then
                -- add flag when needed.
                begin
                  import_flag(x(i).flagcode, x(i).flagdescription,
                              nvl(x(i).flagstartdate, trunc(sysdate)), x(i).flagfreetext,
                              fpnuniqueitem_id);
                end;
              end if;
              if x(i).modificationcode1 is not null then
                begin
                  -- add modification 1
                  addmodification(fpnuniqueitem_id, 1, x(i).modificationcode1,
                                  x(i).modificationdescription1);
                exception
                  when others then
                    begin
                      lvnerrormsg := 'Error adding modification 1: ' || x(i).modificationcode1;
                      pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512) || ' ID:' ||
                                            fpsprimaryid, -3);
                    end;
                end;
              end if;
              if x(i).modificationcode2 is not null then
                begin
                  -- add modification 2
                  addmodification(fpnuniqueitem_id, 2, x(i).modificationcode2,
                                  x(i).modificationdescription2);
                exception
                  when others then
                    begin
                      lvnerrormsg := 'Error adding modification 2: ' || x(i).modificationcode2;
                      pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512) || ' ID:' ||
                                            fpsprimaryid, -3);
                    end;
                end;
              end if;
              if x(i).modificationcode3 is not null then
                begin
                  -- add modification 3
                  addmodification(fpnuniqueitem_id, 3, x(i).modificationcode3,
                                  x(i).modificationdescription3);
                exception
                  when others then
                    begin
                      lvnerrormsg := 'Error adding modification 3: ' || x(i).modificationcode3;
                      pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512) || ' ID:' ||
                                            fpsprimaryid, -3);
                    end;
                end;
              end if;
            exception
              when dup_val_on_index then
                begin
                  --barcode already existed..?
                  pack_import.write_log('Error adding primaryid ' || fpsprimaryid || ' bu ' || x(i).businessunit ||
                                        ' already exists! ' || substr(sqlerrm, 1, 512), -3);
                end;
            end;
          else
            if fpsstatus_code = '40' and x(i).poolitem <> 3 then
              begin
                --item ragged.
                insert into raggeditem
                  (raggeditem_id, primaryid, secondaryid, ragtimestamp, ragreason_id,
                   garmsequencenumber, prevstatus_id, prevstay_id, product_link_id,
                   sizedefinition_link_id, poolitem, purchasedate, lastonstockdate, firstissuedate,
                   lastissuedate, numberofissues, enddatefullrent, qualitygrade_id, washestotal,
                   repairstotal, rewashtotal, daysincirculation, daysinstock, supplier_id,
                   purchaseprice, customerowned, relatedcustomerlink_id,
                   lastweareremployment_link_id, reasoncode_id, residualvalue,
                   lastdistributionpoint_link_id, businessunit_id, weareremployment_link_id,
                   distributionpoint_link_id, systemuser_id, timestamp)
                values
                  (seq_uniqueitem.nextval, fpsprimaryid, x(i).secondaryid, x(i).lastscandate,
                   fpnragreason_id, nvl(x(i).idcodesequencenumber, 1), fpnstatus_id, fpnstay_id,
                   fpnproduct_id, fpnsizedefinition_id, x(i).poolitem, x(i).purchasedate, null,
                   x(i).firstissuedate, x(i).lastissuedate, nvl(x(i).numberofissues, 0),
                   x(i).enddatefullrent, fpnqualitygrade_id, nvl(x(i).washestotal, 0),
                   nvl(x(i).repairtotal, 0), nvl(x(i).rewashestotal, 0),
                   nvl(x(i).daysincircprevissue, 0), nvl(x(i).daysinstockprevissue, 0),
                   fpnsupplier_id, nvl(x(i).purchaseprice, 0), x(i).customerowned,
                   fpnrelatedcustomer_id, null, fpnreasoncode_id, 0, fpndistributionpoint_id,
                   fpnbusinessunit_id, null, fpndistributionpoint_id, pack_import.lvnsystemuserid,
                   sysdate) return raggeditem_id into fpnuniqueitem_id;
                insert into uniqueitem_link
                  (uniqueitem_link_id, uniqueitem_id, raggeditem_id, systemuser_id, timestamp)
                values
                  (fpnuniqueitem_id, null, fpnuniqueitem_id, pack_import.lvnsystemuserid, sysdate);
                --count ragged items
                lv_raggeditems := lv_raggeditems + 1;
              end;
            end if; --item ragged.
          end if; -- if fpbimport_allowed = true then
          if (fpnuniqueitem_id <> 0 and fpnuniqueitem_id is not null) then
            -- idcode was inserted,
            begin
              -- count number of unique items added.
              fpnnumberofuniqueitems := fpnnumberofuniqueitems + 1;
            end;
          end if;
        exception
          when others then
            begin
              lvnerrormsg := 'ConvertUniqueItem, ID code: ' || fpsprimaryid || ' status ' ||
                             fpsstatus_code;
              pack_import.write_log(lvnerrormsg || '
                                ' || substr(sqlerrm, 1, 512), -3);
            end;
        end;
      end loop;
      if c1%notfound then
        data_exists := false;
      end if;
      close c1;
      commit; -- commit after closing cursor releases rollback space.
    end loop;
    begin
      -- insert secondaryuniqueitem
      insert into secondaryuniqueitem
        (uniqueitem_id, businessunit_id, secondaryid, systemuser_id, timestamp)
        select u.uniqueitem_id, u.businessunit_id, i.secondaryid, u.systemuser_id, sysdate
        from   i_uniqueitem i, uniqueitem u, businessunit bu
        where  i.secondaryid is not null
        and    u.businessunit_id = bu.businessunit_id
        and    u.primaryid = i.primaryid
        and    u.idcodesequencenumber = i.idcodesequencenumber
        and    bu.code = i.businessunit
        and    not exists (select x.uniqueitem_id
                from   secondaryuniqueitem x
                where  x.uniqueitem_id = u.uniqueitem_id)
        and    not exists (select y.uniqueitem_id
                from   secondaryuniqueitem y
                where  y.secondaryid = i.secondaryid
                and    y.businessunit_id = u.businessunit_id);
      commit;
    exception
      when others then
        pack_import.write_log('Error insert secondary ids. ' || sqlerrm);
    end;
    updatewearerinventory; -- to correct the amounts
    lvnerrormsg := '    missing plpc: ' || to_char(fpncountplpc) || ' records added.';
    pack_import.write_log(lvnerrormsg);
    begin
      -- update recordpassivestock if needed for products in i_uniqueitem
      update /*+full(p)*/ product p
      set    p.recordpassivestock = 'Y'
      where  p.recordpassivestock <> 'Y'
      and    exists (select u.product_id
              from   uniqueitem u, uniqueitemfixedinfo o
              where  u.uniqueitem_id = o.uniqueitem_id
              and    o.stockroomlocation_id is not null
              and    u.product_id = p.product_id)
      and    exists (select i.productcode from i_uniqueitem i where i.productcode = p.code);
      commit;
    exception
      when others then
        pack_import.write_log('Error update product.recordpassivestock.', 3);
    end;
    lvnerrormsg := '    check number: ' || to_char(fpnitableuniqueitems) ||
                   ' unique items already existed in uniqueitem.';
    pack_import.write_log(lvnerrormsg);
    --count i-table uniqueitems.
    select count(*) into fpnitableuniqueitems from i_uniqueitem;
    lvnerrormsg := '    check number: ' || to_char(fpnitableuniqueitems) ||
                   ' unique items in i-uniqueitem.' || ' SUCCES ConvertUniqueItem: ' ||
                   to_char(fpnnumberofuniqueitems) || ' unique items converted,this run.';
    pack_import.write_log(lvnerrormsg);
    if lv_raggeditems > 0 then
      begin
        pack_import.write_log('of which ' || to_char(lv_raggeditems) || ' ragged items');
      end;
    end if;
    select count(1)
    into   fpnitableuniqueitems
    from   i_uniqueitem i
    where  i.status <> '40' --do not count ragged items
    and    not exists (select u.primaryid
            from   uniqueitem u, businessunit b
            where  u.primaryid = i.primaryid
            and    u.businessunit_id = b.businessunit_id
            and    i.idcodesequencenumber = u.idcodesequencenumber
            and    b.code = i.businessunit);
    if fpnitableuniqueitems > 0 then
      begin
        lvnerrormsg := '    check number: ' || to_char(fpnitableuniqueitems) ||
                       ' still to be converted from i_uniqueitem!';
        pack_import.write_log(lvnerrormsg);
      end;
    end if;
    select count(1) into fpnitableuniqueitems from uniqueitem;
    lvnerrormsg := '    check number: ' || to_char(fpnitableuniqueitems) || ' now in uniqueitem.';
    pack_import.write_log(lvnerrormsg);
    --OR module conversion unique items seperate steps
    convertuniqueorpack;
    convertuniqueorsterile;
    --convertuniqueloss
    convertuniqueloss;
    --convertuniqueorpackcontents
    convertuniqueorpackcontents;
    begin
      --insert into modificationspergroup
      insert into modificationspergroup
        (modificationgroup_id, modification_id, sequencenumber, timestamp, systemuser_id)
        select g.modificationgroup_id, mo.modification_id,
               nvl((select max(x.sequencenumber)
                    from   modificationspergroup x
                    where  x.modificationgroup_id = g.modificationgroup_id), 0) + rownum, sysdate,
               pack_import.lvnsystemuserid
        from   modification mo, modificationgroup g,
               (select iu.modificationcode1 modificationcode
                 from   i_uniqueitem iu
                 where  iu.modificationcode1 is not null
                 union
                 select iu.modificationcode2 modificationcode
                 from   i_uniqueitem iu
                 where  iu.modificationcode2 is not null
                 union
                 select iu.modificationcode3 modificationcode
                 from   i_uniqueitem iu
                 where  iu.modificationcode3 is not null) ix
        where  g.code = '-'
        and    ix.modificationcode = mo.code
        and    not exists (select 1
                from   modificationspergroup x
                where  x.modificationgroup_id = g.modificationgroup_id
                and    x.modification_id = mo.modification_id);
    exception
      when others then
        begin
          lvnerrormsg := 'convertuniqueitem: Fail to insert modificationspergroup';
          pack_import.write_log(lvnerrormsg || ' ' || substr(sqlerrm, 1, 512), -3);
        end;
    end;
    --add missing customer activities
    cfbaddmiscustactivities;
    --convert_uniqueitememblem
    convert_uniqueitememblem;
    --convert_uniqueitemimage
    convert_uniqueitemimage;
  exception
    when error_customerrelatedstock then
      begin
        pack_import.write_log('Error during ConvertUniqueitem ' || lvnerrormsg, 3);
      end;
    when error_missing_data then
      begin
        lvnerrormsg := 'ERROR there are ' || to_char(fpnmissingcurrency) ||
                       ' missing currencies and/or ' || to_char(fpnmissingstockroom) ||
                       ' missing stockrooms in the database, please add them and run this step again.';
        pack_import.write_log(lvnerrormsg, 3);
      end;
    when others then
      begin
        rollback;
        lvnerrormsg := 'Error ConvertUniqueItem, ID code: ' || fpsprimaryid;
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end convertuniqueitem;
  procedure convertuniqueorpack is
    lvncounter             number;
    lvntreatmenttype_id    treatmenttype.treatmenttype_id%type;
    lvnlabellayout_id      labellayout.labellayout_id%type;
    lvncreationemployee_id employee.employee_id%type;
    lvnassembleemployee_id employee.employee_id%type;
    lvnloademployee_id     employee.employee_id%type;
    lvndeliveryemployee_id employee.employee_id%type;
    lvncancelemployee_id   employee.employee_id%type;
    lvnrecallemployee_id   employee.employee_id%type;
    lvnreasoncode_id       reasoncode.reasoncode_id%type;
  begin
    begin
      --delivery label layout
      for x in (select ip.assemblylayout, 0 sterile
                from   i_uniqueorpack ip
                where  ip.assemblylayout is not null
                and    not exists (select 1
                        from   labellayout ll
                        where  ll.code = ip.assemblylayout
                        and    ll.labeltype = 4)
                group  by ip.assemblylayout) loop
        begin
          insert into labellayout
            (labellayout_id, code, description, labeltype, defaultlayout, systemuser_id, timestamp,
             layoutreceiveonstock, sterile)
          values
            (seq_labellayout.nextval, x.assemblylayout, x.assemblylayout, 4, 'N',
             pack_import.lvnsystemuserid, sysdate, 'N', x.sterile);
        exception
          when dup_val_on_index then
            null;
        end;
      end loop;
    exception
      when others then
        begin
          pack_import.write_log('convertuniqueorpack: During adding of all assembly label layout ' ||
                                substr(sqlerrm, 1, 512), 3);
        end;
    end;
    --import uniqueorpack
    select count(1) into lvncounter from i_uniqueorpack;
    pack_import.write_log(lvncounter || ' i_uniqueorpack records in i-table');
    lvncounter := 0;
    --loop i_uniqueorpack
    for x in (select i.*, u.uniqueitem_id, bu.plant_id
              from   i_uniqueorpack i, uniqueitem u, businessunit bu
              where  i.primaryid = u.primaryid
              and    i.businessunit = bu.code
              and    bu.businessunit_id = u.businessunit_id
              and    i.idcodesequencenumber = u.idcodesequencenumber
              and    not exists
               (select 1 from uniqueorpack up where up.uniqueitem_id = u.uniqueitem_id)) loop
      begin
        --lvntreatmenttype_id
        pack_import.cfbcreate_treatmenttype(lvntreatmenttype_id, x.treatmenttype);
        --lvnlabellayout_id -> created previous step
        select ll.labellayout_id
        into   lvnlabellayout_id
        from   labellayout ll
        where  ll.code = x.assemblylayout
        and    ll.labeltype = 4;
        --lvncreationemployee_id
        pack_import.cfbgetcreate_employee(x.plant_id, lvncreationemployee_id,
                                          x.creationemployeenumber, x.creationemployeenumber, null,
                                          null, null, null, null, null, null);
        --lvnassembleemployee_id
        pack_import.cfbgetcreate_employee(x.plant_id, lvnassembleemployee_id,
                                          x.assembleemployeenumber, x.assembleemployeenumber, null,
                                          null, null, null, null, null, null);
        --lvnloademployee_id
        pack_import.cfbgetcreate_employee(x.plant_id, lvnloademployee_id, x.loademployeenumber,
                                          x.loademployeenumber, null, null, null, null, null, null,
                                          null);
        --lvndeliveryemployee_id
        pack_import.cfbgetcreate_employee(x.plant_id, lvndeliveryemployee_id,
                                          x.deliveryemployeenumber, x.deliveryemployeenumber, null,
                                          null, null, null, null, null, null);
        --lvncancelemployee_id
        pack_import.cfbgetcreate_employee(x.plant_id, lvncancelemployee_id, x.cancelemployeenumber,
                                          x.cancelemployeenumber, null, null, null, null, null, null,
                                          null);
        --lvnrecallemployee_id
        pack_import.cfbgetcreate_employee(x.plant_id, lvnrecallemployee_id, x.recallemployeenumber,
                                          x.recallemployeenumber, null, null, null, null, null, null,
                                          null);
        if x.reasoncode is null then
          lvnreasoncode_id := null;
        else
          begin
            --reasoncode
            select rs.reasoncode_id
            into   lvnreasoncode_id
            from   reasoncode rs
            where  rs.code = x.reasoncode;
          exception
            when no_data_found then
              begin
                pack_import.cfbcreate_reasoncode(lvnreasoncode_id, x.reasoncode);
                pack_import.cfbcreate_reasoncode_desc(lvnreasoncode_id, x.reasoncode);
              end;
          end;
        end if;
        --insert uniqueorpack
        insert into uniqueorpack
          (uniqueitem_id, treatmenttype_id, stockexpirationdate, creationtimestamp,
           creationemployee_id, labellayout_id, assembletimestamp, assembleemployee_id,
           loadtimestamp, loademployee_id, deliverytimestamp, deliveryemployee_id, canceltimestamp,
           cancelemployee_id, recalltimestamp, recallemployee_id, reasoncode_id, systemuser_id,
           timestamp)
        values
          (x.uniqueitem_id, lvntreatmenttype_id, x.stockexpirationdate, x.creationtimestamp,
           lvncreationemployee_id, lvnlabellayout_id, x.assembletimestamp, lvnassembleemployee_id,
           x.loadtimestamp, lvnloademployee_id, x.deliverytimestamp, lvndeliveryemployee_id,
           x.canceltimestamp, lvncancelemployee_id, x.recalltimestamp, lvnrecallemployee_id,
           lvnreasoncode_id, pack_import.lvnsystemuserid, sysdate);
        --set uniqueitem as OR PACK
        update uniqueitem u
        set    u.poolitem = 3, u.expirationdate = x.expirationdate
        where  u.uniqueitem_id = x.uniqueitem_id
        and    u.poolitem <> 3;
        commit;
        lvncounter := lvncounter + 1;
      end;
    end loop;
    pack_import.write_log(to_char(lvncounter) ||
                          ' records processed into uniqueorpack from i_uniqueorpack');
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('Error during convertuniqueorpack ' || substr(sqlerrm, 1, 512), 3);
        if lvncounter > 0 then
          pack_import.write_log(to_char(lvncounter) ||
                                ' records were processed into uniqueorpack from i_uniqueorpack');
        end if;
      end;
  end convertuniqueorpack;
  procedure convert_uniqueitememblem is
    lvncounter number := 0;
  begin
    --convert_uniqueitememblem
    insert into uniqueitememblem
      (uniqueitememblem_id, uniqueitem_link_id, product_link_id, sizedefinition_link_id,
       description, emblemtype, attachdate, quantity, systemuser_id, timestamp, embroiderylettering,
       embroideryletteringline1, embroideryletteringline2, embroideryletteringline3,
       emblemtemplateline_id, placement_id)
      select seq_uniqueitememblem.nextval, ur.uniqueitem_id, tl.product_id, tl.sizedefinition_id,
             tl.description, tl.emblemtype, u.firstissuedate, tl.qtypergarment, ur.systemuser_id,
             sysdate, tl.embroiderylettering, tl.embroideryletteringline1,
             tl.embroideryletteringline2, tl.embroideryletteringline3, tl.emblemtemplateline_id,
             tl.placement_id
      from   i_uniqueitem u
      join   businessunit bu
      on     bu.code = u.businessunit
      join   emblemtemplate t
      on     t.code = u.emblemtemplate
      join   emblemtemplateline tl
      on     tl.emblemtemplate_id = t.emblemtemplate_id
      join   uniqueitem ur
      on     (ur.primaryid = u.primaryid and ur.businessunit_id = bu.businessunit_id and
             ur.idcodesequencenumber = u.idcodesequencenumber)
      where  u.typeofmerchandise = 2
      and    not exists
       (select 1 from uniqueitememblem x where x.uniqueitem_link_id = ur.uniqueitem_id);
    lvncounter := sql%rowcount;
    if lvncounter > 0 then
      begin
        commit;
        pack_import.write_log(to_char(lvncounter) ||
                              ' records were inserted into uniqueitememblem');
      end;
    end if;
  end convert_uniqueitememblem;
  procedure get_sterilizationrun(fp_sterilizationrunid     out sterilizationrun.sterilizationrun_id%type,
                                 fp_businessunitid         in businessunit.businessunit_id%type,
                                 fp_chargenumber           in sterilizationrun.chargenumber%type,
                                 fp_employeeid             in employee.employee_id%type,
                                 fp_sterilizercode         in sterilizer.code%type,
                                 fp_plantid                in plant.plant_id%type,
                                 fp_treatementtypeid       in treatmenttype.treatmenttype_id%type,
                                 fp_rejectionreasondid     in reasoncode.reasoncode_id%type,
                                 fp_sterilizationtimestamp in sterilizationrun.sterilizationtimestamp%type,
                                 fp_rejectemployeeid       in sterilizationrun.rejectemployee_id%type,
                                 fp_approvalemployeeid     in sterilizationrun.approvalemployee_id%type) is
    lvnsterilizer_id sterilizer.sterilizer_id%type;
  begin
    begin
      --sterilizer
      select st.sterilizer_id
      into   lvnsterilizer_id
      from   sterilizer st
      where  st.code = fp_sterilizercode
      and    st.plant_id = fp_plantid;
    exception
      when no_data_found then
        begin
          insert into sterilizer
            (sterilizer_id, plant_id, code, active, description, systemuser_id, timestamp)
          values
            (seq_sterilizer.nextval, fp_plantid, fp_sterilizercode, 'Y', fp_sterilizercode,
             pack_import.lvnsystemuserid, sysdate)
          returning sterilizer_id into lvnsterilizer_id;
        end;
    end;
    begin
      select sr.sterilizationrun_id
      into   fp_sterilizationrunid
      from   sterilizationrun sr
      where  sr.businessunit_id = fp_businessunitid
      and    sr.chargenumber = fp_chargenumber;
    exception
      when no_data_found then
        --status completed
        insert into sterilizationrun
          (sterilizationrun_id, businessunit_id, chargenumber, employee_id, sterilizer_id,
           treatmenttype_id, rejectreasoncode_id, systemuser_id, timestamp, status,
           sterilizationtimestamp, rejectemployee_id, approvalemployee_id)
        values
          (seq_sterilizationrun.nextval, fp_businessunitid, fp_chargenumber, fp_employeeid,
           lvnsterilizer_id, fp_treatementtypeid, fp_rejectionreasondid, pack_import.lvnsystemuserid,
           sysdate, 6, fp_sterilizationtimestamp, fp_rejectemployeeid, fp_approvalemployeeid)
        returning sterilizationrun_id into fp_sterilizationrunid;
    end;
  end get_sterilizationrun;
  procedure get_cart(fp_cart_id    out cart.cart_id%type,
                     fp_cartnumber in cart.cartnumber%type,
                     fp_plantid    in plant.plant_id%type,
                     fp_carttype   in carttype.code%type) is
    lv_status_id   status.status_id%type;
    lv_carttype_id carttype.carttype_id%type;
  begin
    begin
      --get/or create cart
      select t.cart_id
      into   fp_cart_id
      from   cart t
      where  t.cartnumber = fp_cartnumber
      and    t.plant_id = fp_plantid;
    exception
      when no_data_found then
        begin
          begin
            --get/or create cart type
            select t.carttype_id into lv_carttype_id from carttype t where t.code = fp_carttype;
          exception
            when no_data_found then
              begin
                insert into carttype
                  (carttype_id, code, factorydescription, systemuser_id, timestamp)
                values
                  (seq_carttype.nextval, fp_carttype, fp_carttype, pack_import.lvnsystemuserid,
                   sysdate)
                returning carttype_id into lv_carttype_id;
                insert into carttype_desc
                  (carttype_id, language_id, description, systemuser_id, timestamp)
                values
                  (lv_carttype_id, pack_import.lvnlanguageid, fp_carttype,
                   pack_import.lvnsystemuserid, sysdate);
              end;
          end;
          --get cart status
          select st.status_id
          into   lv_status_id
          from   status st
          where  st.statustype = 'CA'
          and    st.code = '10';
          --create cart
          insert into cart
            (cart_id, plant_id, cartnumber, carttype_id, status_id, systemuser_id, timestamp)
          values
            (seq_cart.nextval, fp_plantid, fp_cartnumber, lv_carttype_id, lv_status_id,
             pack_import.lvnsystemuserid, sysdate)
          returning cart_id into fp_cart_id;
        end;
    end;
  end get_cart;
  procedure convertuniqueorsterile is
    lvncounter                  number := 0;
    lvnrejectreasonid           reasoncode.reasoncode_id%type;
    lvnsterilizationemployee_id employee.employee_id%type;
    lvnsterilizationrunid       sterilizationrun.sterilizationrun_id%type;
    lvncartid                   cart.cart_id%type;
    lv_rejectemployeeid         employee.employee_id%type;
    lv_approvalemployeeid       employee.employee_id%type;
  begin
    --loop i_uniqueorsterile
    for x in (select i.*, bu.businessunit_id, u.uniqueitem_id, bu.plant_id,
                     (select max(up.treatmenttype_id)
                       from   uniqueorpack up
                       where  u.uniqueitem_id = up.uniqueitem_id) treatmenttype_id
              from   i_uniqueorsterile i, uniqueitem u, businessunit bu
              where  i.businessunit = bu.code
              and    i.primaryid = u.primaryid
              and    i.idcodesequencenumber = u.idcodesequencenumber
              and    exists
               (select 1 from uniqueorpack up where u.uniqueitem_id = up.uniqueitem_id)
              and    not exists
               (select 1 from uniqueorpacksterile us where us.uniqueitem_id = u.uniqueitem_id)) loop
      begin
        --rejection reason
        if x.rejectionreasoncode is null then
          lvnrejectreasonid := null;
        else
          begin
            --reasoncode
            select rs.reasoncode_id
            into   lvnrejectreasonid
            from   reasoncode rs
            where  rs.code = x.rejectionreasoncode;
          exception
            when no_data_found then
              begin
                pack_import.cfbcreate_reasoncode(lvnrejectreasonid, x.rejectionreasoncode);
                pack_import.cfbcreate_reasoncode_desc(lvnrejectreasonid, x.rejectionreasoncode);
              end;
          end;
        end if;
        --get employee's
        pack_import.cfbgetcreate_employee(x.plant_id, lv_rejectemployeeid, x.rejectemployee,
                                          x.rejectemployee, null, null, null, null, null, null, null);
        pack_import.cfbgetcreate_employee(x.plant_id, lv_approvalemployeeid,
                                          x.approvalemployeenumber, x.approvalemployeenumber, null,
                                          null, null, null, null, null, null);
        pack_import.cfbgetcreate_employee(x.plant_id, lvnsterilizationemployee_id,
                                          x.sterilizationemployeenumber,
                                          x.sterilizationemployeenumber, null, null, null, null,
                                          null, null, null);
        get_sterilizationrun(lvnsterilizationrunid, x.businessunit_id, x.chargenumber,
                             lvnsterilizationemployee_id, x.sterilizercode, x.plant_id,
                             x.treatmenttype_id, lvnrejectreasonid, x.sterilizationtimestamp,
                             lv_rejectemployeeid, lv_approvalemployeeid);
        get_cart(lvncartid, x.cartnumber, x.plant_id, x.carttype);
        --insert into
        insert into uniqueorpacksterile
          (uniqueitem_id, sterilizationtimestamp, sterilizationemployee_id, systemuser_id,
           timestamp, sterilizationrun_id, cart_id)
        values
          (x.uniqueitem_id, x.sterilizationtimestamp, lvnsterilizationemployee_id,
           pack_import.lvnsystemuserid, sysdate, lvnsterilizationrunid, lvncartid);
        commit;
        lvncounter := lvncounter + 1;
      end;
    end loop;
    if lvncounter > 0 then
      pack_import.write_log(to_char(lvncounter) ||
                            ' records were processed into uniqueorpacksterile from i_uniqueorsterile');
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('Error during convertuniqueorsterile ' || substr(sqlerrm, 1, 512), 3);
        if lvncounter > 0 then
          pack_import.write_log(to_char(lvncounter) ||
                                ' records were processed into uniqueorpacksterile from i_uniqueorsterile');
        end if;
      end;
  end convertuniqueorsterile;
  procedure convertuniqueloss is
    lv_count number := 0;
  begin
    for x in (select u.uniqueitem_id, cu.customer_id, dp.distributionpoint_id,
                     lp.lossperiods_id lossperiods_id, io.outscandate, io.lossamount
              from   i_uniqueitemloss io
              join   businessunit bu
              on     bu.code = io.businessunit
              join   uniqueitem u
              on     u.businessunit_id = bu.businessunit_id
              and    u.primaryid = io.primaryid
              and    u.idcodesequencenumber = u.idcodesequencenumber
              and    u.poolitem = 1
              join   customer cu
              on     cu.customernumber = io.customernumber
              join   department t
              on     t.departmentnumber = io.departmentnumber
              and    t.customer_id = cu.customer_id
              join   distributionpoint dp
              on     dp.distributionpointnumber = io.distributionpointnumber
              and    dp.department_id = t.department_id
              join   lossperiods lp
              on     lp.year = io.periodyear
              and    lp.period = io.period) loop
      begin
        insert into uniqueitemloss
          (uniqueitemloss_id, uniqueitem_link_id, customer_link_id, distributionpoint_link_id,
           lossstatus, lossperiods_id, outscandate, returneddate, lossinvoiceheader_id, lossamount,
           creditinvoiceheader_id, creditamount, systemuser_id, timestamp)
        values
          (seq_uniqueitemloss.nextval, x.uniqueitem_id, x.customer_id, x.distributionpoint_id, 1,
           x.lossperiods_id, x.outscandate, to_date('31-12-2099', 'DD-MM-YYYY'), null, x.lossamount,
           null, 0, pack_import.lvnsystemuserid, sysdate);
        lv_count := lv_count + 1;
      end;
    end loop;
    commit;
    if lv_count > 0 then
      pack_import.write_log(to_char(lv_count) ||
                            ' records were processed into uniqueitemloss from i_uniqueitemloss');
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('Error during uniqueitemloss ' || substr(sqlerrm, 1, 512), 3);
      end;
  end convertuniqueloss;
  procedure convert_uniqueitemimage is
    lv_count number := 0;
  begin
    --convert_uniqueitemimage
    insert into uniqueitemimage
      (uniqueitemimage_id, uniqueitem_link_id, image_id, scan_id, systemuser_id, timestamp)
      select seq_uniqueitemimage.nextval, u.uniqueitem_id, i.image_id, ii.scan_id,
             pack_import.lvnsystemuserid, sysdate
      from   i_uniqueitemimage ii
      join   businessunit bu
      on     bu.code = ii.businessunit
      join   uniqueitem u
      on     (u.businessunit_id = bu.businessunit_id and u.primaryid = ii.primaryid and
             u.idcodesequencenumber = ii.idcodesequencenumber)
      join   image i
      on     i.code = ii.imagecode
      and    i.imagetype = ii.imagetype
      where  not exists (select 1
              from   uniqueitemimage ui
              where  ui.uniqueitem_link_id = u.uniqueitem_id
              and    ui.image_id = i.image_id);
    --commit
    commit;
    if lv_count > 0 then
      pack_import.write_log(to_char(lv_count) ||
                            ' records were processed into uniqueitemimage from i_uniqueitemimage');
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('Error during uniqueitemimage ' || substr(sqlerrm, 1, 512), 3);
      end;
  end convert_uniqueitemimage;
begin
  --initialization
  begin
    select min(ragreason_id) into fpnragreason_id from ragreason;
  exception
    when no_data_found then
      begin
        pack_import.cfbcreate_ragreason(fpnragreason_id,
                                        --fpnragreason_id,
                                        'R1',
                                        --fpscode,
                                        'Y',
                                        --fpsactive,
                                        'N'
                                        --fpschargeresidualvalue,
                                        );
        pack_import.cfbcreate_ragreason_desc(fpnragreason_id,
                                             --fpnragreason_id,
                                             '-'
                                             --fpsdescription,
                                             );
      end;
  end;
exception
  when others then
    begin
      lvnerrormsg := 'Error intializing: ';
      pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
    end;
end pack_import_uniqueitem;
/
create or replace package pack_import_us is
  -- Author  : ABS
  -- Created : 30/04/2002 3:40:44 PM
  -- Version : 1.0
  -- Purpose :
  procedure cfbimportus_1;
  procedure cfbimportus_2;
  procedure cfbimportus_3;
  procedure cfbimportus_4;
  procedure cfbimportus_5;
  procedure cfbimportus_6;
  procedure cfbimportus_7;
  procedure cfbimportus_8;
  procedure cfbimportus_9;
  procedure cfbimportus_10;
  procedure cfbimportus_11;
end pack_import_us;
/
create or replace package body pack_import_us is
  procedure cfbimportus_1 is
  begin
    pack_import_eu.cfbimporteu_1;
  end cfbimportus_1;
  procedure cfbimportus_2 is
  begin
    pack_import_eu.cfbimporteu_2;
  end cfbimportus_2;
  procedure cfbimportus_3 is
  begin
    pack_import_eu.cfbimporteu_3;
  end cfbimportus_3;
  procedure cfbimportus_4 is
  begin
    pack_import_eu.cfbimporteu_4;
  end cfbimportus_4;
  procedure cfbimportus_5 is
  begin
    pack_import_eu.cfbimporteu_5;
  end cfbimportus_5;
  procedure cfbimportus_6 is
  begin
    pack_import_eu.cfbimporteu_6;
  end cfbimportus_6;
  procedure cfbimportus_7 is
  begin
    pack_import_eu.cfbimporteu_7;
  end cfbimportus_7;
  procedure cfbimportus_8 is
  begin
    pack_import_eu.cfbimporteu_8;
  end cfbimportus_8;
  procedure cfbimportus_9 is
  begin
    pack_import_eu.cfbimporteu_9;
  end cfbimportus_9;
  procedure cfbimportus_10 is
  begin
    pack_import_eu.cfbimporteu_10;
  end cfbimportus_10;
  procedure cfbimportus_11 is
  begin
    pack_import_eu.cfbimporteu_11;
  end cfbimportus_11;
end pack_import_us;
/
create or replace package pack_import_wearer is
  -- Author  : PVD
  -- Created : 09-Jul-2004 10:43:34
  -- Version : 2.06
  -- Updated : ABS-80717 wearer inventory temporary rent stop conversion
  --           ABS-104716 Circ/Max changes and flagging - customization
  --           ABS-152340 Personalized = N when dummy for pool is Y
  --           ABS-152177 update wearerinventory emblem template
  --           ABSN-7347 Redefine Gender via fixed file
  procedure insert_missing_plpc(customerid        in customer.customer_id%type,
                                productid         in product.product_id%type,
                                finishingmethodid in finishingmethod.finishingmethod_id%type,
                                dateactive        in date,
                                dateinactive      in date,
                                price             in customerrentprice.price%type,
                                pricestartdate    in date,
                                lvsizeid          in sizedefinition.sizedefinition_id%type default null);
  procedure convert_lockers;
  procedure cfbimportwearer;
  procedure cfbimportwearerinventory;
end pack_import_wearer;
/
create or replace package body pack_import_wearer is
  fpntransportarticle_id transportarticle.transportarticle_id%type;
  fpnsizestarid          sizedefinition.sizedefinition_id%type;
  errormsg               varchar2(512);
  function get_deliverypoint(pdeliverypoint       in deliverypoint.code%type,
                             pdeliverypointdesc   in deliverypoint.description%type,
                             pcustomerid          in customer.customer_id%type,
                             psortdeliverypointid out deliverypoint.maincustomerdeliverypoint_id%type)
    return deliverypoint.deliverypoint_id%type is
    ldeliverypointid   deliverypoint.deliverypoint_id%type;
    ldeliveryaddressid address.address_id%type;
  begin
    begin
      select p.deliverypoint_id, p.maincustomerdeliverypoint_id
      into   ldeliverypointid, psortdeliverypointid
      from   deliverypoint p
      where  p.customer_id = pcustomerid
      and    p.code = nvl(pdeliverypoint, '1');
    exception
      when no_data_found then
        begin
          select c.visitaddress_id
          into   ldeliveryaddressid
          from   customer c
          where  c.customer_id = pcustomerid;
          pack_import.cfbcreate_deliverypoint(ldeliverypointid, pcustomerid,
                                              nvl(pdeliverypoint, '1'), nvl(pdeliverypointdesc, '-'),
                                              ldeliveryaddressid, null);
          psortdeliverypointid := null;
        end;
    end;
    return ldeliverypointid;
  exception
    when others then
      begin
        errormsg := 'deliverypoint/custid: ' || nvl(pdeliverypoint, 1) || '/' ||
                    to_char(pcustomerid);
        errormsg := 'Error get_deliverypoint ' || errormsg;
        pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
        return - 1;
      end;
  end get_deliverypoint;
  function get_lockersortgroup(fp_customerid            in customer.customer_id%type,
                               fp_lockersortgroupnumber in lockersortgroup.lockersortgroupnumber%type,
                               fp_lockersortgroupdesc   in lockersortgroup.description%type)
    return lockersortgroup.lockersortgroup_id%type is
    lv_lockersortgroupid lockersortgroup.lockersortgroup_id%type;
  begin
    if fp_lockersortgroupnumber is null then
      return null;
    end if;
    begin
      select lg.lockersortgroup_id
      into   lv_lockersortgroupid
      from   lockersortgroup lg
      where  lg.customer_id = fp_customerid
      and    lg.lockersortgroupnumber = fp_lockersortgroupnumber;
    exception
      when no_data_found then
        begin
          insert into lockersortgroup
            (lockersortgroup_id, customer_id, lockersortgroupnumber, description, active,
             systemuser_id, timestamp)
          values
            (seq_lockersortgroup.nextval, fp_customerid, fp_lockersortgroupnumber,
             nvl(fp_lockersortgroupdesc, to_char(fp_lockersortgroupnumber)), 'Y',
             pack_import.lvnsystemuserid, sysdate)
          returning lockersortgroup_id into lv_lockersortgroupid;
        end;
    end;
    return lv_lockersortgroupid;
  end get_lockersortgroup;
  function import_flag(pflagcode flag.code%type, pflagdescription flag_desc.description%type)
    return flag.flag_id%type is
    lflag_id flag.flag_id%type;
  begin
    begin
      -- determine the right flag
      select flag_id
      into   lflag_id
      from   flag
      where  code = pflagcode
      and    flagtype = 1;
    exception
      when no_data_found then
        begin
          pack_import.cfbcreate_flag(lflag_id,
                                     --fpnflag_id,
                                     1,
                                     --fpnflagtype,
                                     pflagcode,
                                     --fpscode,
                                     1,
                                     --fpnpriority,
                                     'ff 0 0',
                                     --fpscolor,
                                     'Y',
                                     --fpsincludeincompletnesscheck,
                                     null,
                                     --fpnsound_id,
                                     'Y',
                                     --fpsshowalways
                                     'N',
                                     --fpsexporttogarmentdispenser
                                     null,
                                     --fpnexportgdcode
                                     'N'); --fpnuseinwebapplication);
          pack_import.cfbcreate_flag_desc(lflag_id,
                                          --fpnflag_id,
                                          pflagdescription
                                          --fpsdescription,
                                          );
        end;
    end;
    return lflag_id;
  exception
    when others then
      begin
        errormsg := 'Error adding flag: ' || pflagcode;
        pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
        return null;
      end;
  end import_flag;
  procedure insert_missing_plpc(customerid        in customer.customer_id%type,
                                productid         in product.product_id%type,
                                finishingmethodid in finishingmethod.finishingmethod_id%type,
                                dateactive        in date,
                                dateinactive      in date,
                                price             in customerrentprice.price%type,
                                pricestartdate    in date,
                                lvsizeid          in sizedefinition.sizedefinition_id%type default null) is
    plpcid                 productlistpercustomer.productlistpercustomer_id%type;
    residualvalueschemeid  residualvaluescheme.residualvaluescheme_id%type;
    lv_customerrentpriceid customerrentprice.customerrentprice_id%type;
  begin
    -- get default sizestarid and residualvalueschemeid
    select residualvaluescheme_id
    into   residualvalueschemeid
    from   residualvaluescheme
    where  code = '-';
    begin
      -- insert missing productlistpercustomer
      pack_import.cfbcreate_productlistpercust(plpcid, productid, dateactive, dateinactive,
                                               finishingmethodid, 'N', 0, customerid, 'N',
                                               nvl(lvsizeid, fpnsizestarid), 'N', 'Y', 0, 3, 0, 0,
                                               'N', 0, 0, 0, 0, 'N', 'N', 0, 0, 0, null, null, 0,
                                               null, null, null, null, residualvalueschemeid, 2, 3,
                                               0, 'N', null, null, 'N', 'N', 'N', 'N', null, 1, 2, 0,
                                               'N', null, null, 0, null, 'N', null,
                                               'CONVERSION ADDED', null, 0, 0);
      -- insert product finishing method
      pack_import.cfbcreate_prodfinishingmethod(productid, finishingmethodid);
      -- insert customerrentprice
      if pricestartdate is not null and price is not null then
        begin
          pack_import.cfbcreate_customerrentprice(lv_customerrentpriceid, plpcid, price,
                                                  pricestartdate, 5, 2, null);
        exception
          when dup_val_on_index then
            null;
          when others then
            errormsg := 'insert_missing_plpc: Fail to import customerrentprice. ';
            pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
        end;
      end if;
      -- insert product deliveryday
      for vcursor2 in (select a.day_id, a.deliverytype
                       from   customerdeliveryday a
                       where  a.customer_id = customerid
                       and    a.typeofmerchadise = 2
                       group  by a.day_id, a.deliverytype) loop
        begin
          insert into productdeliveryday
            (productlistpercustomer_id, day_id, timestamp, systemuser_id, deliverytype)
          values
            (plpcid, vcursor2.day_id, sysdate, pack_import.lvnsystemuserid, vcursor2.deliverytype);
        exception
          when dup_val_on_index then
            null;
          when others then
            errormsg := 'insert_missing_plpc: Fail to import productdeliveryday. ';
            pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
        end;
      end loop;
    exception
      when dup_val_on_index then
        null;
      when others then
        errormsg := 'insert_missing_plpc: Fail to import productlistpercustomer. ';
        pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
    end;
    -- insert productgrouppercustomer
    for x in (select b.productgroup_id, a.customer_id, max(a.customcode) customcode,
                     max(a.customdescription) customdescription, max(c.customernumber) customernumber,
                     max(b.code) productcode
              from   productlistpercustomer a, product b, customer c
              where  a.product_id = b.product_id
              and    a.customer_id = c.customer_id
              and    c.customer_id = customerid
              and    b.product_id = productid
              and    b.productgroup_id is not null
              and    not exists
               (select productgroup_id, customer_id
                      from   productgrouppercustomer
                      where  productgrouppercustomer.productgroup_id = b.productgroup_id
                      and    productgrouppercustomer.customer_id = a.customer_id)
              group  by b.productgroup_id, a.customer_id) loop
      begin
        insert into productgrouppercustomer
          (productgroup_id, customer_id, invoicegroupingcode, customcode, customdescritpion,
           systemuser_id, timestamp, active)
        values
          (x.productgroup_id, x.customer_id, null, x.customcode, x.customdescription,
           pack_import.lvnsystemuserid, sysdate, 'Y');
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'insert_missing_plpc: Fail to import productgrouppercustomer for customernumber ' ||
                      to_char(x.customernumber) || ' ,productcode:' || x.productcode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
  exception
    when others then
      begin
        errormsg := 'Error import wearer insert_missing_plpc ';
        pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end insert_missing_plpc;
  procedure convert_lockers is
    countrows integer := 0;
    procedure addmissingdelpoints is
      lv_deliverypointid     deliverypoint.deliverypoint_id%type;
      lv_sortdeliverypointid deliverypoint.maincustomerdeliverypoint_id%type;
    begin
      --add missing deliverypoints
      for jj in (select c.customer_id, iw.deliverypointnumber,
                        max(iw.deliverypointdescription) deliverypointdescription
                 from   i_wearer iw
                 join   customer c
                 on     c.customernumber = iw.customernumber
                 where  not exists (select 1
                         from   deliverypoint dp
                         where  dp.customer_id = c.customer_id
                         and    dp.code = iw.deliverypointnumber)
                 group  by c.customer_id, iw.deliverypointnumber
                 union
                 select c.customer_id, il.deliverypointcode,
                        il.deliverypointcode deliverypointdescription
                 from   i_locker il
                 join   customer c
                 on     c.customernumber = il.customernumber
                 where  not exists (select 1
                         from   deliverypoint dp
                         where  dp.customer_id = c.customer_id
                         and    dp.code = il.deliverypointcode)
                 group  by c.customer_id, il.deliverypointcode) loop
        begin
          countrows          := countrows +
                                pack_import_customer.cfbimport_deliverypoint(jj.customer_id);
          lv_deliverypointid := get_deliverypoint(jj.deliverypointnumber,
                                                  jj.deliverypointdescription, jj.customer_id,
                                                  lv_sortdeliverypointid);
        end;
      end loop; --jj
    end addmissingdelpoints;
    --internal create locker procedure
    procedure create_locker(fp_customerid            in customer.customer_id%type,
                            fp_customernumber        in customer.customernumber%type,
                            fp_locker                in locker.locker%type,
                            fp_bank                  in locker.bank%type,
                            fp_lockersortaddress     in locker.sortaddress%type,
                            fp_lockersortgroupnumber in lockersortgroup.lockersortgroupnumber%type,
                            fp_lockersortgroupdescr  in lockersortgroup.description%type,
                            fp_deliverypointid       in deliverypoint.deliverypoint_id%type,
                            fp_remark                in locker.remark%type,
                            fp_lockstatus            in locker.lockerstatus%type,
                            fp_keycombination        in locker.keycombination%type) is
      lv_lockersortgroupid lockersortgroup.lockersortgroup_id%type;
    begin
      lv_lockersortgroupid := get_lockersortgroup(fp_customerid, fp_lockersortgroupnumber,
                                                  fp_lockersortgroupdescr);
      insert into locker
        (locker_id, customer_id, bank, locker, deliverypoint_id, lockerstatus, remark,
         systemuser_id, timestamp, sortaddress, lockersortgroup_id, keycombination)
      values
        (seq_locker.nextval, fp_customerid, fp_bank, fp_locker, fp_deliverypointid,
         nvl(fp_lockstatus, 1), fp_remark, pack_import.lvnsystemuserid, sysdate,
         fp_lockersortaddress, lv_lockersortgroupid, fp_keycombination);
      countrows := countrows + 1;
    exception
      when dup_val_on_index then
        null;
      when others then
        errormsg := 'Convert_Lockers: Fail to import locker/bank ' || fp_locker || '/' ||
                    nvl(fp_bank, 'NULL') || ' customer ' || to_char(fp_customernumber) ||
                    ' deliverypoint id ' || fp_deliverypointid;
        pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
    end create_locker;
  begin
    addmissingdelpoints;
    countrows := 0;
    --ading lockers i-locker
    for r in (select il.*, c.customer_id, dp.deliverypoint_id
              from   i_locker il
              join   customer c
              on     (c.customernumber = il.customernumber)
              join   deliverypoint dp
              on     (dp.customer_id = c.customer_id and dp.code = il.deliverypointcode)
              where  not exists (select 1
                      from   locker l
                      where  l.customer_id = c.customer_id
                      and    l.deliverypoint_id = dp.deliverypoint_id
                      and    (l.bank = il.bank or l.bank is null and il.bank is null)
                      and    l.locker = il.locker)) loop
      begin
        create_locker(r.customer_id, r.customernumber, r.locker, r.bank, r.sortaddress,
                      r.lockersortgroupnumber, r.lockersortgroupdescr, r.deliverypoint_id, r.remark,
                      r.lockerstatus, r.keycombination);
      end;
    end loop; --x
    --adding lockers
    for x in (select trim(a.lockerbank) lockerbank, trim(a.locker) locker, a.customernumber,
                     b.customer_id, a.lockersortaddress, a.deliverypointnumber,
                     a.deliverypointdescription, a.lockersortgroupnumber, a.lockersortgroupdescr,
                     dp.deliverypoint_id, substr(a.remark, 1, 40) remark, a.keycombination
              from   i_wearer a
              join   customer b
              on     (a.customernumber = b.customernumber)
              join   deliverypoint dp
              on     (dp.customer_id = b.customer_id and dp.code = a.deliverypointnumber)
              where  trim(a.locker) is not null
              and    trim(a.externallocker) is null
              and    not exists (select locker
                      from   locker l
                      where  l.locker = trim(a.locker)
                      and    l.customer_id = b.customer_id
                      and    (l.deliverypoint_id = dp.deliverypoint_id)
                      and    ((l.bank is null and (trim(a.lockerbank) is null)) or
                            l.bank = trim(a.lockerbank)))) loop
      begin
        create_locker(x.customer_id, x.customernumber, x.locker, x.lockerbank, x.lockersortaddress,
                      x.lockersortgroupnumber, x.lockersortgroupdescr, x.deliverypoint_id, x.remark,
                      2, x.keycombination);
      end;
    end loop; --x
    --also create the external lockers for the sortcustomer when possible
    for y in (select trim(iw.externallockerbank) lockerbank, trim(iw.externallocker) locker,
                     b.customernumber, b.customer_id maincustomer_id, iw.lockersortaddress,
                     dpx.code deliverypointnumber, dpx.code deliverypointdescription,
                     iw.lockersortgroupnumber, iw.lockersortgroupdescr,
                     dpx.deliverypoint_id maincustomerdeliverypoint_id, dps.deliverypoint_id,
                     s.customer_id, substr(iw.remark, 1, 40) remark, iw.keycombination
              from   i_wearer iw, customer s, customer b, deliverypoint dps, deliverypoint dpx
              where  iw.customernumber = s.customernumber
              and    s.sortcustomer_id = b.customer_id
              and    s.customer_id = dps.customer_id
              and    dps.code = iw.deliverypointnumber
              and    dps.maincustomerdeliverypoint_id = dpx.deliverypoint_id
              and    dpx.customer_id = b.customer_id
              and    trim(iw.externallocker) is not null) loop
      begin
        --create external locker
        create_locker(y.maincustomer_id, y.customernumber, y.locker, y.lockerbank,
                      y.lockersortaddress, y.lockersortgroupnumber, y.lockersortgroupdescr,
                      y.maincustomerdeliverypoint_id, y.remark, 2, y.keycombination);
        --create dummy locker for reporting
        create_locker(y.customer_id, y.customernumber, y.locker, y.lockerbank, y.lockersortaddress,
                      y.lockersortgroupnumber, y.lockersortgroupdescr, y.deliverypoint_id, y.remark,
                      2, y.keycombination);
      end;
    end loop; --y
    commit;
    pack_import.write_log('convert_lockers ' || to_char(countrows) || ' locker rows imported ');
  end convert_lockers;
  procedure cfbinitializewearer is
    countrows            integer;
    deliverypointid      deliverypoint.deliverypoint_id%type;
    ndispensernumber     garmentdispenser.dispensernumber%type;
    lsortdeliverypointid deliverypoint.maincustomerdeliverypoint_id%type;
    lflagid              flag.flag_id%type;
  begin
    -- correct errors in provided data
    update i_wearer w set w.departmentnumber = 1 where w.departmentnumber is null;
    update i_wearer e
    set    e.remark = replace(e.remark, '|', chr(10))
    where  e.remark <> replace(e.remark, '|', chr(10));
    commit;
    -- adding wearerfunctions
    countrows := 0;
    for x in (select a.wearerfunctioncode, a.wearerfunctiondescription, b.customer_id,
                     a.dispensecredit, a.customernumber
              from   i_wearer a, customer b
              where  a.customernumber = b.customernumber
              and    a.wearerfunctioncode is not null
              and    not exists (select code
                      from   wearerfunction
                      where  code = a.wearerfunctioncode
                      and    customer_id = b.customer_id)) loop
      begin
        insert into wearerfunction
          (wearerfunction_id, customer_id, code, description, defaultdispensecredit,
           specialminimumgrade_id, specialmaximumgrade_id, systemuser_id, timestamp)
        values
          (seq_wearerfunction.nextval, x.customer_id, x.wearerfunctioncode,
           nvl(x.wearerfunctiondescription, x.wearerfunctioncode), x.dispensecredit, null, null,
           pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'Wearer cfbinitialize: Fail to import wearerfunctioncode ' ||
                      x.wearerfunctioncode || 'for customer ' || to_char(x.customernumber);
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(to_char(countrows) || ' wearerfunctioncode rows imported ');
    end if;
    --adding flags
    countrows := 0;
    for x in (select flagcode, flagdescription
              from   i_wearer a
              where  a.flagcode is not null
              and    not exists (select code
                      from   flag
                      where  code = a.flagcode
                      and    flagtype = 1)
              group  by flagcode, flagdescription) loop
      begin
        insert into flag
          (flag_id, flagtype, code, priority, color, sound_id, systemuser_id, timestamp, showalways,
           includeincompletnesscheck, exporttogarmentdispenser, useinwebapplication)
        values
          (seq_flag.nextval, 1, x.flagcode, 1, 'FF0000', null, pack_import.lvnsystemuserid, sysdate,
           'N', 'N', 'N', 'N')
        returning flag_id into lflagid;
        insert into flag_desc
          (flag_id, language_id, description, systemuser_id, timestamp)
        values
          (lflagid, pack_import.lvnlanguageid, x.flagdescription, pack_import.lvnsystemuserid,
           sysdate);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'Wearer cfbinitialize: Fail to import flagcode ' || x.flagcode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(to_char(countrows) || ' flag(s) imported ');
    end if;
    --add locker
    convert_lockers;
    --adding garmentdispensers
    countrows := 0;
    for x in (select b.customer_id, max(a.customernumber) customernumber, a.deliverypointnumber,
                     max(a.deliverypointdescription) deliverypointdescription, a.garmentdispensercode,
                     max(a.garmentdispenserdesc) garmentdispenserdesc
              from   i_wearer a, customer b
              where  a.customernumber = b.customernumber
              and    a.garmentdispensercode is not null
              group  by b.customer_id, a.deliverypointnumber, a.garmentdispensercode) loop
      begin
        deliverypointid := get_deliverypoint(to_char(x.deliverypointnumber),
                                             x.deliverypointdescription, x.customer_id,
                                             lsortdeliverypointid);
        select nvl(max(g.dispensernumber), 0) + 1
        into   ndispensernumber
        from   garmentdispenser g
        where  g.customer_id = x.customer_id;
        insert into garmentdispenser
          (code, description, systemuser_id, timestamp, garmentdispenser_id, customer_id,
           sortaddress2, sortaddress1, deliverypoint_id, dispensernumber, interfacetype)
        values
          (x.garmentdispensercode, x.garmentdispenserdesc, pack_import.lvnsystemuserid, sysdate,
           seq_garmentdispenser.nextval, x.customer_id, null, null, deliverypointid,
           ndispensernumber, 0);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'Wearer cfbinitialize: Fail to import garmentdispenser' ||
                      to_char(x.garmentdispensercode) || ' for customer ' ||
                      to_char(x.customernumber);
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(to_char(countrows) || ' garmentdispensers rows imported ');
    end if;
  exception
    when others then
      begin
        errormsg := 'Error cfbinitializewearer ' || errormsg;
        pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbinitializewearer;
  procedure cfbintializeinventory is
    countrows             integer;
    countrows1            integer;
    sizestarid            sizedefinition.sizedefinition_id%type;
    sizetypeid            sizetype.sizetype_id%type;
    sizeid                sizedefinition.sizedefinition_id%type;
    residualvalueschemeid residualvaluescheme.residualvaluescheme_id%type;
    fpnmodification_id    modification.modification_id%type;
  begin
    --sizedefinition
    begin
      select sizedefinition_id into sizestarid from sizedefinition where code = '*';
    exception
      when no_data_found then
        begin
          pack_import.cfbcreate_sizedefinition(sizestarid, '*', 'N', null, null, null, 'N');
          pack_import.cfbcreate_sizedefinition_desc(sizestarid, 'All sizes');
        end;
      when dup_val_on_index then
        null;
    end;
    countrows := 0;
    for x in (select distinct trim(sizecode) sizecode, trim(sizedescription) sizedescription
              from   i_wearerinventory
              where  trim(sizecode) is not null
              and    not exists (select code from sizedefinition where code = trim(sizecode))) loop
      begin
        pack_import.cfbcreate_sizedefinition(sizeid, x.sizecode, 'N', null, null, null, 'N');
        pack_import.cfbcreate_sizedefinition_desc(sizeid, nvl(x.sizedescription, x.sizecode));
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'cfbintializeinventory: Fail to import sizecode/sizedescription ' ||
                      x.sizecode || '/' || x.sizedescription;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(countrows || ' size rows imported.');
    end if;
    -- sizes per size type, product size
    countrows  := 0;
    countrows1 := 0;
    for x in (select b.product_id, b.sizetype_id, b.typeofmerchandise, b.packingamount,
                     b.theoreticalweight, c.sizedefinition_id, a.sizecode, a.productcode
              from   i_wearerinventory a, product b, sizedefinition c
              where  trim(a.productcode) = b.code
              and    trim(a.sizecode) = c.code) loop
      sizetypeid := x.sizetype_id;
      -- sizespersizetype
      begin
        select sizedefinition_id
        into   sizeid
        from   sizespersizetype
        where  sizetype_id = sizetypeid
        and    sizedefinition_id = x.sizedefinition_id;
      exception
        when no_data_found then
          begin
            insert into sizespersizetype
              (sizetype_id, sizedefinition_id, sequencenumber, systemuser_id, timestamp)
              select sizetypeid, x.sizedefinition_id, nvl(max(sequencenumber), 0) + 1,
                     pack_import.lvnsystemuserid, sysdate
              from   sizespersizetype
              where  sizetype_id = sizetypeid;
            countrows1 := countrows1 + 1;
          exception
            when others then
              errormsg := 'cfbintializeinventory: Fail to import sizes per size type for sizedefinition ' ||
                          x.sizecode;
              pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
          end;
        when others then
          errormsg := 'cfbintializeinventory: Fail to get sizes per size type for sizedefinition ' ||
                      x.sizecode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
      -- product size
      begin
        select sizedefinition_id
        into   sizeid
        from   productsize
        where  product_id = x.product_id
        and    sizedefinition_id = x.sizedefinition_id;
      exception
        when dup_val_on_index then
          null;
        when no_data_found then
          begin
            pack_import.cfbcreate_productsize(x.product_id, x.sizedefinition_id, 'N',
                                              x.packingamount, x.theoreticalweight, null);
            countrows := countrows + 1;
          exception
            when others then
              errormsg := 'cfbintializeinventory: Fail to import product size for product/sizedefinition ' ||
                          x.productcode || '/' || x.sizecode;
              pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
          end;
        when others then
          errormsg := 'cfbintializeinventory: Fail to get product size for product/sizedefinition ' ||
                      x.productcode || '/' || x.sizecode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(to_char(countrows) || ' product size rows imported.');
    end if;
    if countrows1 > 0 then
      pack_import.write_log(to_char(countrows1) || ' sizespersizetype rows imported.');
    end if;
    -- finishing method
    countrows := 0;
    for x in (select distinct finishingmethodcode, finishingmethoddescription
              from   i_wearerinventory
              where  not exists (select code from finishingmethod where code = finishingmethodcode)) loop
      begin
        insert into finishingmethod
          (finishingmethod_id, code, active, systemuser_id, timestamp)
        values
          (seq_finishingmethod.nextval, x.finishingmethodcode, 'Y', pack_import.lvnsystemuserid,
           sysdate);
        insert into finishingmethod_desc
          (finishingmethod_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_finishingmethod.currval, pack_import.lvnlanguageid, x.finishingmethoddescription,
           pack_import.lvnsystemuserid, sysdate);
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'cfbintializeinventory: Fail to import finishing method code/description ' ||
                      x.finishingmethodcode || '/' || x.finishingmethoddescription;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    commit;
    if countrows > 0 then
      pack_import.write_log(to_char(countrows) || ' finishing method rows imported.');
    end if;
    --modification1,2 and 3
    countrows := 0;
    for x in (select modificationcode, pvd.modificationdescription
              from   (select distinct modificationcode1 modificationcode,
                                       nvl(modificationdescription1, modificationcode1) modificationdescription
                       from   i_wearerinventory a
                       where  modificationcode1 is not null
                       and    not exists
                        (select code from modification where code = a.modificationcode1)
                       union
                       select distinct modificationcode2 modificationcode,
                                       nvl(modificationdescription2, modificationcode2) modificationdescription
                       from   i_wearerinventory a
                       where  modificationcode2 is not null
                       and    not exists
                        (select code from modification where code = a.modificationcode2)
                       union
                       select distinct modificationcode3 modificationcode,
                                       nvl(modificationdescription3, modificationcode3) modificationdescription
                       from   i_wearerinventory a
                       where  modificationcode3 is not null
                       and    not exists
                        (select code from modification where code = a.modificationcode3)) pvd) loop
      begin
        pack_import.cfbcreate_modification(fpnmodification_id, x.modificationcode, 'N', null, 'N');
        pack_import.cfbcreate_modification_desc(fpnmodification_id,
                                                nvl(x.modificationdescription, x.modificationcode));
        countrows := countrows + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          errormsg := 'cfbintializeinventory: Fail to insert modificationcode1' ||
                      x.modificationcode;
          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
      end;
    end loop;
    if countrows > 0 then
      begin
        commit;
        pack_import.write_log(to_char(countrows) || ' modification rows imported ');
        begin
          --insert into modificationspergroup
          insert into modificationspergroup
            (modificationgroup_id, modification_id, sequencenumber, timestamp, systemuser_id)
            select g.modificationgroup_id, mo.modification_id,
                   nvl((select max(x.sequencenumber)
                        from   modificationspergroup x
                        where  x.modificationgroup_id = g.modificationgroup_id), 0) + rownum,
                   sysdate, pack_import.lvnsystemuserid
            from   modification mo, modificationgroup g,
                   (select iw.modificationcode1 modificationcode
                     from   i_wearerinventory iw
                     where  iw.modificationcode1 is not null
                     union
                     select iw.modificationcode2 modificationcode
                     from   i_wearerinventory iw
                     where  iw.modificationcode2 is not null
                     union
                     select iw.modificationcode3 modificationcode
                     from   i_wearerinventory iw
                     where  iw.modificationcode3 is not null) ix
            where  g.code = '-'
            and    ix.modificationcode = mo.code
            and    not exists (select 1
                    from   modificationspergroup x
                    where  x.modificationgroup_id = g.modificationgroup_id
                    and    x.modification_id = mo.modification_id);
          countrows := sql%rowcount;
          --write log if needed
          if countrows > 0 then
            begin
              pack_import.write_log(countrows || ' modificationspergroup(s) added', 1);
            end;
          end if;
          commit;
        exception
          when others then
            begin
              pack_import.write_log('WI Faileded to insert intoFail to insert modificationspergroup ' ||
                                    substr(sqlerrm, 1, 512), -3);
            end;
        end;
        begin
          --insert into productmodificationgroup
          insert into productmodificationgroup
            (product_id, modificationgroup_id, sequencenumber, systemuser_id, timestamp)
            select pmg.product_id, pmg.modificationgroup_id, pmg.seq, pack_import.lvnsystemuserid,
                   sysdate
            from   (select pm.product_id, mpg.modificationgroup_id, max(mpg.sequencenumber) seq
                     from   (select p.product_id, md.modification_id
                              from   (select wi.productcode, wi.modificationcode1
                                       from   i_wearerinventory wi
                                       where  wi.modificationcode1 is not null
                                       group  by wi.productcode, wi.modificationcode1
                                       union
                                       select wi.productcode, wi.modificationcode2
                                       from   i_wearerinventory wi
                                       where  wi.modificationcode2 is not null
                                       group  by wi.productcode, wi.modificationcode2
                                       union
                                       select wi.productcode, wi.modificationcode3
                                       from   i_wearerinventory wi
                                       where  wi.modificationcode3 is not null
                                       group  by wi.productcode, wi.modificationcode3) mp
                              join   product p
                              on     p.code = mp.productcode
                              join   modification md
                              on     md.code = mp.modificationcode1
                              group  by p.product_id, md.modification_id) pm
                     join   modificationspergroup mpg
                     on     mpg.modification_id = pm.modification_id
                     group  by mpg.modificationgroup_id, pm.product_id) pmg
            where  not exists (select 1
                    from   productmodificationgroup pmhx
                    where  pmhx.product_id = pmg.product_id
                    and    pmhx.modificationgroup_id = pmg.modificationgroup_id);
          countrows := sql%rowcount;
          --write log if needed
          if countrows > 0 then
            begin
              pack_import.write_log(countrows || ' productmodificationgroup(s) added', 1);
            end;
          end if;
          commit;
        exception
          when others then
            begin
              pack_import.write_log('WI Failed to insert into productmodificationgroup ' ||
                                    substr(sqlerrm, 1, 512), -3);
            end;
        end;
      end;
    end if;
    ---residualvaluescheme '-'
    begin
      select residualvaluescheme_id
      into   residualvalueschemeid
      from   residualvaluescheme
      where  code = '-';
    exception
      when no_data_found then
        insert into residualvaluescheme
          (residualvaluescheme_id, code, calculationweeks, systemuser_id, timestamp,
           calculationbasis)
        values
          (seq_residualvaluescheme.nextval, '-', 0, pack_import.lvnsystemuserid, sysdate, 1)
        returning residualvaluescheme_id into residualvalueschemeid;
        insert into residualvaluescheme_desc
          (residualvaluescheme_id, language_id, description, systemuser_id, timestamp)
        values
          (seq_residualvaluescheme.currval, pack_import.lvnlanguageid, '-',
           pack_import.lvnsystemuserid, sysdate);
    end;
    commit;
    --
    insert into emblemtemplate
      (emblemtemplate_id, customer_id, code, description, systemuser_id, timestamp, printnamelabel,
       active, rentemblem, embroidery)
      select seq_emblemtemplate.nextval, x.customer_id, x.emblemtemplate, x.emblemtemplate,
             pack_import.lvnsystemuserid, sysdate, 'N', 'Y', 'N', 'N'
      from   (select c.customer_id, trim(upper(wi.emblemtemplate)) emblemtemplate
               from   i_wearerinventory wi
               join   customer c
               on     c.customernumber = wi.customernumber
               where  wi.emblemtemplate is not null
               and    not exists (select 1
                       from   emblemtemplate et
                       where  et.customer_id = c.customer_id
                       and    et.code = wi.emblemtemplate)
               group  by c.customer_id, trim(upper(wi.emblemtemplate))) x;
    countrows := sql%rowcount;
    commit;
    if countrows > 0 then
      begin
        pack_import.write_log(countrows || ' emblemtemplate(s) added', 1);
      end;
    end if;
  exception
    when others then
      begin
        errormsg := 'Error cfbintializeinventory ';
        pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbintializeinventory;
  procedure cfbimportwearer is
    type xtab is table of i_wearer%rowtype;
    x                       xtab;
    countrows               integer := 0;
    countwearers            integer := 0;
    ocountwearers           integer := 0;
    data_exists             boolean := true;
    import_allowed          boolean := true;
    flagid                  flag.flag_id%type := 0;
    flagstartdate           wearer.flagstartdate%type;
    employmentflagid        weareremployment.flag_id%type;
    employmentflagstartdate weareremployment.flagstartdate%type;
    lockerid                locker.locker_id%type;
    lv_externallockerid     locker.locker_id%type;
    customerid              customer.customer_id%type := 0;
    lv_sortcustomerid       customer.customer_id%type := 0;
    departmentid            department.department_id%type := 0;
    deliverypointid         deliverypoint.deliverypoint_id%type := 0;
    lv_sortdeliverypointid  deliverypoint.deliverypoint_id%type := 0;
    distributionpointid     distributionpoint.distributionpoint_id%type := 0;
    costcenterid            costcenter.costcenter_id%type := 0;
    wearerid                wearer.wearer_id%type := 0;
    wearerfunctionid        wearerfunction.wearerfunction_id%type := 0;
    garmentdispenserid      garmentdispenser.garmentdispenser_id%type;
    last_customer           number := 0;
    last_wearer             number := 0;
    last_employment         number := 0;
    fpnstandarddelivery_id  standarddelivery.standarddelivery_id%type;
    cursor c1(pcustomer number, pwearer number, pemployment number) is
      select *
      from   i_wearer i
      where  to_char(i.customernumber) || lpad(i.wearernumber, 12, '0') ||
             to_char(i.weareremploymentnumber) >
             to_char(pcustomer) || lpad(pwearer, 12, '0') || to_char(pemployment)
      and    not exists (select w.wearer_id
              from   wearer w, weareremployment e, customer c
              where  w.customer_id = c.customer_id
              and    c.customernumber = i.customernumber
              and    w.wearernumber = i.wearernumber
              and    e.wearer_id = w.wearer_id
              and    e.sequencenumber = i.weareremploymentnumber)
      order  by to_char(i.customernumber) || lpad(i.wearernumber, 12, '0') ||
                 to_char(i.weareremploymentnumber);
  begin
    -- initialize data
    select count(*) into ocountwearers from wearer;
    cfbinitializewearer;
    -- loop to insert wearers
    while data_exists loop
      -- Loop needed to flush rollback space.
      -- Started to fill the cursor with the right start id.
      open c1(last_customer, last_wearer, last_employment);
      fetch c1 bulk collect
        into x limit 1500;
      for i in 1 .. x.count loop
        begin
          import_allowed  := true;
          last_customer   := x(i).customernumber;
          last_wearer     := x(i).wearernumber; -- for the loop.
          last_employment := x(i).weareremploymentnumber;
          -- check provided data
          begin
            --customer
            errormsg := 'NO_DATA customer: ' || to_char(x(i).customernumber);
            select c.customer_id, c.sortcustomer_id
            into   customerid, lv_sortcustomerid
            from   customer c
            where  c.customernumber = x(i).customernumber;
            --department
            errormsg := 'NO_DATA department: ' || to_char(x(i).departmentnumber) ||
                        ' for customer: ' || to_char(x(i).customernumber);
            select d.department_id
            into   departmentid
            from   department d
            where  d.customer_id = customerid
            and    d.departmentnumber = nvl(x(i).departmentnumber, 1);
          exception
            when no_data_found then
              pack_import.write_log(errormsg, -3);
              import_allowed := false;
              customerid     := null;
              departmentid   := null;
          end;
          if import_allowed then
            begin
              -- import a wearer
              begin
                --wearerfunction
                select wearerfunction_id
                into   wearerfunctionid
                from   wearerfunction
                where  x(i).wearerfunctioncode = code
                 and    customer_id = customerid;
              exception
                when no_data_found then
                  wearerfunctionid := null;
              end;
              -- deliverypoint
              deliverypointid := get_deliverypoint(to_char(x(i).deliverypointnumber),
                                                   x(i).deliverypointdescription, customerid,
                                                   lv_sortdeliverypointid);
              -- get flagid
              if x(i).flagcode is not null then
                begin
                  flagid := import_flag(x(i).flagcode, x(i).flagdescription);
                  if flagid is not null then
                    flagstartdate := nvl(x(i).dateactive, sysdate);
                  else
                    flagstartdate := null;
                  end if;
                end;
              else
                begin
                  flagid        := null;
                  flagstartdate := null;
                end;
              end if;
              begin
                --wearer
                insert into wearer
                  (wearer_id, customer_id, wearernumber, fullname, searchname, emblemname,
                   customeremployeenumber, sex, dummyforpool, dateactive, dateinactive, remark,
                   flag_id, flagstartdate, systemuser_id, timestamp, firstname, emblemnameline2,
                   installdate, creationdate)
                values
                  (seq_wearer.nextval, customerid, x(i).wearernumber, x(i).fullname,
                   x(i).searchname, x(i).emblemname, x(i).customeremployeenumber, x(i).sex,
                   x(i).dummyforpool, x(i).dateactive, x(i).dateinactive, x(i).remark, flagid,
                   flagstartdate, pack_import.lvnsystemuserid, sysdate, x(i).firstname,
                   x(i).emblemnameline2, x(i).dateactive, x(i).dateactive)
                returning wearer_id into wearerid;
              exception
                when dup_val_on_index then
                  select w.wearer_id
                  into   wearerid
                  from   wearer w
                  where  w.wearernumber = x(i).wearernumber
                  and    w.customer_id = customerid;
              end;
              begin
                -- distributionpoint
                select min(dp.distributionpoint_id)
                into   distributionpointid
                from   distributionpoint dp
                where  dp.department_id = departmentid
                and    dp.deliverypoint_id = deliverypointid
                and    (dp.distributionpointnumber = x(i).consumptionpointnumber or x(i).consumptionpointnumber is null);
                if distributionpointid is null then
                  begin
                    select min(dp.distributionpoint_id)
                    into   distributionpointid
                    from   distributionpoint dp
                    where  dp.department_id = departmentid
                    and    (dp.distributionpointnumber = x(i).consumptionpointnumber or x(i).consumptionpointnumber is null);
                    if distributionpointid is not null then
                      begin
                        update distributionpoint t
                        set    t.deliverypoint_id = deliverypointid
                        where  t.distributionpoint_id = distributionpointid;
                      end;
                    else
                      begin
                        select min(costcenter.costcenter_id)
                        into   costcenterid
                        from   costcenter
                        where  costcenter.customer_id = customerid;
                        if costcenterid is null then
                          begin
                            pack_import.cfbcreate_costcenter(costcenterid, '-', '-', customerid,
                                                             null, null);
                          end;
                        end if;
                        pack_import.cfbcreate_distributionpoint(distributionpointid,
                                                                --fpndistributionpoint_id,
                                                                1,
                                                                --fpndistributionpointnumber,
                                                                '-',
                                                                --fpsdescription,
                                                                '',
                                                                --fpsremarkonpackingnote,
                                                                '',
                                                                --fpsremarkondeliverynote,
                                                                to_date('31-12-2099', 'DD-MM-YYYY'),
                                                                --fpdtpackremarkenddate,
                                                                to_date('31-12-2099', 'DD-MM-YYYY'),
                                                                --fpdtdeliverremarkenddate,
                                                                'Y',
                                                                --fpsactive,
                                                                departmentid,
                                                                --fpndepartment_id,
                                                                deliverypointid,
                                                                --fpndeliverypoint_id,
                                                                costcenterid,
                                                                --fpncostcenter_id,
                                                                null,
                                                                --fpslegacydistributionpnumber,
                                                                null, null);
                        -- every distributionpoint needs standarddelivery
                        pack_import.cfbcreate_standarddelivery(fpnstandarddelivery_id, 1, 'N', null,
                                                               'N', fpntransportarticle_id, 'N', 1,
                                                               distributionpointid, null, 'N', 'N',
                                                               null);
                      exception
                        when others then
                          pack_import.write_log('cfbimportwearer, error adding distributionpoint/standardelivery ' ||
                                                substr(sqlerrm, 1, 512), -3);
                      end;
                    end if;
                  end;
                end if; ---if distributionpointid is null then
              end;
              begin
                --locker
                if trim(x(i).locker) is not null and trim(x(i).lockerbank) is null then
                  select locker_id
                  into   lockerid
                  from   locker l
                  where  l.customer_id = customerid
                  and    l.locker = trim(x(i).locker)
                  and    l.bank is null
                  and    l.deliverypoint_id = deliverypointid;
                else
                  if trim(x(i).locker) is not null and trim(x(i).lockerbank) is not null then
                    select locker_id
                    into   lockerid
                    from   locker l
                    where  l.customer_id = customerid
                    and    l.locker = trim(x(i).locker)
                    and    l.bank = trim(x(i).lockerbank)
                    and    l.deliverypoint_id = deliverypointid;
                  else
                    lockerid := null;
                  end if;
                end if;
                --update locker - set status = 2 ocuppied
                if lockerid is not null then
                  update locker set lockerstatus = 2 where locker_id = lockerid;
                end if;
                -- it is allowed to link the same locker more often!
              exception
                when others then
                  lockerid := null;
                  errormsg := 'CFbImportWearer: Fail to load locker ' || to_char(x(i).locker) ||
                              ' for wearer ' || to_char(x(i).wearernumber) || ' customer ' ||
                              to_char(x(i).customernumber) || ' deliverypoint id ' ||
                              to_char(deliverypointid);
                  pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
              end;
              begin
                --externallocker
                if (trim(x(i).externallocker) is not null and trim(x(i).externallockerbank) is null) then
                  begin
                    errormsg := 'CFbImportWearer: External locker; no data found, for locker ' ||
                                to_char(x(i).externallocker) || ' bank is null for wearer ' ||
                                to_char(x(i).wearernumber) || ' the sort customer of customer ' ||
                                to_char(x(i).customernumber) || ' deliverypoint id ' ||
                                to_char(lv_sortdeliverypointid);
                    select locker_id
                    into   lv_externallockerid
                    from   locker l
                    where  l.customer_id = lv_sortcustomerid
                    and    l.locker = trim(x(i).externallocker)
                    and    l.bank is null
                    and    l.deliverypoint_id = lv_sortdeliverypointid;
                    --select dummy locker for reporting as well
                    errormsg := 'CFbImportWearer: External locker; no data found, for (dummy) locker ' ||
                                to_char(x(i).externallocker) || ' bank is null for wearer ' ||
                                to_char(x(i).wearernumber) || ' the sort customer of customer ' ||
                                to_char(x(i).customernumber) || ' deliverypoint id ' ||
                                to_char(deliverypointid);
                    select locker_id
                    into   lockerid
                    from   locker l
                    where  l.customer_id = customerid
                    and    l.locker = trim(x(i).externallocker)
                    and    l.bank is null
                    and    l.deliverypoint_id = deliverypointid;
                  exception
                    when no_data_found then
                      begin
                        pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                      end;
                  end;
                else
                  if (trim(x(i).externallocker) is not null and
                     trim(x(i).externallockerbank) is not null) then
                    begin
                      errormsg := 'CFbImportWearer:  External locker; no data found, for locker ' ||
                                  to_char(x(i).externallocker) || ' bank ' || x(i).externallockerbank ||
                                  ' for wearer ' || to_char(x(i).wearernumber) ||
                                  ' the sort customer of customer ' || to_char(x(i).customernumber) ||
                                  ' deliverypoint_id ' || to_char(lv_sortdeliverypointid);
                      select locker_id
                      into   lv_externallockerid
                      from   locker l
                      where  l.customer_id = lv_sortcustomerid
                      and    l.locker = trim(x(i).externallocker)
                      and    l.bank = trim(x(i).externallockerbank)
                      and    l.deliverypoint_id = lv_sortdeliverypointid;
                      --select dummy locker as well
                      errormsg := 'CFbImportWearer: External locker; no data found, for (dummy) locker ' ||
                                  to_char(x(i).externallocker) || ' bank ' || x(i).externallockerbank ||
                                  ' for wearer ' || to_char(x(i).wearernumber) ||
                                  ' the sort customer of customer ' || to_char(x(i).customernumber) ||
                                  ' deliverypoint_id ' || to_char(deliverypointid);
                      select locker_id
                      into   lockerid
                      from   locker l
                      where  l.customer_id = customerid
                      and    l.locker = trim(x(i).externallocker)
                      and    l.bank = trim(x(i).externallockerbank)
                      and    l.deliverypoint_id = deliverypointid;
                    exception
                      when no_data_found then
                        begin
                          lv_externallockerid := null;
                          pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                        end;
                    end;
                  else
                    lv_externallockerid := null;
                  end if;
                end if;
                --update externallocker - set status = 2 ocuppied
                if lv_externallockerid is not null then
                  update locker set lockerstatus = 2 where locker_id = lv_externallockerid;
                end if;
                -- it is allowed to link the same externallocker more often!
              exception
                when others then
                  begin
                    lv_externallockerid := null;
                    errormsg            := 'CFbImportWearer: Fail to load externallocker ' ||
                                           to_char(x(i).externallocker) || ' for wearer ' ||
                                           to_char(x(i).wearernumber) ||
                                           ' the sort customer of customer ' ||
                                           to_char(x(i).customernumber) || ' deliverypoint_id ' ||
                                           to_char(lv_sortdeliverypointid);
                    pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                  end;
              end;
              --update locker - set status = 2 ocuppied
              if lockerid is not null then
                update locker set lockerstatus = 2 where locker_id = lockerid;
              end if;
              begin
                -- get employmentflagid
                if x(i).employmentflagcode is not null then
                  begin
                    employmentflagid := import_flag(x(i).employmentflagcode,
                                                    x(i).employmentflagdescription);
                    if flagid is not null then
                      employmentflagstartdate := nvl(x(i).dateactive, sysdate);
                    else
                      employmentflagstartdate := null;
                    end if;
                  end;
                else
                  begin
                    employmentflagid        := null;
                    employmentflagstartdate := null;
                  end;
                end if;
                --garmentdispenser
                select min(g.garmentdispenser_id)
                into   garmentdispenserid
                from   garmentdispenser g
                where  g.code = x(i).garmentdispensercode
                and    g.customer_id = customerid;
                --weareremployment
                if lockerid is not null or garmentdispenserid is not null then
                  deliverypointid := null;
                end if;
                insert into weareremployment
                  (weareremployment_id, wearer_id, sequencenumber, distributionpoint_id,
                   wearerfunction_id, flag_id, deliverypoint_id, locker_id, garmentdispenser_id,
                   dispensecredit, systemuser_id, timestamp, flagstartdate, embroideryletteringline1,
                   embroideryletteringline2, embroideryletteringline3, externallocker_id)
                values
                  (seq_weareremployment.nextval, wearerid, x(i).weareremploymentnumber,
                   distributionpointid, wearerfunctionid, employmentflagid, deliverypointid,
                   lockerid, garmentdispenserid, x(i).dispensecredit, pack_import.lvnsystemuserid,
                   sysdate, employmentflagstartdate, x(i).embroideryletteringline1,
                   x(i).embroideryletteringline2, x(i).embroideryletteringline3, lv_externallockerid);
                --weareremployment_link
                insert into weareremployment_link
                  (weareremployment_link_id, weareremployment_id, distributionpoint_link_id,
                   wearersearchname, wearername, wearernumber, systemuser_id, timestamp,
                   sequencenumber)
                values
                  (seq_weareremployment.currval, seq_weareremployment.currval, distributionpointid,
                   x(i).searchname, x(i).fullname, x(i).wearernumber, pack_import.lvnsystemuserid,
                   sysdate, 1);
                --weareempprice
                if x(i).wearerprice = 'Y' then
                  insert into wearerempprice
                    (wearerempprice_id, weareremployment_id, startdate, price, systemuser_id,
                     timestamp)
                  values
                    (seq_wearerempprice.nextval, seq_weareremployment.currval,
                     nvl(x(i).pricestartdate, sysdate), nvl(x(i).price, 0),
                     pack_import.lvnsystemuserid, sysdate);
                end if;
              end;
              countrows := countrows + 1;
            end; -- import a wearer
            commit;
          end if; --import_allowed
        end;
      end loop;
      if c1%notfound then
        data_exists := false;
      end if;
      close c1;
      commit; -- commit after closing cursor releases rollback space.
    end loop;
    commit;
    -- count i-wearers
    select count(*) into countwearers from i_wearer;
    if countwearers > 0 then
      begin
        pack_import.write_log(to_char(ocountwearers) || ' already existed in wearers.');
        pack_import.write_log(to_char(countwearers) || ' wearers records in i-table.');
        pack_import.write_log(to_char(countrows) || ' wearers imported this run.');
        select count(*) into countwearers from wearer;
        pack_import.write_log(to_char(countwearers) || ' now in wearer.');
      end;
    end if;
    begin
      -- Update customer lockermanagement.
      update customer x
      set    x.lockermanagement = 'N'
      where  x.lockermanagement <> 'N'
      and    exists (select y.locker_id from locker y where y.customer_id = x.customer_id)
      and    (select max(count(*))
              from   locker l, weareremployment e
              where  l.locker_id = e.locker_id
              and    l.customer_id = x.customer_id
              group  by e.wearer_id, l.locker, l.bank) > 1
      and    exists
       (select i.customernumber from i_wearer i where i.customernumber = x.customernumber);
      commit;
      update customer c
      set    c.usesgarmentdispenser = 'Y', c.lockermanagement = 'N'
      where  exists (select g.garmentdispenser_id
              from   garmentdispenser g
              where  g.customer_id = c.customer_id)
      and    exists
       (select i.customernumber from i_wearer i where i.customernumber = c.customernumber);
      --delete possible existing  CustomerLockerManagement records that should not be there
      delete from customerlockermanagement clm
      where  exists (select 1
              from   customer c
              where  c.customer_id = clm.customer_id
              and    c.lockermanagement = 'N')
      and    exists (select i.customernumber
              from   i_wearer i
              join   customer c
              on     c.customernumber = i.customernumber
              where  c.customer_id = clm.customer_id);
      commit;
      pack_import.write_log('    Update locker/garmentdispenser management successfull.');
    exception
      when others then
        pack_import.write_log('cfbimportwearer, error update locker management: ' ||
                              substr(sqlerrm, 1, 512), 3);
    end;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimportwearer;
  procedure cfbimportwearerinventory is
    type xtab is table of i_wearerinventory%rowtype;
    x                          xtab;
    z                          integer;
    countrows                  integer := 0;
    countwearerinv             integer := 0;
    ocountwearerinv            integer := 0;
    countrowsnonu              integer := 0;
    countplpc                  integer := 0;
    circinventory              integer := 0;
    import_allowed             boolean := true;
    data_exists                boolean := true;
    customerid                 customer.customer_id%type := 0;
    wearerid                   wearer.wearer_id%type;
    wdateactive                wearer.dateactive%type;
    wdateinactive              wearer.dateinactive%type;
    weareremploymentid         weareremployment.weareremployment_id%type;
    wdummyforpool              wearer.dummyforpool%type;
    productid                  product.product_id%type;
    sizedefinitionid           sizedefinition.sizedefinition_id%type;
    finishingmethodid          finishingmethod.finishingmethod_id%type;
    qualitygradeid             qualitygrade.qualitygrade_id%type;
    modification1id            modification.modification_id%type;
    modification2id            modification.modification_id%type;
    modification3id            modification.modification_id%type;
    plpcid                     productlistpercustomer.productlistpercustomer_id%type;
    reasoncodeid               reasoncode.reasoncode_id%type;
    last_customer              number := 0;
    last_wearer                number := 0;
    last_weareremployment      number := 0;
    last_productcode           varchar2(12) := ' ';
    last_sizecode              varchar2(12) := ' ';
    last_finishingmethodcode   varchar2(6) := ' ';
    lvnemblemtemplateid        emblemtemplate.emblemtemplate_id%type;
    lvnwearerinventoryid       wearerinventory.wearerinventory_id%type;
    lvnwearerinvoicecategoryid wearerinvoicecategory.wearerinvoicecategory_id%type;
    cursor c1(pcustomer            number,
              pwearer              number,
              pweareremployment    number,
              pproductcode         varchar2,
              psizecode            varchar2,
              pfinishingmethodcode varchar2) is
      select i.*
      from   i_wearerinventory i
      where  (lpad(to_char(i.customernumber), 12, '0') || lpad(i.wearernumber, 12, '0') ||
             to_char(i.weareremploymentnumber) || lpad(i.productcode, 12, '0') ||
             lpad(i.sizecode, 12, '0') || lpad(i.finishingmethodcode, 6, '0')) >=
             (lpad(to_char(pcustomer), 12, '0') || lpad(pwearer, 12, '0') ||
             to_char(pweareremployment) || lpad(pproductcode, 12, '0') || lpad(psizecode, 12, '0') ||
             lpad(pfinishingmethodcode, 6, '0'))
      and    not exists (select v.wearerinventory_id
              from   wearerinventory v, wearer w, customer c, product p,
                     sizedefinition s, finishingmethod f, weareremployment e
              where  i.wearernumber = w.wearernumber
              and    i.weareremploymentnumber = e.sequencenumber
              and    i.customernumber = c.customernumber
              and    i.productcode = p.code
              and    i.sizecode = s.code
              and    i.finishingmethodcode = f.code
              and    v.weareremployment_id = e.weareremployment_id
              and    e.wearer_id = w.wearer_id
              and    w.customer_id = c.customer_id
              and    v.product_id = p.product_id
              and    v.sizedefinition_id = s.sizedefinition_id
              and    v.finishingmethod_id = f.finishingmethod_id)
      order  by (lpad(to_char(i.customernumber), 12, '0') || lpad(i.wearernumber, 12, '0') ||
                 to_char(i.weareremploymentnumber) || lpad(i.productcode, 12, '0') ||
                 lpad(i.sizecode, 12, '0') || lpad(i.finishingmethodcode, 6, '0'));
    procedure get_create_wearerinvcategory(fp_code               in wearerinvoicecategory.code%type,
                                           fp_description        in wearerinvoicecategory.description%type,
                                           fp_employerpercentage in wearerinvoicecategory.employerpercentage%type,
                                           fp_maxemployeramount  in wearerinvoicecategory.maxemployeramount%type) is
      lvncounter number;
    begin
      --get_create_wearerinvcategory
      errormsg := 'get_create_wearerinvcategory';
      if fp_code is null then
        lvnwearerinvoicecategoryid := null;
      else
        begin
          select wic.wearerinvoicecategory_id
          into   lvnwearerinvoicecategoryid
          from   wearerinvoicecategory wic
          where  wic.customer_id = customerid
          and    wic.code = fp_code;
        exception
          when no_data_found then
            begin
              insert into wearerinvoicecategory
                (wearerinvoicecategory_id, customer_id, code, description, employerpercentage,
                 maxemployeramount, systemuser_id, timestamp)
              values
                (seq_wearerinvoicecategory.nextval, customerid, fp_code,
                 coalesce(fp_description, fp_code, '-'), nvl(fp_employerpercentage, 0),
                 nvl(fp_maxemployeramount, 0), pack_import.lvnsystemuserid, sysdate)
              returning wearerinvoicecategory_id into lvnwearerinvoicecategoryid;
            end;
        end;
        begin
          select count(1)
          into   lvncounter
          from   wearerinvoicecategoryproduct wicp
          where  wicp.wearerinvoicecategory_id = lvnwearerinvoicecategoryid
          and    wicp.product_id = productid;
          if lvncounter = 0 then
            begin
              insert into wearerinvoicecategoryproduct
                (wearerinvoicecategory_id, product_id, systemuser_id, timestamp)
              values
                (lvnwearerinvoicecategoryid, productid, pack_import.lvnsystemuserid, sysdate);
            end;
          end if;
        end;
      end if;
    end get_create_wearerinvcategory;
  begin
    -- initialize data
    cfbintializeinventory;
    select min(reasoncode_id) into reasoncodeid from reasoncode;
    --count existing wearer inventory records
    select count(*) into ocountwearerinv from wearerinventory;
    -- loop to insert wearers
    while data_exists loop
      -- Loop needed to flush rollback space.
      -- Started to fill the cursor with the right start id.
      open c1(last_customer, last_wearer, last_weareremployment, last_productcode, last_sizecode,
              last_finishingmethodcode);
      fetch c1 bulk collect
        into x limit 3000;
      for i in 1 .. x.count loop
        begin
          import_allowed           := true;
          last_customer            := x(i).customernumber;
          last_wearer              := x(i).wearernumber;
          last_weareremployment    := x(i).weareremploymentnumber;
          last_productcode         := x(i).productcode;
          last_sizecode            := x(i).sizecode;
          last_finishingmethodcode := x(i).finishingmethodcode;
          -- check provided data
          begin
            --customer
            errormsg := 'NO_DATA customer: ' || to_char(x(i).customernumber);
            select c.customer_id
            into   customerid
            from   customer c
            where  c.customernumber = x(i).customernumber;
            --wearer
            errormsg := 'NO_DATA customer/wearer: ' || to_char(x(i).customernumber) || '/' ||
                        to_char(x(i).wearernumber);
            select w.wearer_id, w.dateactive, w.dateinactive, w.dummyforpool
            into   wearerid, wdateactive, wdateinactive, wdummyforpool
            from   wearer w
            where  w.wearernumber = x(i).wearernumber
            and    w.customer_id = customerid;
            --product
            errormsg := 'NO_DATA product: ' || to_char(x(i).productcode);
            select p.product_id into productid from product p where p.code = x(i).productcode;
            --sizecode
            errormsg := 'NO_DATA size: ' || to_char(x(i).sizecode);
            select s.sizedefinition_id
            into   sizedefinitionid
            from   sizedefinition s
            where  s.code = x(i).sizecode;
            --finishingmethod
            errormsg := 'NO_DATA finshingmethod: ' || to_char(x(i).finishingmethodcode);
            select f.finishingmethod_id
            into   finishingmethodid
            from   finishingmethod f
            where  f.code = x(i).finishingmethodcode;
            --weareremploymentnumber
            errormsg := 'NO_DATA weareremploymentnumber: ' || to_char(x(i).weareremploymentnumber);
            select e.weareremployment_id
            into   weareremploymentid
            from   weareremployment e
            where  e.wearer_id = wearerid
            and    e.sequencenumber = x(i).weareremploymentnumber;
            -- check emblemtemplate code
            if x(i).emblemtemplate is null then
              lvnemblemtemplateid := null;
            else
              begin
                select t.emblemtemplate_id
                into   lvnemblemtemplateid
                from   emblemtemplate t
                where  t.customer_id = customerid
                and    t.code = trim(upper(x(i).emblemtemplate));
              exception
                when no_data_found then
                  begin
                    pack_import.cfbcreate_emblemtemplate(lvnemblemtemplateid, customerid,
                                                         x(i).emblemtemplate, x(i).emblemtemplate,
                                                         'Y', 'Y', 'Y');
                  end;
              end;
            end if;
          exception
            when no_data_found then
              pack_import.write_log(errormsg, -3);
              import_allowed := false;
          end;
          if import_allowed then
            begin
              begin
                --check plpc
                select min(l.productlistpercustomer_id)
                into   plpcid
                from   productlistpercustomer l
                where  l.customer_id = customerid
                and    l.product_id = productid
                and    (l.sizedefinition_id = fpnsizestarid or
                      l.sizedefinition_id = sizedefinitionid)
                and    l.finishingmethod_id = finishingmethodid;
                if plpcid is null then
                  insert_missing_plpc(customerid, productid, finishingmethodid, x(i).startdate,
                                      x(i).enddate, x(i).price, x(i).pricestartdate);
                  countplpc := countplpc + 1;
                end if;
              exception
                when others then
                  errormsg := 'Error adding missing plpc. ';
                  pack_import.write_log(errormsg, -3);
              end;
              --qualitygrade
              if trim(x(i).specialqualitygrade) is not null then
                qualitygradeid := pack_import.getqualitygradeid(x(i).specialqualitygrade);
              else
                qualitygradeid := null;
              end if;
              -- check start date
              if x(i).startdate > wdateactive then
                wdateactive := x(i).startdate;
              end if;
              --get_create_wearerinvcategory
              get_create_wearerinvcategory(x(i).wearerinvoicecategorycode,
                                           x(i).wearerinvoicecategorydesc,
                                           x(i).wic_employerpercentage, x(i).wic_maxemployeramount);
              --import wearerinventory
              insert into wearerinventory
                (wearerinventory_id, weareremployment_id, product_id, sizedefinition_id,
                 finishingmethod_id, emblemtemplate_id, specialgrade_id, maxinventory,
                 freeofchargeqty, circinventory, changesperweek, systemuser_id, timestamp,
                 maxfreeofcharge, dateactive, dateinactive, swingsuitstatus, returnedqty,
                 qtytobereturnedreplacement, qtytobereturneddecreasemax, dispensecredit,
                 personalizedgarment, remark, wearerinvoicecategory_id, temporaryrentstopstartdate,
                 temporaryrentstopenddate, temporarymaxinventory)
              values
                (seq_wearerinventory.nextval, weareremploymentid, productid, sizedefinitionid,
                 finishingmethodid, lvnemblemtemplateid, qualitygradeid, x(i).maxinventory,
                 x(i).freeofchargeqty, x(i).circinventory, x(i).changesperweek,
                 pack_import.lvnsystemuserid, sysdate, x(i).maxfreeofcharge, wdateactive,
                 x(i).enddate, x(i).swingsuitstatus, x(i).quantityreturned,
                 nvl(x(i).qtytobereturnedreplacement, 0), nvl(x(i).qtytobereturneddecreasemax, 0), 0,
                 case wdummyforpool when 'Y' then 'N' else 'Y' end, x(i).wearerinvremark,
                 lvnwearerinvoicecategoryid, x(i).temporaryrentstopstartdate,
                 x(i).temporaryrentstopenddate, x(i).maxinventory)
              returning wearerinventory_id into lvnwearerinventoryid;
              --wearerinvprice
              if x(i).wearerinventoryprice = 'Y' then
                insert into wearerinvprice
                  (wearerinvprice_id, wearerinventory_id, startdate, price, systemuser_id,
                   timestamp)
                values
                  (seq_wearerinvprice.nextval, lvnwearerinventoryid,
                   nvl(x(i).pricestartdate, sysdate), nvl(x(i).price, 0),
                   pack_import.lvnsystemuserid, sysdate);
              end if;
              -- fill nonuniqueitem table
              circinventory := x(i).circinventory - x(i).freeofchargeqty;
              if circinventory > 0 then
                begin
                  for z in 1 .. circinventory loop
                    begin
                      insert into nonuniqueitem
                        (nonuniqueitem_id, issuedate, sequencenumber, reasoncode_id,
                         wearerinventory_id, flag_id, flagstartdate, systemuser_id, timestamp,
                         startrentdate, freeitem)
                      values
                        (seq_nonuniqueitem.nextval, wdateactive, z, reasoncodeid,
                         lvnwearerinventoryid, null, null, pack_import.lvnsystemuserid, sysdate,
                         wdateactive, 'N');
                      countrowsnonu := countrowsnonu + 1;
                    exception
                      when dup_val_on_index then
                        null;
                      when others then
                        errormsg := 'CFbImportWearerInventory: Fail to insert nonuniqueitem for  wearernumber ' ||
                                    to_char(x(i).wearernumber) || ' customer ' ||
                                    to_char(x(i).customernumber) || ' productcode' || x(i).productcode;
                        pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                    end;
                  end loop;
                end;
              end if;
              --Free non unique
              circinventory := x(i).freeofchargeqty;
              if circinventory > 0 then
                begin
                  for z in 1 .. circinventory loop
                    begin
                      insert into nonuniqueitem
                        (nonuniqueitem_id, issuedate, sequencenumber, reasoncode_id,
                         wearerinventory_id, flag_id, flagstartdate, systemuser_id, timestamp,
                         startrentdate, freeitem)
                      values
                        (seq_nonuniqueitem.nextval, wdateactive, z, reasoncodeid,
                         lvnwearerinventoryid, null, null, pack_import.lvnsystemuserid, sysdate,
                         wdateactive, 'Y');
                      countrowsnonu := countrowsnonu + 1;
                    exception
                      when dup_val_on_index then
                        null;
                      when others then
                        errormsg := 'CFbImportWearerInventory: Fail to insert nonuniqueitem for  wearernumber ' ||
                                    to_char(x(i).wearernumber) || ' customer ' ||
                                    to_char(x(i).customernumber) || ' productcode' || x(i).productcode;
                        pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
                    end;
                  end loop;
                end;
              end if;
              begin
                --wearerinventorymodification
                if trim(x(i).modificationcode1) is not null then
                  select m.modification_id
                  into   modification1id
                  from   modification m
                  where  m.code = x(i).modificationcode1;
                  insert into wearerinventorymodification
                    (wearerinventory_id, modification_id, sequencenumber, systemuser_id, timestamp)
                  values
                    (lvnwearerinventoryid, modification1id, 1, pack_import.lvnsystemuserid, sysdate);
                end if;
                if trim(x(i).modificationcode2) is not null then
                  select m.modification_id
                  into   modification2id
                  from   modification m
                  where  m.code = x(i).modificationcode2;
                  insert into wearerinventorymodification
                    (wearerinventory_id, modification_id, sequencenumber, systemuser_id, timestamp)
                  values
                    (lvnwearerinventoryid, modification2id, 2, pack_import.lvnsystemuserid, sysdate);
                end if;
                if trim(x(i).modificationcode3) is not null then
                  select m.modification_id
                  into   modification3id
                  from   modification m
                  where  m.code = x(i).modificationcode3;
                  insert into wearerinventorymodification
                    (wearerinventory_id, modification_id, sequencenumber, systemuser_id, timestamp)
                  values
                    (lvnwearerinventoryid, modification3id, 3, pack_import.lvnsystemuserid, sysdate);
                end if;
              exception
                when dup_val_on_index then
                  null;
              end;
              --update i-table with real wearerinventory id that has been created
              update i_wearerinventory i
              set    i.wearerinventory_id = lvnwearerinventoryid
              where  i.customernumber = x(i).customernumber
              and    i.wearernumber = x(i).wearernumber
              and    i.productcode = x(i).productcode
              and    i.sizecode = x(i).sizecode
              and    i.weareremploymentnumber = x(i).weareremploymentnumber;
              countrows := countrows + 1;
            end;
          end if; --import_allowed
        exception
          when dup_val_on_index then
            null;
          when others then
            errormsg := 'CFbImportWearerInventory: Fail to insert wearerinventory for  wearernumber ' ||
                        to_char(x(i).wearernumber) || ' for customer ' ||
                        to_char(x(i).customernumber);
            pack_import.write_log(errormsg || ' ' || substr(sqlerrm, 1, 512), -3);
        end;
      end loop;
      if c1%notfound then
        data_exists := false;
      end if;
      close c1;
      commit; -- commit after closing cursor releases rollback space.
    end loop;
    -- count i-wearersinventory
    commit;
    select count(*) into countwearerinv from i_wearerinventory;
    if countwearerinv > 0 then
      begin
        pack_import.write_log(to_char(countwearerinv) || ' wearer inventory records in i-table.');
        pack_import.write_log(to_char(ocountwearerinv) ||
                              ' wearer inventory records already existed.');
        pack_import.write_log(to_char(countrows) || ' wearer inventory records imported.');
        select count(*) into countwearerinv from wearerinventory;
        pack_import.write_log(to_char(countwearerinv) || ' records now in wearer inventory.');
        if countplpc > 0 then
          pack_import.write_log(to_char(countplpc) || ' productlistpercustomer records imported.');
        end if;
        if countrowsnonu > 0 then
          pack_import.write_log(to_char(countrowsnonu) || ' nonuniqueitem rows inserted ');
        end if;
        -- make sure the size is not unfisished when used in wearerinventory
        update sizedefinition s
        set    s.unfinishedlength = 'N'
        where  exists (select s.sizedefinition_id
                from   wearerinventory i
                where  i.sizedefinition_id = s.sizedefinition_id)
        and    s.unfinishedlength <> 'N';
      end;
    end if;
    commit;
    update wearerinventory wi
    set    wi.emblemtemplate_id =
            (select et.emblemtemplate_id
             from   i_wearerinventory xi
             join   customer c
             on     c.customernumber = xi.customernumber
             join   emblemtemplate et
             on     et.code = trim(upper(xi.emblemtemplate))
             where  xi.wearerinventory_id = wi.wearerinventory_id), wi.timestamp = sysdate
    where  wi.emblemtemplate_id is null
    and    exists (select et.emblemtemplate_id
            from   i_wearerinventory xi
            join   customer c
            on     c.customernumber = xi.customernumber
            join   emblemtemplate et
            on     et.code = trim(upper(xi.emblemtemplate))
            where  xi.wearerinventory_id = wi.wearerinventory_id);
    countrowsnonu := sql%rowcount;
    commit;
    if countrowsnonu > 0 then
      pack_import.write_log(to_char(countrowsnonu) ||
                            ' wearerinventory emblemtemplate rows updated');
    end if;
  exception
    when others then
      begin
        rollback;
        errormsg := 'Error import cfbimportwearerinventory ';
        pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimportwearerinventory;
begin
  --initialisation
  select min(transportarticle_id) into fpntransportarticle_id from transportarticle;
  select sizedefinition_id into fpnsizestarid from sizedefinition where code = '*';
exception
  when others then
    errormsg := 'Error intializing: ';
    pack_import.write_log(errormsg || substr(sqlerrm, 1, 512), 3);
end pack_import_wearer;
/
create or replace package pack_import_web is
  -- Version : 1.0
  procedure convert_webuser;
  procedure convert_webusercustomer;
  procedure convert_web;
end pack_import_web;
/
create or replace package body pack_import_web is
  gv_message abslog.message%type;
  procedure convert_webuser is
    lv_langaugeid       languages.language_id%type;
    lv_plantid          plant.plant_id%type;
    lv_counter          number;
    lv_count_duplicates number;
  begin
    --convert_webuser
    gv_message          := 'pack_import_web.convert_webuser';
    lv_counter          := 0;
    lv_count_duplicates := 0;
    --count already existing records
    select count(1)
    into   lv_count_duplicates
    from   i_webuser iwb
    join   webuser wb
    on     wb.loginname = upper(iwb.loginname);
    --loop i_webuser
    for x in (select *
              from   i_webuser iw
              where  not exists (select 1 from webuser wb where wb.loginname = upper(iw.loginname))) loop
      begin
        --get language
        gv_message := 'language code ' || nvl(x.languagecode, 'NULL');
        select l.language_id into lv_langaugeid from languages l where l.code = x.languagecode;
        --get plant
        gv_message := 'plant code ' || nvl(x.plantcode, 'NULL');
        select pt.plant_id into lv_plantid from plant pt where pt.code = x.plantcode;
        --insert webuser
        gv_message := 'pack_import_web.convert_webuser insert into webuser ';
        insert into webuser
          (webuser_id, password, plant_id, language_id, loginname, convertedpassword, active,
           readonly, emailaddress, welcomemessage, accessgarments, accessnongarments,
           accesssalesitems, showgarments, passwordexpiresdays, changepasswordnextlogin,
           showgarmentgrade, showgarmentissuedate, showgarmentstay, showgarmentwashesissue,
           showgarmentwashestotal, showgarmentrepairsissue, showgarmentrepairstotal,
           showgarmentrewashesissue, showgarmentrewashestotal, showgarmentweeksinuseissue,
           showgarmentweeksinusetotal, showgarmentfreeofcharge, productdescriptiononly, allowsales,
           webreportpreviewer, laundryrepresent, custominfoaccess, userfolderaccess,
           securefolderaccess, phoneid, systemuser_id, timestamp)
        values
          (seq_webuser.nextval, '-', lv_plantid, lv_langaugeid, upper(x.loginname), x.convertedpassword,
           nvl(x.active, 'N'), nvl(x.readonly, 'N'), nvl(x.emailaddress, '-'), x.welcomemessage,
           nvl(x.accessgarments, 'N'), nvl(x.accessnongarments, 'N'), nvl(x.accesssalesitems, 'N'),
           nvl(x.showgarments, 0), nvl(x.passwordexpiresdays, 30),
           nvl(x.changepasswordnextlogin, 'N'), nvl(x.showgarmentgrade, 'N'),
           nvl(x.showgarmentissuedate, 'N'), nvl(x.showgarmentstay, 'N'),
           nvl(x.showgarmentwashesissue, 'N'), nvl(x.showgarmentwashestotal, 'N'),
           nvl(x.showgarmentrepairsissue, 'N'), nvl(x.showgarmentrepairstotal, 'N'),
           nvl(x.showgarmentrewashesissue, 'N'), nvl(x.showgarmentrewashestotal, 'N'),
           nvl(x.showgarmentweeksinuseissue, 'N'), nvl(x.showgarmentweeksinusetotal, 'N'),
           nvl(x.showgarmentfreeofcharge, 'N'), nvl(x.productdescriptiononly, 'N'),
           nvl(x.allowsales, 'N'), nvl(x.webreportpreviewer, 0), nvl(x.laundryrepresent, 'N'),
           nvl(x.custominfoaccess, 'N'), nvl(x.userfolderaccess, 'N'),
           nvl(x.securefolderaccess, 'N'), x.phoneid, pack_import.lvnsystemuserid, sysdate);
        --counter
        lv_counter := lv_counter + 1;
      exception
        when no_data_found then
          begin
            pack_import.write_log(gv_message || ' does not exist for i_webuser.loginname ' ||
                                  upper(x.loginname), 3);
          end;
      end;
    end loop; --x
    --commit
    commit;
    --message
    if lv_count_duplicates > 0 then
      begin
        pack_import.write_log(' ' || to_char(lv_count_duplicates) ||
                              ' webuser records did already exist');
      end;
    end if;
    if lv_counter > 0 then
      begin
        pack_import.write_log('Imported ' || to_char(lv_counter) || ' webusers');
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('Error during conversion of i_webuser ' || substr(sqlerrm, 1, 512), 3);
      end;
  end convert_webuser;
  procedure convert_webusercustomer is
    lv_customerid       customer.customer_id%type;
    lv_webuserid        webuser.webuser_id%type;
    lv_counter          number;
    lv_count_duplicates number;
  begin
    --convert_webusercustomer
    gv_message          := 'pack_import_web.convert_webusercustomer';
    lv_counter          := 0;
    lv_count_duplicates := 0;
    --loop i_webusercustomer
    for y in (select * from i_webusercustomer ic) loop
      begin
        --get customer
        gv_message := 'customer number ' || nvl(to_char(y.customernumber), 'NULL');
        select c.customer_id
        into   lv_customerid
        from   customer c
        where  c.customernumber = y.customernumber;
        --get webuser
        gv_message := 'web user ' || nvl(upper(y.loginname), 'NULL');
        select wb.webuser_id into lv_webuserid from webuser wb where wb.loginname = upper(y.loginname);
        --insert into webusercustomer
        gv_message := 'pack_import_web.convert_webusercustomer insert into webusercustomer';
        insert into webusercustomer
          (webusercustomer_id, webuser_id, customer_id, systemuser_id, timestamp)
        values
          (seq_webusercustomer.nextval, lv_webuserid, lv_customerid, pack_import.lvnsystemuserid,
           sysdate);
        --counter
        lv_counter := lv_counter + 1;
      exception
        when dup_val_on_index then
          lv_count_duplicates := lv_count_duplicates + 1;
        when no_data_found then
          begin
            pack_import.write_log(gv_message || ' does not exist for i_webusercustomer conversion',
                                  3);
          end;
      end;
    end loop; --y
    --commit
    commit;
    --messages
    if lv_count_duplicates > 0 then
      begin
        pack_import.write_log(' ' || to_char(lv_count_duplicates) ||
                              ' webusercustomer records did already exist');
      end;
    end if;
    if lv_counter > 0 then
      begin
        pack_import.write_log('Imported ' || to_char(lv_counter) || ' webusercustomer records');
      end;
    end if;
  exception
    when others then
      begin
        rollback;
        pack_import.write_log('Error during conversion of i_webusercustomer ' ||
                              substr(sqlerrm, 1, 512), 3);
      end;
  end convert_webusercustomer;
  procedure convert_web is
  begin
    convert_webuser;
    convert_webusercustomer;
  end convert_web;
end pack_import_web;
/
create or replace package pack_import_workorder is
  -- Author  : PVD
  -- Created : 20-June-2003
  -- Version : 1.0
  -- Updated : 27-March-2023
  -- Purpose : Create work order header and lines.
  --           Option to create sales notes as well
  procedure cfbimportworkorder;
  procedure cfbimportworkorderline;
end pack_import_workorder;
/
create or replace package body pack_import_workorder is
  lvnerrormsg varchar2(1000);
  procedure addmodification(fpnmodification_id in out modification.modification_id%type,
                            fpscode            in modification.code%type,
                            fpsdescription     in modification_desc.description%type) is
  begin
    -- create or retrieve modification
    select modification_id into fpnmodification_id from modification where code = fpscode;
  exception
    when no_data_found then
      -- add modification
      begin
        pack_import.cfbcreate_modification(fpnmodification_id, fpscode, 'N', fpscode, 'N');
        pack_import.cfbcreate_modification_desc(fpnmodification_id, nvl(fpsdescription, fpscode));
      exception
        when others then
          --error
          lvnerrormsg := 'Error modification: ' || fpscode;
          pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
    when others then
      --error
      lvnerrormsg := 'Error modification: ' || fpscode;
      pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
  end;
  procedure get_stockreservationpergrade(fp_stockreservationpergradeid out stockreservationpergrade.stockreservationpergrade_id%type,
                                         fp_qualitygradeid             in qualitygrade.qualitygrade_id%type,
                                         fp_stockroomid                in stockroom.stockroom_id%type,
                                         fp_productid                  in product.product_id%type,
                                         fp_sizeid                     in sizedefinition.sizedefinition_id%type,
                                         fp_customerowned              in stockdefinitionperitem.customerowned%type default 'N') is
    lv_stockdefinitionperitemid stockdefinitionperitem.stockdefinitionperitem_id%type;
    lv_supplier_id              supplier.supplier_id%type;
  begin
    begin
      lvnerrormsg := 'get_stockreservationpergrade get stockdefinitionperitem_id ';
      --get stockdefinitionperitem_id customerid should never be NULL
      select sdpi.stockdefinitionperitem_id
      into   lv_stockdefinitionperitemid
      from   stockdefinitionperitem sdpi
      where  sdpi.stockroom_id = fp_stockroomid
      and    sdpi.product_id = fp_productid
      and    sdpi.sizedefinition_id = fp_sizeid
      and    sdpi.customer_id is null
      and    sdpi.customerowned = fp_customerowned;
    exception
      when no_data_found then
        begin
          lvnerrormsg := 'get_stockreservationpergrade insert stockdefinitionperitem_id ';
          select p.supplier_id
          into   lv_supplier_id
          from   product p
          where  p.product_id = fp_productid;
          insert into stockdefinitionperitem
            (stockdefinitionperitem_id, stockroom_id, product_id, sizedefinition_id, customer_id,
             customerowned, minqtynew, minqtyused, maxqtynew, maxqtyused, systemuser_id, timestamp,
             defaultsupplier_id)
          values
            (seq_stockdefinitionperitem.nextval, fp_stockroomid, fp_productid, fp_sizeid, null,
             fp_customerowned, 0, 0, 999, 999, pack_import.lvnsystemuserid, sysdate, lv_supplier_id)
          returning stockdefinitionperitem_id into lv_stockdefinitionperitemid;
        end;
    end;
    begin
      --get stockreservationpergrade_id
      lvnerrormsg := 'get_stockreservationpergrade';
      select srpg.stockreservationpergrade_id
      into   fp_stockreservationpergradeid
      from   stockreservationpergrade srpg
      where  srpg.stockdefinitionperitem_id = lv_stockdefinitionperitemid
      and    srpg.qualitygrade_id = fp_qualitygradeid;
    exception
      when no_data_found then
        begin
          lvnerrormsg := 'get_stockreservationpergrade insert stockreservationpergrade.';
          insert into stockreservationpergrade
            (stockreservationpergrade_id, stockdefinitionperitem_id, qualitygrade_id,
             qtyuniquereserved, qtynonuniquereserved, qtyuniquewiithmodifreserved, qtynonunique,
             qtyuniqueordered, qtynonuniqueordered, systemuser_id, timestamp,
             qtyuniqueordereddirectissue, qtynonuniqueordereddirectissue)
          values
            (seq_stockreservationpergrade.nextval, lv_stockdefinitionperitemid, fp_qualitygradeid,
             0, 0, 0, 0, 0, 0, pack_import.lvnsystemuserid, sysdate, 0, 0)
          returning stockreservationpergrade_id into fp_stockreservationpergradeid;
        end;
    end;
  end get_stockreservationpergrade;
  procedure cfbimportworkorder is
    fpnworkorder_id           workorder.workorder_id%type;
    fpnroute_id               route.route_id%type;
    fp_processingstockroom_id stockroom.stockroom_id%type;
    lvcounter                 number := 0;
    fpnreasoncodeid           reasoncode.reasoncode_id%type;
    fpnorderpriorityid        workorder.orderpriority_id%type;
    lv_shipmenttypeid         shipmenttype.shipmenttype_id%type;
    procedure get_reasoncodeid(fpn_workordernumber in workorder.workordernumber%type) is
    begin
      select max(rs.reasoncode_id)
      into   fpnreasoncodeid
      from   i_workorderline il, reasoncode rs
      where  rs.code = il.reasoncode
      and    il.workordernumber = fpn_workordernumber;
      if fpnreasoncodeid is null then
        select min(rs.reasoncode_id) into fpnreasoncodeid from reasoncode rs;
      end if;
    end get_reasoncodeid;
    procedure get_shipmenttype(fp_shipmenttypecode in varchar2) is
      procedure create_shipmenttype is
      begin
        --create_shipmenttype
        lvnerrormsg := 'insert shipmenttype ' || upper(trim(fp_shipmenttypecode));
        insert into shipmenttype
          (shipmenttype_id, code, active, defaultshipmenttype, systemuser_id, timestamp)
        values
          (seq_shipmenttype.nextval, upper(trim(fp_shipmenttypecode)), 'Y', 'N',
           pack_import.lvnsystemuserid, sysdate)
        returning shipmenttype_id into lv_shipmenttypeid;
        insert into shipmenttype_desc
          (shipmenttype_id, language_id, description, systemuser_id, timestamp)
        values
          (lv_shipmenttypeid, pack_import.lvnlanguageid, fp_shipmenttypecode,
           pack_import.lvnsystemuserid, sysdate);
      end create_shipmenttype;
    begin
      --get_shipmenttype
      if trim(fp_shipmenttypecode) is null then
        begin
          lv_shipmenttypeid := null;
        end;
      else
        begin
          lvnerrormsg := 'get shipmenttype ' || upper(trim(fp_shipmenttypecode));
          select sht.shipmenttype_id
          into   lv_shipmenttypeid
          from   shipmenttype sht
          where  sht.code = upper(trim(fp_shipmenttypecode));
        exception
          when no_data_found then
            begin
              create_shipmenttype;
            end;
        end;
      end if;
    end get_shipmenttype;
  begin
    select min(t.orderpriority_id)
    into   fpnorderpriorityid
    from   orderpriority t
    where  t.ordertype = 1
    and    t.active = 'Y';
    -- inserting workorders.
    for x in (select i.workordernumber, s.status_id, i.routenumber, i.routedaynumber, i.requestdate,
                     b.businessunit_id, i.entrydate, i.neededdate, i.expectedcompletiondate,
                     i.completiondate, i.referencenumber, i.billtocustomerrelated, i.deliverfrom,
                     i.customerowned, i.allowedfhaseddeilvery, i.labelsprinted,
                     i.emblempicklistprinted, i.picklistprinted, i.remark, c.customer_id, w.wearer_id,
                     e.weareremployment_id, b.plant_id, i.processingstockroom_code,
                     i.shipmenttypecode, c.debtor_id, c.defaultinvoicebusinessunit_id,
                     case
                       when e.weareremployment_id is null then
                        6
                       else
                        3
                     end origin,
                     case
                       when e.weareremployment_id is null then
                        'Y'
                       else
                        'N'
                     end directinvoice, dp.distributionpoint_id
              from   i_workorder i
              join   customer c
              on     c.customernumber = i.customernumber
              join   businessunit b
              on     b.code = i.businessunit
              left   outer join(wearer w
              join   weareremployment e
              on     e.wearer_id = w.wearer_id) on (w.wearernumber = i.wearernumber and w.customer_id = c.customer_id and e.sequencenumber = nvl(i.weareremploymentnumber, 1))
              left   outer join(department t
              join   distributionpoint dp
              on     dp.department_id = t.department_id) on (t.departmentnumber = nvl(i.departmentnumber, 1) and t.customer_id = c.customer_id and dp.distributionpointnumber = nvl(i.consumptionpointnumber, 1))
              join   status s
              on     s.code = to_char(i.status)
              and    s.statustype = 'WO') loop
      begin
        begin
          --get_shipmenttype
          get_shipmenttype(x.shipmenttypecode);
          -- determine route id.
          lvnerrormsg := 'cfbimportworkorder determine route id';
          select r.route_id
          into   fpnroute_id
          from   route r
          where  r.routenumber = x.routenumber
          and    r.drivingday_id = x.routedaynumber
          and    r.plant_id = x.plant_id;
        exception
          when no_data_found then
            fpnroute_id := null;
        end;
        --get processing stockroom id
        lvnerrormsg := 'cfbimportworkorder get processing stock room code ' ||
                       nvl(x.processingstockroom_code, 'NULL');
        select st.stockroom_id
        into   fp_processingstockroom_id
        from   stockroom st
        where  st.code = x.processingstockroom_code;
        --get reason code
        get_reasoncodeid(x.workordernumber);
        lvnerrormsg := 'cfbimportworkorder insert into workorder';
        --insert
        insert into workorder
          (workorder_id, workordernumber, weareremployment_link_id, status_id, businessunit_id,
           route_id, requestdate, entrydate, neededdate, expectedcompletedate, completiondate,
           referencenumber, remark, customerowned, billtocustomerrelated, deliverfrom,
           allowphasedelivery, labelsprinted, emblempicklistprinted, picklistprinted,
           customer_link_id, systemuser_id, timestamp, ordered, origin, pickdate, pickuser_id,
           processingstockroom_id, reasoncode_id, orderpriority_id, shipmenttype_id, directinvoice,
           invoicebusinessunit_id, debtor_id, distributionpoint_link_id)
        values
          (seq_workorder.nextval, x.workordernumber, x.weareremployment_id, x.status_id,
           x.businessunit_id, fpnroute_id, x.requestdate, x.entrydate, x.neededdate,
           x.expectedcompletiondate, x.completiondate, x.referencenumber, x.remark, x.customerowned,
           x.billtocustomerrelated, nvl(x.deliverfrom, 3), x.allowedfhaseddeilvery, x.labelsprinted,
           x.emblempicklistprinted, x.picklistprinted, x.customer_id, pack_import.lvnsystemuserid,
           sysdate, 'N', x.origin, x.entrydate, null, fp_processingstockroom_id, fpnreasoncodeid,
           fpnorderpriorityid, lv_shipmenttypeid, x.directinvoice, x.defaultinvoicebusinessunit_id,
           x.debtor_id,
           case when x.weareremployment_id is null then x.distributionpoint_id else null end)
        returning workorder_id into fpnworkorder_id;
        lvcounter := lvcounter + 1;
      exception
        when dup_val_on_index then
          null;
        when others then
          begin
            lvnerrormsg := 'CFbImportWorkOrder: Fail to import.' || lvnerrormsg;
            pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
          end;
      end;
    end loop;
    commit;
    if lvcounter > 0 then
      pack_import.write_log(lvcounter || ' workorder imported.');
    end if;
  exception
    when others then
      begin
        rollback;
        lvnerrormsg := 'CFbImportWorkOrder: Fail to import.' || lvnerrormsg;
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimportworkorder;
  procedure cfbimportworkorderline is
    fpnworkorderline_id     workorderline.workorderline_id%type;
    fpnreasoncode_id        reasoncode.reasoncode_id%type;
    fpnqualitygradeid       qualitygrade.qualitygrade_id%type;
    fpnmodification_id      modification.modification_id%type;
    fpnfinishingmethod_id   finishingmethod.code%type;
    fpnstockreservationid   stockreservationpergrade.stockreservationpergrade_id%type;
    lvcounter               number := 0;
    lv_stocktype            workorderlinereservation.stocktype%type;
    lv_emblemtemplateid     emblemtemplate.emblemtemplate_id%type;
    lv_emblemtemplatelineid emblemtemplateline.emblemtemplateline_id%type;
  begin
    --select quality grade
    lvnerrormsg := 'cfbimportworkorderline loop i_workorderline';
    for x in (select w.workorder_id, p.product_id, s.sizedefinition_id, i.reasoncode, i.codeuniquely,
                     i.quantityordered, i.quantitycanceled, i.completiondate, i.modificationcode1,
                     i.modificationdescription1, i.modificationcode2, i.modificationdescription2,
                     i.modificationcode3, i.modificationdescription3, w.workordernumber,
                     replace(i.instructions, '|', chr(10)) instructions, i.quantityfilled,
                     i.quantitypedingorder, i.finishingmethodcode, w.processingstockroom_id,
                     w.deliverfrom, i.qualitygradecode, i.emblemtemplate, c.customer_id,
                     iw.customernumber, i.productcode, i.sizecode, w.expectedcompletedate,
                     case
                       when w.origin = 6 then
                        nvl(i.salesprice, 0)
                       else
                        i.salesprice
                     end salesprice,
                     case
                       when w.origin = 6 then
                        nvl(i.quantitytobecredited, 1)
                       else
                        i.quantitytobecredited
                     end quantitytobecredited,
                     case
                       when w.origin = 6 then
                        1
                       else
                        0
                     end salespriceorigin,
                     case
                       when w.origin = 6 then
                        1
                       else
                        0
                     end manualpricechange
              from   i_workorderline i
              join   i_workorder iw
              on     iw.workordernumber = i.workordernumber
              join   workorder w
              on     w.workordernumber = i.workordernumber
              join   product p
              on     p.code = i.productcode
              join   sizedefinition s
              on     s.code = i.sizecode
              join   customer c
              on     c.customernumber = iw.customernumber) loop
      begin
        --get qualitygrade
        lvnerrormsg := 'cfbimportworkorderline get qualitygrade ' ||
                       nvl(x.qualitygradecode, 'NULL');
        select q.qualitygrade_id
        into   fpnqualitygradeid
        from   qualitygrade q
        where  q.code = x.qualitygradecode;
        --get reasoncode
        lvnerrormsg := 'cfbimportworkorderline get reasoncode ' || nvl(x.reasoncode, 'NULL');
        select r.reasoncode_id into fpnreasoncode_id from reasoncode r where r.code = x.reasoncode;
        --get finishingmethod
        lvnerrormsg := 'cfbimportworkorderline get finishingmethod ' ||
                       nvl(x.finishingmethodcode, 'NULL');
        select f.finishingmethod_id
        into   fpnfinishingmethod_id
        from   finishingmethod f
        where  f.code = x.finishingmethodcode;
        --insert workorderline
        lvnerrormsg := 'cfbimportworkorderline insert workorderline';
        insert into workorderline
          (workorderline_id, workorder_id, product_link_id, sizedefinition_link_id,
           finishingmethod_id, requestedgrade_id, reasoncode_id, quantityordered, completiondate,
           codeuniquely, instructions, quantityfilled, quantitypendingorder, quantitycancelled,
           systemuser_id, timestamp, purchaseorderline_id, emblemtemplate_id, quantitypicked,
           expecteddate, salesprice, salespriceorigin, manualpricechange, quantitytobecredited)
        values
          (seq_workorderline.nextval, x.workorder_id, x.product_id, x.sizedefinition_id,
           fpnfinishingmethod_id, fpnqualitygradeid, fpnreasoncode_id, x.quantityordered,
           x.completiondate, x.codeuniquely, x.instructions, x.quantityfilled, x.quantitypedingorder,
           x.quantitycanceled, pack_import.lvnsystemuserid, sysdate, null, null, 0,
           nvl(x.expectedcompletedate, trunc(sysdate)), x.salesprice, x.salespriceorigin,
           x.manualpricechange, x.quantitytobecredited)
        returning workorderline_id into fpnworkorderline_id;
        lv_stocktype := 1;
        if x.modificationcode1 is not null then
          begin
            -- add modification 1
            lv_stocktype := 3;
            addmodification(fpnmodification_id, x.modificationcode1, x.modificationdescription1);
            pack_import.cfbcreate_workorderlinemod(fpnworkorderline_id,
                                                   --fpnworkorderline_id,
                                                   fpnmodification_id,
                                                   --fpnmodification_id,
                                                   1
                                                   --fpnsequencenumber,
                                                   );
          end;
        end if;
        if x.modificationcode2 is not null then
          begin
            -- add modification 2
            lv_stocktype := 3;
            addmodification(fpnmodification_id, x.modificationcode2, x.modificationdescription3);
            pack_import.cfbcreate_workorderlinemod(fpnworkorderline_id,
                                                   --fpnworkorderline_id,
                                                   fpnmodification_id,
                                                   --fpnmodification_id,
                                                   2
                                                   --fpnsequencenumber,
                                                   );
          end;
        end if;
        if x.modificationcode3 is not null then
          begin
            -- add modification 3
            lv_stocktype := 3;
            addmodification(fpnmodification_id, x.modificationcode3, x.modificationdescription3);
            pack_import.cfbcreate_workorderlinemod(fpnworkorderline_id,
                                                   --fpnworkorderline_id,
                                                   fpnmodification_id,
                                                   --fpnmodification_id,
                                                   3
                                                   --fpnsequencenumber,
                                                   );
          end;
        end if;
        if x.deliverfrom = 2 then
          begin
            --get stockreservation per grade
            get_stockreservationpergrade(fpnstockreservationid, fpnqualitygradeid,
                                         x.processingstockroom_id, x.product_id, x.sizedefinition_id);
            --create workorderline reservation
            lvnerrormsg := 'insert into workorderlinereservation';
            insert into workorderlinereservation
              (workorderline_id, stockreservationpergrade_id, stocktype, quantity, systemuser_id,
               timestamp, sequencenumber)
            values
              (fpnworkorderline_id, fpnstockreservationid, lv_stocktype, x.quantityordered,
               pack_import.lvnsystemuserid, sysdate, 0);
          end;
        end if;
        if x.emblemtemplate is not null then
          begin
            begin
              --add emblemtemplateline to workorderline
              select t.emblemtemplate_id
              into   lv_emblemtemplateid
              from   emblemtemplate t
              where  t.code = x.emblemtemplate
              and    t.customer_id = x.customer_id;
            exception
              when no_data_found then
                begin
                  lv_emblemtemplateid := null;
                  pack_import.write_log('  emblemtemplate ' || x.emblemtemplate || ' not found ' ||
                                        ' for customer ' || x.customernumber || ' for workorder ' ||
                                        x.workordernumber);
                end;
            end;
            if lv_emblemtemplateid is not null then
              begin
                --take the first emblemtemplateline
                select min(el.emblemtemplateline_id)
                into   lv_emblemtemplatelineid
                from   emblemtemplateline el
                where  el.emblemtemplate_id = lv_emblemtemplateid;
                if lv_emblemtemplatelineid is null then
                  begin
                    pack_import.write_log('  emblemtemplate line not found for ' ||
                                          x.emblemtemplate || ' not found ' || ' for customer ' ||
                                          x.customernumber || ' for workorder ' ||
                                          x.workordernumber);
                  end;
                else
                  begin
                    --insert into WORKORDERLINEEMBLEM
                    insert into workorderlineemblem
                      (workorderlineemblem_id, emblemtemplateline_id, workorderline_id, product_id,
                       sizedefinition_id, attachmentby, qtyrequested, qtyissued, systemuser_id,
                       timestamp)
                    values
                      (seq_workorderlineemblem.nextval, lv_emblemtemplatelineid,
                       fpnworkorderline_id, null, null, 0, 1, 1, pack_import.lvnsystemuserid,
                       sysdate);
                  end;
                end if;
              end;
            end if;
          end;
        end if;
        lvcounter := lvcounter + 1;
      exception
        when no_data_found then
          pack_import.write_log(lvnerrormsg || ' not found. Workorderline not imported', -3);
      end;
    end loop;
    commit;
    if lvcounter > 0 then
      pack_import.write_log(lvcounter || ' workorderlines imported.');
    end if;
  exception
    when others then
      begin
        lvnerrormsg := 'CFbImportWorkOrderLine: Fail to import.' || lvnerrormsg;
        pack_import.write_log(lvnerrormsg || substr(sqlerrm, 1, 512), 3);
      end;
  end cfbimportworkorderline;
end pack_import_workorder;
/
set define on
/
