2. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 7/6/2017 8:32:12 AM Central Daylight Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.

2.1 Files compared

# Location File Last Modified
1 HC 837 Compliance 05122017.zip\HC 837 Compliance 05122017\EDI_CodeConversion\EDI_CodeConversion\src\main\gov\va\med\hac\edi\era\jpa ProcessERepos835Load.java Thu May 12 19:17:58 2016 UTC
2 HC 837 Compliance 05122017.zip\HC 837 Compliance 05122017\EDI_CodeConversion\EDI_CodeConversion\src\main\gov\va\med\hac\edi\era\jpa ProcessERepos835Load.java Wed Jul 5 13:05:12 2017 UTC

2.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 2 4190
Changed 1 2
Inserted 0 0
Removed 0 0

2.3 Comparison options

Whitespace
Character case Differences in character case are significant
Line endings Differences in line endings (CR and LF characters) are ignored
CR/LF characters Not shown in the comparison detail

2.4 Active regular expressions

No regular expressions were active.

2.5 Comparison detail

  1   package go v.va.med.h ac.edi.era .jpa;
  2  
  3   import gov .va.med.do main.erepo s.Claim;
  4   import gov .va.med.do main.erepo s.ClaimAmo unt;
  5   import gov .va.med.do main.erepo s.ClaimPym tInfo;
  6   import gov .va.med.do main.erepo s.DentalSv cLine;
  7   import gov .va.med.do main.erepo s.EntityAd tlId;
  8   import gov .va.med.do main.erepo s.EntityNa me;
  9   import gov .va.med.do main.erepo s.Function alGroup;
  10   import gov .va.med.do main.erepo s.InstSvcL ine;
  11   import gov .va.med.do main.erepo s.PrfsnSvc Line;
  12   import gov .va.med.do main.erepo s.Stg835Cl p;
  13   import gov .va.med.do main.erepo s.Stg835Cl pCas;
  14   import gov .va.med.do main.erepo s.Stg835Cl pName;
  15   import gov .va.med.do main.erepo s.Stg835Hd r;
  16   import gov .va.med.do main.erepo s.Stg835Hd rBpr;
  17   import gov .va.med.do main.erepo s.Stg835Hd rTrn;
  18   import gov .va.med.do main.erepo s.Stg835Pa yerInfo;
  19   import gov .va.med.do main.erepo s.Stg835Pl b;
  20   import gov .va.med.do main.erepo s.Stg835Sv c;
  21   import gov .va.med.do main.erepo s.Stg835Sv cCas;
  22   import gov .va.med.do main.erepo s.Stg835Sv cLq;
  23   import gov .va.med.do main.erepo s.TradingP artners;
  24   import gov .va.med.do main.erepo s.TxnSet;
  25   import gov .va.med.do main.erepo s.TxnSetId ;
  26   import gov .va.med.do main.erepo s.batchloa d.ClaimDtD AO;
  27   import gov .va.med.do main.erepo s.batchloa d.EntityAd dressDAO;
  28   import gov .va.med.do main.erepo s.batchloa d.EntityNa meDAO;
  29   import gov .va.med.ha c.edi.util s.BadInput DataExcept ion;
  30   import gov .va.med.ha c.edi.util s.DateUtil ;
  31   import gov .va.med.ha c.edi.util s.DbTransa ctionEnder Exception;
  32   import gov .va.med.ha c.edi.util s.StringUt ils;
  33  
  34   import jav a.math.Big Decimal;
  35   import jav a.sql.SQLE xception;
  36   import jav a.util.Arr ayList;
  37   import jav a.util.Ite rator;
  38   import jav a.util.Lis t;
  39   import jav a.util.Set ;
  40   import jav a.util.UUI D;
  41  
  42   import jav ax.persist ence.Entit yManager;
  43   import jav ax.persist ence.Query ;
  44  
  45   import org .slf4j.Log ger;
  46   import org .slf4j.Log gerFactory ;
  47  
  48   // Copy da ta from th e E_REPOS  835 stagin g tables i nto the re gular ERep ository ta bles
  49   public cla ss Process ERepos835L oad {
  50     static f inal Logge r summaryL OGGER = Lo ggerFactor y.getLogge r(ProcessE Repos835Lo ad.class);
  51     static f inal Logge r traceLOG GER = Logg erFactory. getLogger( "trace." +  ProcessER epos835Loa d.class);
  52     // Const ants
  53     final pr ivate stat ic String  DATE_FORMA T = "HH:mm :ss:SSS";
  54     final pr ivate stat ic String  INPROCESS_ STATUS = " INPROCESS" ;
  55     final pr ivate stat ic String  ERROR_STAT US = "ERRO R";
  56     final pr ivate stat ic BigDeci mal zeroBD  = new Big Decimal("0 ");
  57  
  58     //////// ////////// /// Testin g and debu gging inst rumentatio n //////// ///
  59     // files etRestrict ionString  is used du ring testi ng to crea te a run
  60     //   ove r a subset  of file_n umbers in  a file
  61     // Set t his to a b lank strin g when not  testing
  62     //privat e static S tring test FilesetRes trictionCl ause
  63     //    =  "";
  64         // =  " AND fil e_number =  'W84146_9 999'";
  65    
  66     
  67     // test  with actua l input fi le here... .........f ile in pat h of this  class
  68     private  static Str ing testFi lesetRestr ictionClau se = " AND  file_numb er = '835_ input_test '";
  69     
  70     
  71  
  72     // testT ransaction Restrictio nString is  used duri ng testing  to create  a run
  73     //   ove r a subset  of transa ctions in  a fileset
  74     // Set t his to a b lank strin g when not  testing
  75     private  static Str ing testTr ansactionR estriction Clause
  76         = "" ;
  77         // =  " AND TO_ NUMBER(ST0 2TXN_CTL_N BR) < 101" ;
  78     //////// ////////// /// End of  Testing a nd debuggi ng instrum entation / //////////
  79  
  80     // Facad es for ins erting and  updating
  81     Insertio nMethods i nsertFacad e = new In sertionMet hods();
  82     StagingF acade stag ingFacade  = new Stag ingFacade( );
  83  
  84     // Top-l evel contr ol field;  there are  few file n umbers in  a run
  85     private  String vFi leNumber =  "";
  86  
  87     // Contr ol field,  level 2 :  a file_num ber has ma ny transac tion contr ol numbers
  88     // Trans action con trol numbe r is plain  in stagin g, but lef t-padded w ith zeros
  89     //   in  the ERepos itory
  90     private  String vSt 02txnCtlNb rPadded =  "";
  91     private  String vSt 02txnCtlNu mberNoPad  = "";
  92  
  93     // Claim  key is fo r querying  from the  837 data
  94     private  String vCl aimKey = " ";
  95     private  String v83 7FileNumbe r = "";
  96     private  String v83 7St02txnCt lNbr = "";
  97     private  String v83 7SbsrId =  "";
  98     private  String v83 7BillHrchl Key = "";
  99     private  String v83 7SbsrHrchl Key = "";
  100  
  101     // The D etail Head  Info Key  stores the  GUID of t he DETAIL_ HEAD_INFO  record
  102     //   for  when it i s needed i n table CL AIM_PYMT_I NFO
  103     private  String vDt lHeadInfoK ey = "";
  104  
  105     // Contr ol field,  level 3: A  transacti on has a s mall numbe r of claim  payments
  106     private  String vCl pKey = "";
  107  
  108     // Contr ol field,  level 4: A  claim pay ment has a  variable  number of  service li nes
  109     private  String vSv cKey = "";
  110  
  111     // The s taging ver sions of c laim payme nt key and  service l ine key ar e used in
  112     //   que ries again st the sta ging area
  113     private  String vSt gClpKey =  "";
  114     private  String vSt gSvcKey =  "";
  115  
  116     // vTran sactionCou nt counts  the number  of transa ctions (ie . headers)
  117     //   in  a fileset,  for updat ing the fu nctional g roup recor d
  118     private  int vTrans actionCoun t = 0;
  119  
  120     // vSegm entCount c ounts the  number of  segments i n a header , that is,  the
  121     //   num ber of rec ords inser ted for a  transactio n.
  122     private  int vSegme ntCount =  0;
  123  
  124     // vQuer yCount is  used for n aming dyna mically-cr eated quer ies
  125     // Perha ps this is  used if m ore than o ne file ar e picked u p for the  run
  126     private  int vQuery Count = 0;
  127  
  128     private  String vCl earinghous eId = "";
  129     private  String vPa yerId    =  "";
  130  
  131     private  String vFa cilityId =  "";
  132     private  String vPr oviderId =  "";
  133     private  String vPr oviderNpi=  null;
  134     private  String vPa yeeName  =  "";
  135  
  136     // The p roduction  date will  be set in  insertTrac eNumbers,  then get i ts own rec ord
  137     //   in  table CLAI M_DT
  138     private  String vPr odDate   =  "";
  139     private  String vCl aimDate  =  "";
  140  
  141     // We ha ve no mech anism to s et vIntAmt  at presen t
  142     private  BigDecimal  vIntAmt =  zeroBD;
  143  
  144     // List  of the fil esets that  are being  processed
  145     final pr ivate Arra yList file NumbersLis t  = new A rrayList(3 );
  146  
  147     // hasXC odeError m arks wheth er an erro r occurred  in XCODE  conversion , for
  148     //   the  current f ileset
  149     private  boolean ha sXCodeErro r = false;
  150  
  151     // This  method car ries most  of the log ic
  152     final pr otected vo id process 835Load(En tityManage r dbEMStg,  EntityMan ager dbEME repos)
  153     throws T hrowable
  154     {
  155             
  156           bo olean DEBU G = true;
  157       Query  query = db EMStg.crea teNativeQu ery("SELEC T DISTINCT  FILE_NUMB ER FileNum ber FROM E _REPOS.STG _835_HDR W HERE STSE_ STATUS = ' NEW' "); / / + testFi lesetRestr ictionClau se);
  158       
  159  
  160       List f ileNumberL ist = null ;
  161       Iterat or fileNum berIterato r = null;
  162       
  163         // c annot open  connectio
  164         try  {
  165              fileNumber List = que ry.getResu ltList();
  166         }cat ch(Excepti on ex) {
  167              System.out .println(" process835 Load() - e rror runni ng top lev el query:  "  + ex.ge tMessage() );
  168         }
  169              fileNumber Iterator =  fileNumbe rList.iter ator();
  170             
  171                // Put t he fileset  identifie rs into a  vector
  172                     whi le (fileNu mberIterat or.hasNext ()) {
  173                           final St ring nextF ileNumber  = (String)  fileNumbe rIterator. next();
  174           
  175   /**                     
  176                           if(DEBUG ) {
  177                               Syst em.out.pri ntln("proc ess835Load () - nextF ileNumber  is: " + ne xtFileNumb er);
  178                           }
  179   **/                     
  180                           
  181                           fileNumb ersList.ad d(nextFile Number);
  182                }   // e nd while
  183  
  184   /**               
  185                if(DEBUG ) {
  186                      Sy stem.out.p rintln("pr ocess835Lo ad() - siz e of fileN umbersList  is: " + f ileNumbers List.size( ));
  187                    }  
  188   **/
  189                     
  190       // Loo p through  the filese ts, proces sing each  one
  191       final  int numFil eSets = fi leNumbersL ist.size() ;
  192       System .out.print ln("proces s835Load() : " + numF ileSets +  " Filesets  are avail able in 83 5 Staging  Tables for  Processin g");
  193       for (i nt i=0; i  < numFileS ets; i++)  {
  194           
  195         dbEM Stg.getTra nsaction() .begin();
  196              dbEMErepos .getTransa ction().be gin();
  197         dbEM Stg.flush( );
  198         dbEM Stg.clear( ); 
  199         dbEM Erepos.flu sh();
  200         dbEM Erepos.cle ar();
  201         
  202         // L og and rol lback if t his doesn' t work
  203         try  {
  204           //  Count the  transacti ons (ie. h eaders) fo r this fil e number
  205           vT ransaction Count = 0;
  206     
  207           //  Start pro cessing th is fileset
  208           vF ileNumber  = (String)  fileNumbe rsList.get (i);
  209           su mmaryLOGGE R.info("St art Proces sing For F ileNumber  : " + vFil eNumber);
  210           tr aceLOGGER. info("Star t Processi ng For Fil eNumber :  " + vFileN umber);
  211      
  212         
  213           if (DEBUG) {
  214                    Syst em.out.pri ntln("proc ess835Load () - Start  Processin g For File Number : "  + vFileNu mber );
  215           }
  216       
  217           //  For files ets that c ome from t he HAC sys tem, rathe r
  218           //    than th e FEE syst em, we nee d to conve rt from th e
  219           //    old XCO DE procedu re codes
  220           //  Ticket: D EF004652 -  Changed 4  to 5 belo w.
  221           if  (vFileNum ber.substr ing(1,5).e qualsIgnor eCase("841 4")) {
  222              // Assume  no XCODE e rrors in t his filese t
  223              hasXCodeEr ror = fals e;
  224     
  225              // Perform  XCODE con version as  necessary , while up dating the
  226              //   statu s of HDR,  CLP, and S VC records  on the wa y, for all  the
  227              //   recor ds in this  fileset
  228              convertPro cCode(dbEM Stg, dbEME repos);
  229           }  else {
  230              // Update  the HDR, C LP, SVC ta ble status es from 'N EW' to 'IN PROCESS'
  231               stagingFa cade.updat eStatusCol umns(vFile Number, db EMStg);
  232           }
  233           
  234           db EMStg.flus h();
  235           db EMErepos.f lush();
  236           db EMErepos.c lear();
  237           
  238           //  Insert in to the two  X12 envel ope tables
  239           //  Note: At  this point , we have  not yet co unted the  transactio ns,
  240           //    whose c ount goes  into table  FUNCTIONA L_GROUP.   But, we ha ve to
  241           //    insert  FUNCTIONAL _GROUP fir st because  TXN_SET h as a refer ential
  242           //    integri ty constra int to it.   The move ment of da ta from
  243           //    the cac he to the  database g oes by def ault in th e same ord er in
  244           //    which r ecords wer e inserted  in the co de.
  245           tr aceLOGGER. info("Inse rting enve lope recor ds at " +  DateUtil.g etCurrentT imeFormatt ed(DATE_FO RMAT));
  246           
  247           /* *
  248           if (DEBUG) {
  249                    Syst em.out.pri ntln("proc ess835Load () - Inser ting envel ope record s at " + D ateUtil.ge tCurrentTi meFormatte d(DATE_FOR MAT));
  250           }
  251           ** /
  252           
  253           Fu nctionalGr oup functi onalGroup  = insertEn velopeInfo (dbEMStg,  dbEMErepos );
  254                    dbEM Stg.flush( );
  255                    dbEM Erepos.flu sh();
  256                    dbEM Erepos.cle ar();     
  257                    
  258                // ? WHA T DOES THI S COMMENT  MEAN? DON' T CLEAR TH EM WHERE?  THEY'RE CL EARED BELO W   
  259           //  Don't cle ar eRepos  objects  
  260                traceLOG GER.info(" Starting t o insert t ransaction s at "
  261                             + Date Util.getCu rrentTimeF ormatted(D ATE_FORMAT ));
  262                      
  263           in sertHeader Segments_S TSE(dbEMSt g, dbEMEre pos);
  264                    dbEM Stg.flush( );         // write r ecords fro m above
  265                    dbEM Erepos.flu sh(); // h angs on in sert INTCH G_CONTROL  call - whe re is this ?
  266                    dbEM Erepos.cle ar();
  267                    
  268           up dateTransa ctionSetCo unt(dbEMEr epos);
  269           
  270                    dbEM Stg.flush( );
  271                    dbEM Erepos.flu sh();
  272                    dbEM Erepos.cle ar();
  273          
  274                    if(D EBUG) {
  275                             System .out.print ln("proces s835Load()  - EMs cle ared and f lushed at  " + DateUt il.getCurr entTimeFor matted(DAT E_FORMAT)) ;
  276                    }
  277       
  278           
  279           in sertFacade .insertEdi 835Process (vFileNumb er, vClear inghouseId , vPayerId , vSt02txn CtlNbrPadd ed, dbEMEr epos);
  280                    dbEM Stg.flush( );
  281                    dbEM Erepos.flu sh();
  282                    dbEM Erepos.cle ar();
  283                    
  284  
  285           
  286                    if(D EBUG) {
  287                             System .out.print ln("proces s835Load()  - DONE In serting an  835 proce ss insertF acade.inse rtEdi835Pr ocess() re cords at "
  288                                      + DateUt il.getCurr entTimeFor matted(DAT E_FORMAT)) ;
  289                    }
  290        
  291                       
  292                    // F or File Nu mbers that  encounter ed an erro r with XCo des, add
  293                    //    a suffix  to disting uish them  the next t ime they a re process ed
  294                    // N ote: If th ere was an  XCode err or for a g iven heade r, that he ader
  295                    //    would not  have been  copied to  the eRepo s tables.   We need t o update
  296                    //    the file  number for  those hea ders, givi ng it a ne w suffix,  so that
  297                    //    it will i n future b e treated  as a diffe rent files et
  298                    if ( hasXCodeEr ror) {
  299                      Sy stem.out.p rintln("pr ocess835Lo ad() - Err or occurre d. Updatin g file num ber at "
  300                           + DateUt il.getCurr entTimeFor matted(DAT E_FORMAT)) ;
  301                      Sy stem.out.p rintln("pr ocess835Lo ad() - Err or occurre d. Updatin g file num ber at "
  302                               + Da teUtil.get CurrentTim eFormatted (DATE_FORM AT));
  303                      st agingFacad e.updateFi leNumber(  vFileNumbe r, dbEMStg );
  304                    }
  305     
  306                             System .out.print ln(("proce ss835Load( ) - Commit ting the E Repository  transacti on at "
  307                                               + DateUtil .getCurren tTimeForma tted(DATE_ FORMAT)));
  308     
  309                             dbEMEr epos.getTr ansaction( ).commit() ;
  310                             System .out.print ln("proces s835Load()  - Commit  successful ");
  311     
  312                             System .out.print ln("proces s835Load()  - Committ ing the st aging tran saction at  "
  313                                               + DateUtil .getCurren tTimeForma tted(DATE_ FORMAT));
  314     
  315                             dbEMSt g.getTrans action().c ommit();
  316                             System .out.print ln("proces s835Load()  - ALL DON E Commit s uccessful" );            
  317                             
  318                    }cat ch(Excepti on e) {
  319                             
  320                             
  321                             if(DEB UG) {
  322                                      System.o ut.println ("process8 35Load() e rror: " +  e.getMessa ge());
  323                                      e.printS tackTrace( );
  324                             }
  325                             
  326                             
  327                             handle Exception( dbEMStg, " staging",  e);
  328                             handle Exception( dbEMErepos , "erepos" , e);
  329                             
  330                             
  331                    }
  332       } // e nd of loop  through t he fileset s
  333         
  334     } // end  method pr ocess835Lo ad
  335  
  336     private  static voi d handleEx ception(En tityManage r dbEMErep os, String  identifie r, Throwab le e) thro ws Throwab le {
  337           Sy stem.out.p rintln("ha ndleExcept ion() - EM  with erro r is: " +  dbEMErepos .getClass( ).getName( ));
  338           Sy stem.out.p rintln("ha ndleExcept ion() - Th rowable e  is: " + e. getMessage ());  
  339           Sy stem.out.p rintln("ha ndleExcept ion() - Ro lling back  the datab ase transa ction " +  identifier  + "\n");
  340           
  341           if  (dbEMErep os != null ) {
  342                    if ( dbEMErepos .getTransa ction().is Active())  {
  343                             dbEMEr epos.getTr ansaction( ).rollback ();
  344                    }
  345           }
  346           Sy stem.out.p rintln("ha ndleExcept ion() - Ro llback suc cessful");
  347           th row e;
  348           
  349     }     //  end handl eException ()
  350     
  351     private  void updat eTransacti onSetCount (EntityMan ager dbEM)
  352     {
  353           //   boolean  DEBUG = tr ue;
  354             
  355              Query getF unctionalG roupToUpda te = dbEM. createQuer y("SELECT  f FROM gov .va.med.do main.erepo s.Function alGroup f  "
  356                             + "  W HERE f.fil eNumber=?1 " );
  357             
  358             
  359            
  360              getFunctio nalGroupTo Update.set Parameter( 1, vFileNu mber);
  361             
  362              Functional Group func tionalGrou pToUpdate  = null;
  363             
  364              try {
  365                      fu nctionalGr oupToUpdat e = (Funct ionalGroup ) getFunct ionalGroup ToUpdate.g etSingleRe sult();
  366                      fu nctionalGr oupToUpdat e.setGe01n brTranSets (Integer.t oString(vT ransaction Count));
  367              }catch(Exc eption e)  {
  368                      Sy stem.out.p rintln("up dateTransa ctionSetCo unt() - ER ROR: " + e .getMessag e());
  369                      e. printStack Trace();
  370              }
  371             
  372              dbEM.persi st(functio nalGroupTo Update);
  373       
  374     } // end  method u
  375     
  376     // Inser t a record  into each  of the "e nvelope" t ables:
  377     //   INT CHG_CONTRO L (Interch ange contr ol) and FU NCTIONAL_G ROUP
  378     private  Functional Group inse rtEnvelope Info(Entit yManager d bEMStg, En tityManage r dbEMErep os)
  379     throws S QLExceptio n
  380     {
  381              Functional Group func tionalGrou pToReturn  = null;
  382         // C all up the  first hea der record  from the  staging ta bles
  383       Query  getHeaderR ecord = db EMStg.crea teQuery("S ELECT h"
  384                             + "  F ROM gov.va .med.domai n.erepos.S tg835Hdr h  "
  385                             + "  W HERE h.fil eNumber=?1  AND ROWNU M=?2");
  386       getHea derRecord. setParamet er(1, vFil eNumber);
  387       getHea derRecord. setParamet er(2, new  Long(1));
  388       
  389       List h eaders = g etHeaderRe cord.getRe sultList() ;    
  390      
  391         Stg8 35Hdr crSt g835Hdr =  null;
  392         if(h eaders.siz e()>0)
  393         {
  394              crStg835Hd r = (Stg83 5Hdr) head ers.get(0) ;
  395         }
  396         
  397         // O nly do thi s if a hea der record  was found
  398         if ( crStg835Hd r != null)  {
  399              // Pull a  few pieces  of data o ut of the  header rec ord, into  globals
  400              vFileNumbe r = crStg8 35Hdr.getF ileNumber( );
  401              vClearingh ouseId = c rStg835Hdr .getCleari nghouseId( );
  402              vPayerId =  crStg835H dr.getPaye rId();
  403  
  404              final Stri ng transac tionDate =  DateUtil. getCurrent DateFormat ted("yyyyM Mdd");
  405              final Stri ng transac tionTime =  DateUtil. getCurrent TimeFormat ted("HHmm" );
  406  
  407  
  408              insertFaca de.insertI nterchange Control(vF ileNumber,  vPayerId,  vClearing houseId, c rStg835Hdr , transact ionDate, t ransaction Time, dbEM Erepos);
  409  
  410              // Insert  a row into  FUNCTIONA L_GROUP
  411              functional GroupToRet urn = inse rtFacade.i nsertFunct ionalGroup (vFileNumb er, vPayer Id, vClear inghouseId , transact ionDate, t ransaction Time, dbEM Erepos);
  412         }
  413         
  414   /**       
  415     if(DEBUG ) {
  416                    Syst em.out.pri ntln("inse rtEnvelope Info() - D ONE callin g insertFu nctionalGr oup() ");
  417     }      
  418   **/      
  419         
  420         
  421         retu rn functio nalGroupTo Return;
  422     } // end  method in sertEnvelo peInfo
  423  
  424     // For t hose heade rs in the  current fi leset that  were mark ed as INPR OCESS
  425     //   by  the proc c ode conver sion, inse rt rows in to some ta bles (like  TXN_SET,
  426     //   FIN ANCIAL_INF O, CLAIM_P YMT_INFO,  and SVC_PY MT_INFO),  and call m ethods
  427     //   to  insert row s into mos t of the o ther table s.
  428     private  void inser tHeaderSeg ments_STSE (EntityMan ager dbEMS tg, Entity Manager db EMErepos)
  429     throws S QLExceptio n, BadInpu tDataExcep tion
  430     {
  431       
  432             
  433     boolean  DEBUG = tr ue;
  434     
  435              if(DEBUG)  {
  436                      Sy stem.out.p rintln("in sertHeader Segments_S TSE() - vF ileNumber  is: " + vF ileNumber) ;
  437              }
  438             
  439              Query getI nProcessHe adersQuery  = dbEMStg .createNat iveQuery(" SELECT * F ROM STG_83 5_HDR " +
  440                              " WHE RE STSE_ST ATUS = ?1  AND  FILE_ NUMBER = ? 2 " + 
  441                               test Transactio nRestricti onClause +
  442                              " ORD ER BY TO_N UMBER(ST02 TXN_CTL_NB R)", Stg83 5Hdr.class  );     
  443           
  444  
  445   // SETTING  FROM 'NEW ' TO 'INPR OCESS' NOT  COMMITTIN G     
  446           ge tInProcess HeadersQue ry.setPara meter(1,"I NPROCESS") ;                     // CHANGE  BACK TO IN PROCESS WH EN PROBLEM  IS SOLVED .
  447           ge tInProcess HeadersQue ry.setPara meter(2,vF ileNumber) ;
  448  
  449           Li st inProce ssHeaders= null;
  450           
  451           tr y {
  452                    inPr ocessHeade rs = getIn ProcessHea dersQuery. getResultL ist();
  453           }c atch(Excep tion ex) {
  454                    Syst em.out.pri ntln("inse rtHeaderSe gments_STS E() - erro r getting  HDR record : " + ex.g etMessage( ));
  455                    ex.p rintStackT race();
  456           }
  457           
  458                    
  459           It erator inP rocessHead erIterator  = inProce ssHeaders. iterator() ;
  460           
  461           // Hack so th at I can c lear the J PA cache
  462           wh ile(inProc essHeaderI terator.ha sNext()) {  inProcess HeaderIter ator.next( ); }
  463           in ProcessHea derIterato r = inProc essHeaders .iterator( );
  464           
  465           in t headerCo unter = 0;
  466       // Loo p through  the header s, process ing each b y insertin g into sev eral table s
  467       while  (inProcess HeaderIter ator.hasNe xt()) {
  468           he aderCounte r++;
  469           
  470           if (headerCou nter % 50  == 0)
  471           {
  472                    dbEM Stg.flush( );
  473                    dbEM Erepos.flu sh();              
  474                    dbEM Erepos.cle ar();
  475           }
  476           
  477         // G et the nex t header
  478         fina l Stg835Hd r crStg835 Hdr = (Stg 835Hdr) in ProcessHea derIterato r.next();
  479         
  480         
  481   // calls i nsert inse rtClaimPay ment_CLP  
  482   // IF THER E IS NO HE ADER RECOR D FROM ABO VE THIS IS  NEVER CAL LED....... ...... 
  483   // GO THRO UGH CALLS  IN HERE AN D FIND E_R EPOS.INTCH G_CONTROL_ PK  
  484   // unique  constraint  (E_REPOS. INTCHG_CON TROL_PK) v iolated          
  485         inse rtHeaderSe gment_STSE (crStg835H dr, dbEMSt g, dbEMEre pos);
  486  
  487     
  488         if(D EBUG) {
  489                    Syst em.out.pri ntln("inse rtHeaderSe gments_STS E() - DONE  calling i nsertHeade rSegment_S TSE() ");
  490                    }       
  491         
  492         
  493         // S how a litt le output  in case th is is bein g run manu ally
  494         if ( vTransacti onCount %  100 == 0)
  495         {
  496           Sy stem.out.p rintln("in sertHeader Segments_S TSE() - Fi nished tra nsaction c ount: " +  vTransacti onCount);
  497         }
  498         
  499         
  500       }
  501       
  502       
  503     } // end  method in sertHeader Segments_S TSE
  504  
  505     // Inser t informat ion for on e header,  including  its claim  payments
  506     //   and  service l ines
  507     private  void inser tHeaderSeg ment_STSE( final Stg8 35Hdr crSt g835Hdr, E ntityManag er dbEMStg , EntityMa nager dbEM Erepos)
  508     throws S QLExceptio n, BadInpu tDataExcep tion
  509     {
  510             
  511             
  512           bo olean DEBU G = true;
  513       // cou nt the num ber of seg ments inse rted in th is transac tion
  514       vSegme ntCount =  0;
  515  
  516       // Res et the ins tance vari ables that  vary for  each heade r
  517       initia lizeHeader Variables( );
  518  
  519       // TOD O: File nu mber and c learinghou se and pay erId
  520       //   s hould have  already b een set, a nd should
  521       //   n ot change  from heade r to heade r.  Maybe  assert thi s?
  522       vFileN umber = cr Stg835Hdr. getFileNum ber();
  523       vClear inghouseId  = crStg83 5Hdr.getCl earinghous eId();
  524       vPayer Id = crStg 835Hdr.get PayerId();
  525  
  526       // Get  variable  pieces of  info from  the header  record
  527       vFacil ityId = cr Stg835Hdr. getFacilit yId();
  528       vProvi derId = cr Stg835Hdr. getProvide rId();
  529       vPayee Name  = cr Stg835Hdr. getProvide rName();
  530       vProvi derNpi = c rStg835Hdr .getNpi();
  531  
  532       // Use  both the  unpadded a nd padded  versions o f the
  533       //   t ransaction  control n umber
  534       vSt02t xnCtlNumbe rNoPad = c rStg835Hdr .getSt02tx nCtlNbr();
  535       vSt02t xnCtlNbrPa dded = Str ingUtils.l PadZeros(v St02txnCtl NumberNoPa d, 9);
  536  
  537       // Cre ate a new  record rep resenting  the transa ction, in  TXN_SET
  538       
  539       TxnSet  trTxnSet  = (TxnSet)  new TxnSe t();
  540       TxnSet Id trTxnSe tId = (Txn SetId) new  TxnSetId( );
  541       trTxnS etId.setFi leNumber(v FileNumber );
  542       trTxnS etId.setSt 02txnCtlNb r(vSt02txn CtlNbrPadd ed);    
  543       trTxnS et.setId(t rTxnSetId) ;
  544       trTxnS et.setTxTy pe("835");
  545       trTxnS et.setSt01 txnId("835 ");
  546       vSegme ntCount++;
  547       
  548  
  549       // TWP : REMOVE F orgein Key  Order Hac king !!! I nsert the  new transa ction reco rd
  550       trTxnS et.setSe02 txnCtlNbr( vSt02txnCt lNbrPadded );
  551       trTxnS et.setSe01 txnSgmtCnt (new BigDe cimal(Inte ger.toStri ng(vSegmen tCount)));
  552       
  553       trTxnS et.setCrea tedBy("E_R EPOS");
  554       
  555       dbEMEr epos.persi st(trTxnSe t);
  556       
  557       // Get  a record  from the p rovider in formation  table, use d mostly
  558       //   f or setting  fields in  the finan cial info  record   
  559       Query  getProvide rInformati onQuery =  dbEMStg.cr eateQuery( "SELECT bp r"
  560                + "  FRO M gov.va.m ed.domain. erepos.Stg 835HdrBpr  bpr "
  561                + "   WH ERE bpr.fi leNumber=? 1 AND bpr. st02txnCtl Nbr=?2");
  562       getPro viderInfor mationQuer y.setParam eter(1, vF ileNumber) ;
  563       getPro viderInfor mationQuer y.setParam eter(2, vS t02txnCtlN umberNoPad );
  564       
  565       List p roviderInf ormations  = getProvi derInforma tionQuery. getResultL ist();    
  566           
  567       Stg835 HdrBpr crS tg835HdrBp r = null;
  568       if(pro viderInfor mations.si ze() > 0)
  569       {
  570           cr Stg835HdrB pr = (Stg8 35HdrBpr)  providerIn formations .get(0);
  571       }
  572       
  573       // Cre ate a new  record for  table fin ancial_inf o
  574       insert Facade.ins ertFinanci alInfo(crS tg835HdrBp r, vFileNu mber, vSt0 2txnCtlNbr Padded, db EMErepos);
  575      
  576       if(DEB UG) {
  577           Sy stem.out.p rintln("in sertHeader Segment_ST SE() - DON E calling  insertFina ncialInfo( )");
  578       }
  579       
  580       
  581       
  582       vSegme ntCount++;
  583  
  584       // Ins ert a sing le record  into table  TRACE_NUM BER, which  identifie s
  585       //   t his transa ction for  future ref erence
  586       insert TraceNumbe rs_TRN(dbE MStg, dbEM Erepos);
  587  
  588    
  589       if(DEB UG) {
  590           Sy stem.out.p rintln("in sertHeader Segment_ST SE() - DON E calling  insertTrac eNumbers() ");
  591       }
  592     
  593       // Ins ert a reco rd indicat ing the id entity of  the receiv er of this  835,
  594       //   b ut only if  the clear inghouse i s not SXC
  595       if (!v Clearingho useId.equa ls("752578 509")) {
  596           in sertFacade .insertSeg mentREF(vF ileNumber,  vSt02txnC tlNbrPadde d,vClpKey,  vSvcKey,  "EV", vCle aringhouse Id, "HEADE R", dbEMEr epos);
  597           
  598           
  599            i f(DEBUG) {
  600                    Syst em.out.pri ntln("inse rtHeaderSe gment_STSE () - DONE  calling in sertSegmen tREF()");
  601              }
  602                    
  603           vS egmentCoun t++;
  604       }
  605  
  606       // Ins ert the pr oduction d ate, that  is, the en d date of  the
  607       //   a djudicatio n producti on cycle f or include d claims
  608       insert Facade.ins ertDate(vF ileNumber,  vSt02txnC tlNbrPadde d,
  609           vC lpKey, vSv cKey, "405 ", vProdDa te, dbEMEr epos);
  610       vSegme ntCount++;
  611  
  612      
  613       if(DEB UG) {
  614           Sy stem.out.p rintln("in sertHeader Segment_ST SE() - DON E calling  insertDate ()");
  615       } 
  616     
  617       
  618       
  619       // Ins ert record s into sev eral table s to ident ify the pa yer
  620       insert PayerIdent ification( dbEMStg, d bEMErepos) ;
  621         
  622       // Ins ert a reco rd into ta ble ENTITY _ID to ide ntify the  payee
  623       insert PayeeIdent ification_ N1(dbEMEre pos);
  624       
  625       
  626       // Ins ert a reco rd into ta ble ENTITY _ADTL_ID i dentifying  the
  627       insert PayeeIdent ification_ REF(dbEMEr epos);
  628          
  629       // Ins ert a skel eton recor d into DET AL_HEAD_IN FO, settin g the
  630       //   k ey on the  way
  631       vDtlHe adInfoKey  = insertFa cade.inser tProviderS ummaryLX(v FileNumber , vSt02txn CtlNbrPadd ed, dbEMEr epos);
  632       vSegme ntCount++;
  633  
  634      
  635       if(DEB UG) {
  636           Sy stem.out.p rintln("in sertHeader Segment_ST SE() - DON E calling  () insertP roviderSum maryLX()") ;
  637       }
  638       
  639         
  640       if(DEB UG) {
  641           Sy stem.out.p rintln("in sertHeader Segment_ST SE() - GET TING LIST  OF RECS. F ROM STG_83 5_CLP tabl e");
  642           Sy stem.out.p rintln("pa rams for q ry are - f ileNumber:  " + vFile Number + " , vSt02txn CtlNumberN oPad: " +  vSt02txnCt lNumberNoP ad);
  643       }
  644      
  645       
  646       List c laimPaymen ts = null;  // getCla imPayments Query.getR esultList( );   
  647       
  648                // Get a ll the cla im payment  records f or this tr ansaction   
  649                // CHANG E TO CLASS  TO DAO CL ASS HERE.
  650       // gov .va.med.do main.erepo s.batchloa d
  651       try {
  652                Query ge tClaimPaym entsQuery  = dbEMStg. createQuer y("SELECT  cp"
  653                         + "  FROM  gov.va.med .domain.er epos.Stg83 5Clp cp "
  654                         + "   WHER E cp.fileN umber=?1 A ND cp.st02 txnCtlNbr= ?2");
  655                
  656                getClaim PaymentsQu ery.setPar ameter(1,  vFileNumbe r);
  657                getClaim PaymentsQu ery.setPar ameter(2,  vSt02txnCt lNumberNoP ad);
  658                
  659                claimPay ments = ge tClaimPaym entsQuery. getResultL ist();   
  660                        
  661                if(DEBUG ) {
  662                    Syst em.out.pri ntln("inse rtHeaderSe gment() -  SIZE OF CL P Payments  list is:  " + claimP ayments.si ze());
  663                }
  664       
  665                
  666       }catch (Exception  e) {
  667           Sy stem.out.p rintln("in sertHeader Segment_ST SE() - err or getting  Stg835Clp DAO object s");
  668           e. printStack Trace();
  669       }
  670               
  671        
  672       // get  a referen ce to clai mPayments
  673       Iterat or claimPa ymentItera tor = clai mPayments. iterator() ;
  674  
  675       // Loo p through  the claim  payment re cords
  676       while  (claimPaym entIterato r.hasNext( )) {
  677           
  678   // see if  this class  can be re -written b ased on th e signatur e of the c ompiled ve rsion in t he erepos. jar file i n the lib  dir.             
  679         // c urrent Cla imPayment    
  680         // f inal Stg83 5Clp crStg 835Clp1 =  (Stg835Clp ) claimPay mentIterat or.next();
  681            / / final St g835ClpDAO  crStg835C lp1 = null ;
  682           St g835Clp cr Stg835Clp1  = null;
  683           
  684                     crS tg835Clp1  = (Stg835C lp) claimP aymentIter ator.next( );
  685                     ins ertClaimPa yment_CLP( crStg835Cl p1,dbEMStg , dbEMErep os);
  686                     ins ertClaimAm ount("2100 ", crStg83 5Clp1, dbE MErepos);
  687            
  688         if(D EBUG) {
  689              System.out .println(" insertHead erSegment_ STSE() - i nsertClaim Payment_CL P() DONE") ;
  690         }
  691       }  //  end loop f or each cl aim
  692       
  693       insert PayeeIdent ification_ N3N4(dbEME repos);
  694      
  695       if(DEB UG) {
  696              System.out .println(" insertHead erSegment_ STSE() -   insertPaye eIdentific ation_N3N4 () DONE");
  697       }
  698       
  699       //---- Provider A djustment  (PLB)
  700       insert ProviderAd justment_P LB(dbEMStg , dbEMErep os);
  701      
  702       if(DEB UG) {
  703              System.out .println(" insertHead erSegment_ STSE() -    insertPro viderAdjus tment_PLB( ) DONE");
  704         } 
  705     
  706       
  707       
  708       
  709  
  710       // On  the new tr ansaction  record (ta ble TXN_SE T), set th e count
  711       //   o f segments  we have b een accumu lating, an d the cont rol number
  712       trTxnS et.setSe01 txnSgmtCnt (new BigDe cimal(Inte ger.toStri ng(vSegmen tCount)));
  713       trTxnS et.setSe02 txnCtlNbr( vSt02txnCt lNbrPadded );
  714  
  715       // Ins ert the ne w transact ion record
  716       dbEMEr epos.persi st(trTxnSe t);
  717       vTrans actionCoun t++;
  718  
  719       // Mar k the head er record  for deleti on from st aging
  720       crStg8 35Hdr.setS tseStatus( "DELETE");
  721       dbEMSt g.persist( crStg835Hd r);
  722  
  723       
  724      } // en d method i nsertHeade rSegmentST SE
  725  
  726     
  727           /* *
  728            *  I believe  you will  need to cr eate a rec ord in the  CLAIM_AMO UNT table  with:
  729                    and  AMT01 set  to AU (pg.  182, 183  of spec.) 
  730                    (nam e of new f ield:'Amou nt Qualifi er Code' -  value='AU ')
  731                    and  AMT02 set  to the val ue (Claim_ Level_Allo wed_Amount ) (pg. 182 , 183 of s pec.)
  732                    and  LOOP_ID se t to 2100.
  733  
  734                     clp 13Ref01=AU , clp16Amt 02=1
  735    
  736                     TAB LE                            st g_835_clp  field
  737                     AMT 02AMT                         =c lp16Amt02
  738                     AMT 01AMT_QUAL _CD        =clp13Ref0 1  (NOT NU LL........ ..char(3) 
  739           
  740      * 
  741      * Write  a new Cla imAmount r ecord.
  742        * @author 
D NS     BLACKW
  743      * @sinc e 1/6/2015
  744      * @para m stg835
  745      * @para m dbEMErep os
  746    * @param  claimKey 
  747      */
  748     private  void inser tClaimAmou nt(String  loopId, St g835Clp st g835, Enti tyManager  dbEMErepos ) {
  749           bo olean DEBU G = true;
  750           fi nal String  TX_TYPE =  "835";
  751           fi nal String  CREATED_B Y = "E_REP OS";
  752           fi nal java.s ql.Date NO W = new ja va.sql.Dat e(new java .util.Date ().getTime ());
  753           fi nal BigDec imal SEQ_N BR= new Bi gDecimal(" 1");
  754           St ring vClai mKey = "";
  755           St ring Clp16 Amt02 = "" ;
  756           St ring Clp13 Ref01 = "" ;
  757   //      St ring amt01 amtQualCd  = "XX";                                                                          // req uired, EMP TY FOR MOS T RECORDS  - DEFAULT  VALUE WILL  TRIGGER 8 35 OUTPUT? ??
  758           Bi gDecimal a mt02 = new  BigDecima l("0");
  759           
  760           //  all exist ing record s are null  for this  REQUIRED f ield
  761           //  check bas e and DAO  classes fo r property  locattion
  762            i f( (stg835 .getClp16A mt02() !=  null) ) {
  763                                                
  764                     //  NO NULLS -  all exist ing record s are null  for this  REQUIRED f ield
  765                              if( ( stg835.get Clp13Ref01 () != null ) && (stg8 35.getClp1 3Ref01().l ength() <  4 ) ) {
  766                                       
  767                                       final C laimAmount  crClaimAm ount = new  ClaimAmou nt();
  768                                       crClaim Amount.set Amt01amtQu alCd(stg83 5.getClp13 Ref01());        
  769                                  c rClaimAmou nt.setTxTy pe(TX_TYPE );                                                                                                            // REQUIRE D
  770                                  c rClaimAmou nt.setLoop Id(loopId) ;
  771                                  c rClaimAmou nt.setCrea tedBy(CREA TED_BY);
  772                                  c rClaimAmou nt.setDate Created(NO W);
  773                                  c rClaimAmou nt.setSeqN br(SEQ_NBR );                                                                                                            // REQUIRE D
  774                                  c rClaimAmou nt.setClai mAmountKey (UUID.rand omUUID().t oString(). toUpperCas e());                 // REQUIRE D
  775                                  v ClaimKey =  stg835.ge tClaimKey( );           
  776                                 
  777                                  Q uery getCl aimQuery =  dbEMErepo s.createQu ery("SELEC T c FROM g ov.va.med. domain.ere pos.Claim  c WHERE c. claimKey=? 1");
  778                                  g etClaimQue ry.setPara meter(1, v ClaimKey);
  779                             
  780                                  L ist claimL ist = getC laimQuery. getResultL ist();
  781                                  I terator cl aimIterato r = claimL ist.iterat or();
  782                             
  783                                          if ( claimItera tor.hasNex t()) {
  784                                               final Clai m rowClaim  = (Claim)  claimIter ator.next( );
  785                                               crClaimAmo unt.setCla im(rowClai m);
  786                                               crClaimAmo unt.setSub scriberInf o(rowClaim .getSubscr iberInfo() );
  787                                          }
  788                              
  789                                                   
  790                                       
  791                                  t ry {
  792                                       dbEMEre pos.persis t(crClaimA mount);
  793                                  } catch(Exce ption e) {
  794                                       System. out.printl n("insertC laimAmount () - ERROR : " + e.ge tMessage() );
  795                                       e.print StackTrace ();
  796                                  }
  797                                  
  798                                  
  799                                  i f(DEBUG) {
  800                                       System. out.printl n("insertC laimAmount  DONE");
  801                                       
  802                                  }
  803  
  804                                  
  805                              } //  end null c heck
  806                              
  807               } // end  null check                 
  808                                  
  809      }    //  end inser tClaimAmou nt()
  810  
  811      /**
  812           "I  believe y ou will ne ed to crea te a recor d in the E NTITY_ADTL _ID table:
  813                    with  the TX_TY PE set to  835 
  814                    and  the REF01  set to BB 
  815                    and  REF02 set  with the a uthorizati on number  (authoriza tionNumber )"
  816  
  817      * @para m stg835
  818      * @para m dbEMErep os
  819      * @para m loopId
  820      */
  821     
  822     // to do  - add ref erence to  EntityAdtl Id class t o CLAIM_PA YMENT_INFO  classs
  823     // see i f we can p ull the va lue out of  that OR p ass in the  immediate  value
  824     // of Cl aimPayment Info here  and see if  we can ge t it (alre ady tried  and failed )
  825     /**
  826      * From  AJ:
  827      * 
  828   First crea te the Cla imPymtInfo  object, t hen once t he EntityA dtlId obje ct is crea ted associ ate 
  829   that with  the ClaimP ymtInfo ob ject then  when those  are persi sted the c orrect key s will be  inserted.   
  830   To associa te the two  objects,  use the Cl aimPymtInf o. getEnti tyAdtlIds( ) method,  that will  return a s et 
  831   of EntityA dtlIds, ad d the new  EntityAdtl Ids to the  Set and H ibernate w ill handle  the rest 
  832   when they’ re persist ed.
  833  
  834    
  835      */
  836     
  837     /**
  838       public  EntityAdt lId insert EntityAdtl Id(String  loopId, St g835Clp st g835, Enti tyManager  dbEMErepos ) {
  839                    bool ean DEBUG  = true;
  840                    fina l String T X_TYPE = " 835";
  841                    fina l String C REATED_BY  = "E_REPOS ";
  842                    fina l java.sql .Date NOW  = new java .sql.Date( new java.u til.Date() .getTime() );
  843                    fina l BigDecim al SEQ_NBR = new BigD ecimal("1" );
  844                    // C laim vars
  845                    Stri ng cClaimK ey="";
  846                    Stri ng cFileNu m="";
  847                    Stri ng cStx02= "";
  848                    
  849                    // E ntityName  vars
  850                    Stri ng enKey=" ";
  851                    Enti tyNameDAO  enRow = nu ll;
  852                    Stri ng enFileN br = "";
  853                    Stri ng cpiKey= "";
  854           
  855           
  856                final En tityAdtlId  entityAdt lId = new  EntityAdtl Id();
  857                // entit yAdtlId.
  858            / / still do esn't work  with clai mKey fro s tg835 OR c laim...... ...
  859                    // g et a zilli on foreign  keys..... ...
  860                    enti tyAdtlId.s etClaimKey (cClaimKey );
  861                    // e ntityAdtlI d.setClaim PymtInfoKe y(cpiKey);
  862                    
  863                    
  864                    enti tyAdtlId.s etRefSegKe y(UUID.ran domUUID(). toString() .toUpperCa se()); 
  865                entityAd tlId.setTx Type(TX_TY PE);
  866                entityAd tlId.setFi leNumber(s tg835.getF ileNumber( ));
  867                   
  868                entityAd tlId.setCr eatedBy(CR EATED_BY);
  869                entityAd tlId.setDa teCreated( NOW);
  870                entityAd tlId.setLo opId(loopI d);
  871                entityAd tlId.setSe qNbr(SEQ_N BR);
  872                entityAd tlId.setRe f01idQlfr( stg835.get Clp15Amt01 ());         // NEW F IELD
  873                entityAd tlId.setRe f02scndId( stg835.get Clp14Ref02 ());         // NEW F IELD
  874                
  875                     
  876                dbEMErep os.persist (entityAdt lId);
  877        }  //  end inser tEeaID()
  878     
  879    **/ 
  880     
  881     // Inser t informat ion for on e claim pa yment, inc luding ser vice lines
  882     // to tw o new reco rds....... .....
  883     // this  is called  from:inser tHeaderSeg ment()
  884     // 
  885     private  void inser tClaimPaym ent_CLP(fi nal Stg835 Clp crStg8 35Clp1, En tityManage r dbEMStg,  EntityMan ager dbEME repos)
  886     throws S QLExceptio n
  887     {
  888  
  889           bo olean DEBU G = true;   
  890       // Ser vice line  records ar e linked t o claim pa yments ove r column c lp_key
  891       vStgCl pKey = crS tg835Clp1. getClpKey( );
  892       vClaim Key  = crS tg835Clp1. getClaimKe y(); 
  893     
  894   /**    
  895       if(DEB UG) {
  896           Sy stem.out.p rintln("in sertClaimP ayment_CLP () - vStgC lpKey is:  " + vStgCl pKey + ",  vClaimKey  is: " + vC laimKey);
  897       }
  898   **/
  899       
  900       
  901       
  902       v837Fi leNumber =  "";
  903       v837St 02txnCtlNb r = "";
  904       v837Sb srId = "";
  905       v837Bi llHrchlKey  = "";
  906       v837Sb srHrchlKey  = "";
  907    
  908   if(DEBUG)  {
  909           Sy stem.out.p rintln("in sertClaimP ayment_CLP () - Claim PaymentKey  is: " + v StgClpKey) ;
  910           Sy stem.out.p rintln("in sertClaimP ayment_CLP () - Claim Key is: "  + vClaimKe y);
  911   }
  912  
  913  
  914       Query  getClaimQu ery = 
  915                    dbEM Erepos.cre ateNativeQ uery("SELE CT * FROM  CLAIM WHER E CLAIM_KE Y=?1 ", Cl aim.class) ;
  916       
  917       
  918           ge tClaimQuer y.setParam eter(1, vC laimKey);
  919           
  920                    List  claim = g etClaimQue ry.getResu ltList();
  921                    Iter ator claim Iterator =  claim.ite rator();
  922                    Clai m rowClaim  = null;
  923                    
  924                    
  925                    if ( claimItera tor.hasNex t()) {
  926                             rowCla im = (Clai m) claimIt erator.nex t();                          
  927                    }
  928  
  929                    if ( rowClaim ! = null) {
  930                             v837Fi leNumber =  rowClaim. getFileNum ber();
  931                             v837St 02txnCtlNb r = rowCla im.getSt02 txnCtlNbr( );
  932                             v837Sb srId = row Claim.getS ubscriberI d();
  933                             v837Bi llHrchlKey  = rowClai m.getBilli ngHrchlLev elKey();
  934                             v837Sb srHrchlKey  = rowClai m.getSubsc riberHrchl LevelKey() ;
  935                    }
  936     
  937                // Get a ll the cla im adjustm ent record s at the c laim payme nt level,
  938                //   for  the curre nt claim p ayment
  939                    //Sr eedhar - C hanges mad e for CR 1 3902
  940                    
  941                    if(D EBUG) {
  942                             System .out.print ln("gettin g Stg835Cl pCas recor ds......") ;
  943                    }
  944                    
  945                    
  946                Query ge tClaimAdjS egQuery =  dbEMStg.cr eateQuery( "SELECT ad j"
  947                         + "  FROM  gov.va.med .domain.er epos.Stg83 5ClpCas ad j "
  948                         + "   WHER E adj.clpK ey=?1 ");
  949                getClaim AdjSegQuer y.setParam eter(1, vS tgClpKey);
  950                
  951                if(DEBUG ) {
  952                             System .out.print ln("run qu ery for St g835ClpCas  records.. ....");
  953                    }
  954                
  955                List cla imAdjSeg =  null;
  956                
  957                try {
  958                    clai mAdjSeg =  getClaimAd jSegQuery. getResultL ist();  
  959                }catch(E xception e x) {
  960                    Syst em.out.pri ntln("inse rtClaimPay ment_CLP()  - ERROR w ith StgClp Cas query" );
  961                    ex.p rintStackT race();
  962                }
  963                        
  964                Iterator  claimAdjS egIterator  = claimAd jSeg.itera tor();
  965  
  966                String v PayerClmCo de = "1";
  967  
  968                // Loop  through th e claim ad justments  to the cur rent claim  payment
  969                while (c laimAdjSeg Iterator.h asNext())  {
  970                  final  Stg835ClpC as vStg835 ClpCas = ( Stg835ClpC as) claimA djSegItera tor.next() ;
  971                  
  972                           
  973                  if (vS tg835ClpCa s.getCas02 clmAdjRsn1 ().equalsI gnoreCase( "23")) 
  974                  {
  975                      vP ayerClmCod e = "2";
  976                  }
  977  
  978                  
  979                  if ((v Stg835ClpC as.getCas0 5clmAdjRsn 2() != nul l) && (vSt g835ClpCas .getCas05c lmAdjRsn2( ).equalsIg noreCase(" 23")))
  980                  {
  981                      vP ayerClmCod e = "2";
  982                  }
  983                  
  984                  if ((v Stg835ClpC as.getCas0 8clmAdjRsn 3() != nul l) && (vSt g835ClpCas .getCas08c lmAdjRsn3( ).equalsIg noreCase(" 23")))
  985                  {
  986                      vP ayerClmCod e = "2";
  987                  }
  988                  
  989                  if ((v Stg835ClpC as.getCas1 1clmAdjRsn 4() != nul l) && (vSt g835ClpCas .getCas11c lmAdjRsn4( ).equalsIg noreCase(" 23")))
  990                  {
  991                      vP ayerClmCod e = "2";
  992                  }
  993                  
  994                  if ((v Stg835ClpC as.getCas1 4clmAdjRsn 5() != nul l) && (vSt g835ClpCas .getCas14c lmAdjRsn5( ).equalsIg noreCase(" 23")))
  995                  {
  996                      vP ayerClmCod e = "2";
  997                  }
  998                  
  999                  if ((v Stg835ClpC as.getCas1 7clmAdjRsn 6() != nul l) && (vSt g835ClpCas .getCas17c lmAdjRsn6( ).equalsIg noreCase(" 23")))
  1000                  {
  1001                      vP ayerClmCod e = "2";
  1002                  }
  1003                  
  1004                  
  1005                }
  1006                    
  1007       // Ins ert a reco rd for the  claim pay ment, sett ing the ke y on the w ay
  1008       vClpKe y = insert Facade.ins ertClaimPy mtInfo(crS tg835Clp1,  rowClaim
  1009              , vFileNum ber, vSt02 txnCtlNbrP added, vDt lHeadInfoK ey, vPayer ClmCode, d bEMErepos) ;// end ch anges for  CR 13902
  1010       
  1011        
  1012       
  1013       
  1014       vClaim Date = crS tg835Clp1. getClaimDa te();
  1015       vSegme ntCount++;
  1016  
  1017       // Ins ert adjust ment recor ds at the  claim paym ent level
  1018       insert ClaimAdjus tmants_CAS (dbEMStg,d bEMErepos) ;
  1019  
  1020       if(DEB UG) {
  1021           Sy stem.out.p rintln("in sertClaimP ayment_CLP () - inser tClaimAdju stmants()  DONE");
  1022       }
  1023       
  1024       // Ins ert a reco rd in tabl e ENTITY_N AME to hol d the Pati ent Name
  1025       insert Names_NM1( "QC", dbEM Stg,dbEMEr epos);
  1026  
  1027       if(DEB UG) {
  1028           Sy stem.out.p rintln("in sertClaimP ayment_CLP () - inser tNames_NM1 () DONE");
  1029       }
  1030       
  1031       
  1032       
  1033       // Ser vice Provi der (NM1):   HAC and  FEE have d ifferent
  1034       //     methods du e to a dif ficiency i n how the  service
  1035       //     provider i s set in F EE.
  1036       // If  the payer  is FEE, we  need a mo re complic ated metho d
  1037       //   o f setting  the provid er name
  1038       /*if ( "12115".eq uals(vPaye rId) || "1 2116".equa ls(vPayerI d)) {
  1039           in sertFeePro viderName_ NM1(crStg8 35Clp1.get ClaimKey() , dbEMStg, dbEMErepos );
  1040       } else  {
  1041           in sertNames_ NM1("82",  dbEMStg,db EMErepos);
  1042       }*/
  1043       
  1044       insert ServicePro viderName_ NM1(crStg8 35Clp1.get ClaimKey() , dbEMStg, dbEMErepos );
  1045       if(DEB UG) {
  1046           Sy stem.out.p rintln("in sertClaimP ayment_CLP () - inser tServicePr oviderName _NM1() DON E");
  1047       }
  1048        
  1049       //Sree dhar - Cha nges made  for CR 139 04
  1050  
  1051       String  v837Claim Type = "";
  1052       String  vBillType  = "";
  1053       BigDec imal v837C lm02Amt =  new BigDec imal("0");
  1054       BigDec imal v835C lp03Amt =  new BigDec imal("0");
  1055       
  1056       if (ro wClaim !=  null) {
  1057           v8 37ClaimTyp e = rowCla im.getClai mType();
  1058           vB illType =  rowClaim.g etClm05fcl yTypeCd();
  1059           v8 37Clm02Amt  = rowClai m.getClm02 clmChrgAmt ();
  1060           v8 35Clp03Amt  = crStg83 5Clp1.getC lp03clmChr gAmt();
  1061       }
  1062       
  1063       if (v8 35Clp03Amt .longValue () < v837C lm02Amt.lo ngValue())  {    
  1064                if (((v8 37ClaimTyp e.substrin g(0, 10).e qualsIgnor eCase("005 010X223"))  ||
  1065                   (v837 ClaimType. equalsIgno reCase("00 4010X096A1 "))) &&
  1066                   ((vBi llType.equ alsIgnoreC ase("11"))  || (vBill Type.equal sIgnoreCas e("21")) | |
  1067                    (vBi llType.equ alsIgnoreC ase("28"))  || (vBill Type.equal sIgnoreCas e("41")) | |
  1068                    (vBi llType.equ alsIgnoreC ase("65"))  || (vBill Type.equal sIgnoreCas e("66")) | |
  1069                    (vBi llType.equ alsIgnoreC ase("86")) )) {
  1070                    
  1071                    inse rtFacade.i nsertInpat ientAdjId_ MIA(vClpKe y, dbEMEre pos);
  1072                 } else  {
  1073                    inse rtFacade.i nsertOutpa tientAdjId _MOA(vClpK ey, dbEMEr epos); 
  1074                 }
  1075        }
  1076       
  1077       // Cla im Date
  1078       insert Facade.ins ertDate
  1079           (n ull, null,  vClpKey,  vSvcKey, " 050", vCla imDate, db EMErepos);
  1080       vSegme ntCount++;
  1081  
  1082       // Cla im Supplem ental Amou nt (AMT) i s only ins erted if t here is in terest,
  1083       //   w hich there  never is  as of this  writing
  1084       final  int numCla imAmountsI nserted =  insertFaca de.insertC laimSuplAm ountAMT
  1085           (v ClpKey, vI ntAmt, dbE MErepos);
  1086       vSegme ntCount +=  numClaimA mountsInse rted;
  1087  
  1088       if(DEB UG) {
  1089           Sy stem.out.p rintln("in sertClaimP ayment() -  insertCla imSuplAmou ntAMT() -  DONE");
  1090           Sy stem.out.p rintln("in sertClaimP ayment() -  WRITING S ERVICE LIN ES - vStgC lpKey is:  " + vStgCl pKey);
  1091        }
  1092        
  1093                                 Qu ery getSvc RecordsQue ry = dbEMS tg.createQ uery("SELE CT svc"
  1094                                          + "   FROM gov. va.med.dom ain.erepos .Stg835Svc  svc "
  1095                                          + "    WHERE sv c.clpKey=? 1 ");
  1096                                 ge tSvcRecord sQuery.set Parameter( 1, vStgClp Key);
  1097                                 
  1098                                 Li st svcReco rds = null ;
  1099                                 
  1100                                      svcRecor ds = getSv cRecordsQu ery.getRes ultList();  
  1101                                 It erator svc RecordsIte rator = sv cRecords.i terator();
  1102                             
  1103                               
  1104                                 wh ile (svcRe cordsItera tor.hasNex t()) {
  1105                                    final Stg8 35Svc crSt g835Svc =  (Stg835Svc ) svcRecor dsIterator .next();
  1106                             
  1107                                    insertServ iceLine_SV C(crStg835 Svc, dbEMS tg, dbEMEr epos);
  1108                                   
  1109                                 }  // end loo p for each  service l ine
  1110                                 
  1111      
  1112       
  1113       
  1114       vClpKe y = "";
  1115       vSvcKe y = "";
  1116  
  1117       // Mar k the clai m payment  record for  deletion  from stagi ng
  1118       //TWP: NEED TO CO NVERT & SA VE BC$J fi gures this  out not J PA
  1119       crStg8 35Clp1.set ClpStatus( "DELETE");
  1120       
  1121       
  1122       dbEMSt g.persist( crStg835Cl p1);
  1123       
  1124      } // en d method i nsertClaim Payment_CL P
  1125  
  1126   // Insert  informatio n for one  service li ne
  1127     private  void inser tServiceLi ne_SVC(fin al Stg835S vc crStg83 5Svc, Enti tyManager  dbEMStg, E ntityManag er dbEMEre pos)
  1128     throws S QLExceptio n
  1129     {
  1130       vStgSv cKey = crS tg835Svc.g etSvcKey() ;
  1131  
  1132       boolea n DEBUG =  true;
  1133       
  1134       // Ins ert a reco rd for the  service,  while sett ing the ke y for the  service li ne
  1135       vSvcKe y = insert Facade.ins ertSvcPymt Info(crStg 835Svc , v ClpKey, db EMErepos);
  1136       vSegme ntCount++;
  1137  
  1138       // Ins ert a reco rd for the  service d ate (type  472) or th e start an d
  1139       //   e nd of the  service pe riod
  1140       final  String vSv cDtQual =  crStg835Sv c.getDtm01 ddtmQual() ;
  1141       if ("4 72".equals (vSvcDtQua l)) {
  1142         inse rtFacade.i nsertDate
  1143              (null, nul l, vClpKey , vSvcKey,
  1144                vSvcDtQu al, crStg8 35Svc.getD tm01dtFld( ), dbEMEre pos);
  1145         vSeg mentCount+ +;
  1146       } else  {
  1147         inse rtFacade.i nsertDate
  1148              (null, nul l, vClpKey , vSvcKey,
  1149                vSvcDtQu al, crStg8 35Svc.getD tm01dtFld( ), dbEMEre pos);
  1150         vSeg mentCount+ +;
  1151  
  1152         inse rtFacade.i nsertDate
  1153              (null, nul l, vClpKey , vSvcKey,
  1154                crStg835 Svc.getDtm 02ddtmQual (), crStg8 35Svc.getD tm02dtFld( ), dbEMEre pos);
  1155         vSeg mentCount+ +;
  1156       }
  1157  
  1158       // Ins ert the li ne control  number us ed by the  provider,  if we have  one
  1159       if (cr Stg835Svc. getRef02ad tlId() !=  null) {
  1160         inse rtFacade.i nsertSegme ntREF(vFil eNumber,
  1161              vSt02txnCt lNbrPadded , vClpKey,  vSvcKey,  "6R",
  1162              crStg835Sv c.getRef02 adtlId(),  "2110", db EMErepos);
  1163         vSeg mentCount+ +;
  1164       }
  1165  
  1166       // Ins ert the Se rvice Leve l Renderin g Provider  ID
  1167       if (cr Stg835Svc. getSvcRefR enderingPr ovId() !=  null) {
  1168         inse rtFacade.i nsertSegme ntREF(vFil eNumber,
  1169              vSt02txnCt lNbrPadded , vClpKey,  vSvcKey,  "HPI",
  1170              crStg835Sv c.getSvcRe fRendering ProvId(),  "2110", db EMErepos);
  1171         vSeg mentCount+ +;
  1172       }
  1173  
  1174       // Ins ert Servic e Suppleme ntal Amoun t
  1175       if (cr Stg835Svc. getSvcAllo wedAmt() ! = null) {
  1176         inse rtFacade.i nsertServi ceSuplAmou ntAMT(vClp Key, vSvcK ey, "B6",
  1177              crStg835Sv c.getSvcAl lowedAmt() , "2110",  dbEMErepos );
  1178         vSeg mentCount+ +;
  1179       }
  1180  
  1181       // Ins ert adjust ments at t he service  level
  1182       insert ServiceLev elAdjustme nts_CAS(db EMStg,dbEM Erepos);
  1183  
  1184       // Ins ert Health  Care Rema rk Codes ( LQ)
  1185       insert HealthCare RemarkCode s_LQ(dbEMS tg,dbEMEre pos);
  1186  
  1187       vSvcKe y = "";
  1188  
  1189       // Mar k the serv ice line r ecord for  deletion f rom stagin g
  1190       crStg8 35Svc.setS vcStatus(" DELETE");
  1191       
  1192       
  1193       if(DEB UG) {
  1194           Sy stem.out.p rintln("Pr ocessERepo s835Load.i nsertServi ceLine() -  persistin g to dbEMS tg");
  1195       }
  1196      
  1197       dbEMSt g.persist( crStg835Sv c);
  1198       
  1199       if(DEB UG) {
  1200           Sy stem.out.p rintln("Pr ocessERepo s835Load.i nsertServi ceLine() -  DONE pers isting to  dbEMStg");
  1201       }
  1202       
  1203       
  1204     } // end  method in sertServic eLine_SVC
  1205  
  1206     // Inser t a record  into ERep os table T RACE_NUMBE R for the  current tr ansaction
  1207     private  void inser tTraceNumb ers_TRN(En tityManage r dbEMStg,  EntityMan ager dbEME repos)
  1208     //throws  Exception
  1209     {
  1210         // G et the tra ce number  records fr om staging  for the c urrent tra nsaction       
  1211         Quer y getTrace NumberQuer y = dbEMSt g.createQu ery("SELEC T trn"
  1212                  + "  F ROM gov.va .med.domai n.erepos.S tg835HdrTr n trn "
  1213                  + "    WHERE trn. fileNumber =?1 AND tr n.st02txnC tlNbr=?2") ;
  1214         getT raceNumber Query.setP arameter(1 , vFileNum ber);
  1215         getT raceNumber Query.setP arameter(2 , vSt02txn CtlNumberN oPad);
  1216        
  1217         List  traceNumb ers = getT raceNumber Query.getR esultList( ); 
  1218         Iter ator trace NumberIter ator = tra ceNumbers. iterator() ;
  1219  
  1220         // L oop throug h the stag ed trace n umber reco rds
  1221         // T ODO: There  seem to n ever be mo re than on e, which m akes sense
  1222         //    Maybe we  should che ck this as  a precond ition?
  1223         whil e (traceNu mberIterat or.hasNext ()) {
  1224              final Stg8 35HdrTrn c rStg835Hdr Trn = (Stg 835HdrTrn)  traceNumb erIterator .next();
  1225              vSegmentCo unt++;
  1226  
  1227              insertFaca de.insertT raceNumber (crStg835H drTrn,
  1228                    vFil eNumber, v St02txnCtl NbrPadded,  vPayerId,  dbEMErepo s);
  1229              vProdDate  = crStg835 HdrTrn.get ProdDate() ;
  1230  
  1231         }  / / -- end l oop while
  1232         
  1233     }     //  end inser tTraceNumb ers_TRN()
  1234  
  1235     // Creat e rows in  several ta bles that  identify t he payer
  1236     private  void inser tPayerIden tification (EntityMan ager dbEMS tg, Entity Manager db EMErepos)
  1237     throws S QLExceptio n, BadInpu tDataExcep tion
  1238     {
  1239       // Get  the appli cable row  from table  STG_835_P AYER_INFO
  1240       Query  getPayerIn foQuery =  dbEMStg.cr eateQuery( "SELECT in f "
  1241                + "  FRO M gov.va.m ed.domain. erepos.Stg 835PayerIn fo inf "
  1242                + "   WH ERE inf.id .payerId=? 1 AND inf. id.facilit yId=?2");
  1243       getPay erInfoQuer y.setParam eter(1, vP ayerId);
  1244       getPay erInfoQuer y.setParam eter(2, vF acilityId) ;   
  1245       List p ayerInfos  = getPayer InfoQuery. getResultL ist(); 
  1246    
  1247       Query  getPayerIn foQueryBus  = dbEMStg .createQue ry("SELECT  inf "
  1248                + "  FRO M gov.va.m ed.domain. erepos.Stg 835PayerIn fo inf "
  1249                + "   WH ERE inf.id .payerId=? 1 AND inf. id.facilit yId=?2");     
  1250       getPay erInfoQuer yBus.setPa rameter(1,  "12345");
  1251       getPay erInfoQuer yBus.setPa rameter(2,  "0");   
  1252       List p ayerInfosB us = getPa yerInfoQue ryBus.getR esultList( ); 
  1253       
  1254       // Not e: As of t his writin g, there a re no mult iples in t he data
  1255       Stg835 PayerInfo  crStg835Pa yerInfo =  null;
  1256       Stg835 PayerInfo  crStg835Pa yerInfoBus  = null;
  1257       if(pay erInfos.si ze() > 0)
  1258       {
  1259           cr Stg835Paye rInfo = (S tg835Payer Info) paye rInfos.get (0);
  1260       }
  1261       // If  no payer i nfo record s were fou nd in stag ing, log i t and erro r out
  1262       if (cr Stg835Paye rInfo == n ull) {
  1263         Syst em.out.pri ntln("inse rtPayerIde ntificatio n() - Coul dn't find  the Payer  Informatio n in STG_8 35_PAYER_I NFO table  for the fo llowing Vi sin Id: "  + vFacilit yId);
  1264          
  1265         thro w new BadI nputDataEx ception();
  1266  
  1267       // If  we found a  payer inf o record i n staging,  insert ro ws in seve ral tables
  1268       } else  {
  1269         // I nsert a ro w into ENT ITY_ID
  1270         inse rtFacade.i nsertEntit yId(vFileN umber, vSt 02txnCtlNb rPadded,
  1271              crStg835Pa yerInfo.ge tPayerName (), "1000A ", "PR", n ull, null,  dbEMErepo s);
  1272         vSeg mentCount+ +;
  1273  
  1274         // I nsert a ro w into ENT ITY_ADDRES S
  1275         inse rtFacade.i nsertEntit yAddress(c rStg835Pay erInfo, vF ileNumber,  vSt02txnC tlNbrPadde d, dbEMEre pos);
  1276         vSeg mentCount+ +;
  1277  
  1278         // B usiness Co ntact Info rmation
  1279         // I n order to  write a c ontact rec ord for th is payer,  we need at  least one
  1280         //    of contac t name, ph one number , or fax n umber
  1281  
  1282         if(p ayerInfosB us.size()  > 0)
  1283         {
  1284           cr Stg835Paye rInfoBus =  (Stg835Pa yerInfo) p ayerInfosB us.get(0);
  1285         }
  1286         
  1287         Stri ng cntcNam e = crStg8 35PayerInf oBus.getPa yerContact ();
  1288         Stri ng phoneNu m = crStg8 35PayerInf oBus.getPa yerPhone() ;
  1289         Stri ng eMail    = crStg83 5PayerInfo Bus.getPay erEmail();
  1290  
  1291         if ( (!((cntcNa me == null ) || (cntc Name.equal s("")))) | |
  1292                  (!((ph oneNum ==  null) || ( phoneNum.e quals("")) )) ||
  1293                  (!((eM ail == nul l)   || (e Mail.equal s("")))))  {
  1294  
  1295   // If we g ot one of  those, cre ate a new  row for ta ble CNTC_I NFO
  1296           in sertFacade .insertCon tactInfoBu s(vFileNum ber, vSt02 txnCtlNbrP added
  1297              , cntcName , phoneNum , eMail, d bEMErepos) ;
  1298           vS egmentCoun t++;
  1299         }
  1300  
  1301                //Techni cal Contac t Informat ion
  1302                // In or der to wri te a conta ct record  for this p ayer, we n eed at lea st one
  1303                //   of  contact na me, phone  number, or  fax numbe r
  1304                cntcName  = crStg83 5PayerInfo .getPayerC ontact();
  1305                phoneNum  = crStg83 5PayerInfo .getPayerP hone();
  1306                eMail    = crStg835 PayerInfo. getPayerEm ail();
  1307           
  1308                if ((!(( cntcName = = null) ||  (cntcName .equals("" )))) ||
  1309                         (!((phoneN um == null ) || (phon eNum.equal s("")))) | |
  1310                         (!((eMail  == null)    || (eMail .equals("" ))))) {
  1311           
  1312                  // If  we got one  of those,  create a  new row fo r table CN TC_INFO
  1313                  insert Facade.ins ertContact Info(vFile Number, vS t02txnCtlN brPadded
  1314                    , cn tcName, ph oneNum, eM ail, dbEME repos);
  1315                  vSegme ntCount++;                 
  1316         }
  1317       }
  1318     } // end  method in sertPayerI dentificat ion
  1319  
  1320     // Inser t a row in  table ENT ITY_ID to  identify t he payee
  1321     private  void inser tPayeeIden tification _N1(Entity Manager db EMErepos)
  1322     throws S QLExceptio n
  1323     {
  1324       // Dec ide on the  code and  qualifier  before cal ling the i nsert meth od
  1325       String  n103IdCdQ ual = null ;
  1326       String  n104IdCd  = null;
  1327  
  1328       // Cur rently we  require th e tax id t o process  claims.  S o
  1329       // dur ing the NP I transiti on if we g et only on e id then  it has
  1330       // to  be the TIN  stored in  vProvider Id (atypic al provide rs such as
  1331       // HUM ANA which  are not el igible for  NPI's). I F They sen d an NPI
  1332       // the n that goe s in the N 104 segmen t and the  TIN goes i n the REF  segment
  1333       if(vPr oviderNpi  == null) {
  1334         // c heck becau se some of  the pre N PI era pro viderId co lumns can  contain
  1335         // b oth NPI or  TIN
  1336         if ( vProviderI d.length()  > 9) {
  1337           n1 03IdCdQual  = "XX";
  1338         } el se {
  1339           n1 03IdCdQual  = "FI";
  1340         }
  1341         n104 IdCd = vPr oviderId;
  1342       } else  {
  1343         n103 IdCdQual =  "XX";
  1344         n104 IdCd = vPr oviderNpi;
  1345       }
  1346  
  1347       // Ins ert the ro w
  1348       insert Facade.ins ertEntityI d(vFileNum ber, vSt02 txnCtlNbrP added
  1349           ,v PayeeName,  "1000B",  "PE", n103 IdCdQual,  n104IdCd,  dbEMErepos );
  1350       vSegme ntCount++;
  1351       
  1352     } // end  method in sertPayeeI dentificat ionN1
  1353  
  1354     //
  1355     private  void inser tPayeeIden tification _REF(Entit yManager d bEMErepos)
  1356     throws S QLExceptio n
  1357     {
  1358       // TOD O: What do es this co mment mean ?
  1359       // If  both the N PI and Tin  were sent  then the  TIN goes
  1360       // in  the REF se gment of t he 1000B ( ENTITY_ADT L_ID table ).
  1361        if (v ProviderNp i != null)  {
  1362          ins ertFacade. insertSegm entREF(vFi leNumber,  vSt02txnCt lNbrPadded ,
  1363                vClpKey,  vSvcKey,  "TJ", vPro viderId, " 1000B", db EMErepos);
  1364          vSe gmentCount ++;
  1365        }
  1366     } // end  method in sertPayeeI dentificat ionRef
  1367  
  1368     //
  1369     private  void inser tPayeeIden tification _N3N4(Enti tyManager  dbEMErepos )
  1370     throws S QLExceptio n
  1371     {  
  1372                Query ge tEntityAdd ressQuery 
  1373                    dbEM Erepos.cre ateNativeQ uery("SELE CT *"
  1374                         + "  FROM  ENTITY_ADD RESS "
  1375                         + "  WHERE  (FILE_NUM BER = ?1 "
  1376                         + "  AND S T02TXN_CTL _NBR = ?2  "
  1377                         + "  AND N M109BILL_P RVD_ID = ? 3 "
  1378                         + "  AND L OOP_ID = ? 4) "
  1379                         + "  OR (H RCHL_LEVEL _KEY = ?5) ", EntityA ddressDAO. class);
  1380                    getE ntityAddre ssQuery.se tParameter (1, v837Fi leNumber);
  1381                    getE ntityAddre ssQuery.se tParameter (2, v837St 02txnCtlNb r);
  1382                    if ( vProviderN pi != null ){
  1383                             getEnt ityAddress Query.setP arameter(3 , vProvide rNpi);
  1384                    } el se {
  1385                             getEnt ityAddress Query.setP arameter(3 , vProvide rId);
  1386                    }
  1387                    
  1388                    getE ntityAddre ssQuery.se tParameter (4, "2010A A");
  1389                    getE ntityAddre ssQuery.se tParameter (5, v837Bi llHrchlKey );
  1390                    List  entityAdd resss = ge tEntityAdd ressQuery. getResultL ist();
  1391                    Iter ator entit yAddressIt erator = e ntityAddre sss.iterat or();
  1392  
  1393                    Enti tyAddressD AO rowEnti tyAddress8 37 = null;
  1394                    if ( entityAddr essIterato r.hasNext( )) {
  1395                             rowEnt ityAddress 837 = (Ent ityAddress DAO) entit yAddressIt erator.nex t();                    
  1396                    }
  1397                    
  1398                    // i n the N3 a nd N4 segm ents for 1 000B (ENTI TY_ADDRESS  table).
  1399                    if ( rowEntityA ddress837  != null) {
  1400                          insertFac ade.insert EntityAddr ess(rowEnt ityAddress 837, vFile Number, vS t02txnCtlN brPadded,  dbEMErepos );
  1401                          vSegmentC ount++; // N3 Count
  1402                          vSegmentC ount++; // N4 Count
  1403                    } 
  1404                    else  if (vFile Number.sub string(0,  3).equalsI gnoreCase( "SXC")) {
  1405                             Query  getTPQuery  = 
  1406                             dbEMEr epos.creat eNativeQue ry("SELECT  *"
  1407                                 +  "  FROM TR ADING_PART NERS "
  1408                                 +  "  WHERE A BBREV_TAG  = ?1 ", Tr adingPartn ers.class) ;
  1409                         getTPQuery .setParame ter(1, "SX C");
  1410                    
  1411                             List t radingPart ners = get TPQuery.ge tResultLis t();
  1412                             Iterat or trading PartnersIt erator = t radingPart ners.itera tor();
  1413                    
  1414                             Tradin gPartners  rowTrading Partners =  null;
  1415                             if (tr adingPartn ersIterato r.hasNext( )) {
  1416                                      rowTradi ngPartners  = (Tradin gPartners)  tradingPa rtnersIter ator.next( );                   
  1417                             }
  1418                             
  1419                             if (ro wTradingPa rtners !=  null) {
  1420                                  i nsertFacad e.insertEn tityAddres s(rowTradi ngPartners , vFileNum ber, vSt02 txnCtlNbrP added, dbE MErepos);
  1421                                  v SegmentCou nt++; //N3  Count
  1422                                  v SegmentCou nt++; //N4  Count
  1423                             }                         
  1424                             
  1425                             
  1426                     }
  1427        
  1428     } // end  method in sertPayeeI dentificat ionRef
  1429     
  1430     // Inser t adjustme nt records  at the cl aim paymen t level
  1431     private  void inser tClaimAdju stmants_CA S(EntityMa nager dbEM Stg, Entit yManager d bEMErepos)
  1432     throws S QLExceptio n
  1433     {
  1434       // Get  all the c laim adjus tment reco rds at the  claim pay ment level ,
  1435       //   f or the cur rent claim  payment
  1436       Query  getClaimAd justmentsQ uery = dbE MStg.creat eQuery("SE LECT adj"
  1437                + "  FRO M gov.va.m ed.domain. erepos.Stg 835ClpCas  adj "
  1438                + "   WH ERE adj.cl pKey=?1 ") ;
  1439       getCla imAdjustme ntsQuery.s etParamete r(1, vStgC lpKey);
  1440       
  1441       List c laimAdjust ments = ge tClaimAdju stmentsQue ry.getResu ltList();    
  1442       Iterat or claimAd justmentIt erator = c laimAdjust ments.iter ator();
  1443  
  1444       int cl aimCasesSe qNbr = 0;
  1445  
  1446       // Loo p through  the claim  adjustment s to the c urrent cla im payment
  1447       while  (claimAdju stmentIter ator.hasNe xt()) {
  1448         vSeg mentCount+ +;
  1449         clai mCasesSeqN br++;
  1450         fina l Stg835Cl pCas crStg 835ClpCas  = (Stg835C lpCas) cla imAdjustme ntIterator .next();
  1451  
  1452         // O nly do thi s if a cla im adjustm ent group  is present
  1453         // T ODO: This  seems to n ever be nu ll, why do  we check?
  1454         if ( crStg835Cl pCas != nu ll && crSt g835ClpCas .getCas01c lmAdjGrp()  != null & &
  1455                      !( crStg835Cl pCas.getCa s03adjAmt1 ().equals( new BigDec imal(0))))  {
  1456              insertFaca de.insertC laimAdjust ment(crStg 835ClpCas
  1457                  , vClp Key, claim CasesSeqNb r, dbEMEre pos);
  1458         }
  1459       }
  1460  
  1461     } // end  method in sertClaimA djustmantC AS
  1462  
  1463     // Inser t a new re cord into  table ENTI TY_NAME, c oming from  table STG _835_NAME,
  1464     //   wit h the type  of name c oming in a s a parame ter
  1465     private  void inser tNames_NM1 (final Str ing vQual,  EntityMan ager dbEMS tg, Entity Manager db EMErepos)
  1466     throws S QLExceptio n
  1467     {
  1468       // Get  the recor d from STG _835_CLP_N AME for th is claim p ayment and  the
  1469       //   g iven quali fier  
  1470       Query  getNameQue ry = dbEMS tg.createQ uery("SELE CT name"
  1471                + "  FRO M gov.va.m ed.domain. erepos.Stg 835ClpName  name "
  1472                + "   WH ERE name.c lpKey=?1 A ND name.nm 101entyIdC d=?2");
  1473       getNam eQuery.set Parameter( 1, vStgClp Key);
  1474       getNam eQuery.set Parameter( 2, vQual);
  1475       
  1476       List n ames = get NameQuery. getResultL ist();   
  1477       Iterat or nameIte rator = na mes.iterat or();    
  1478       // Loo p through  the result s, creatin g a record  in the ta rget for e ach one
  1479       while  (nameItera tor.hasNex t()) {
  1480           fi nal Stg835 ClpName cr Stg835ClpN ame = (Stg 835ClpName ) nameIter ator.next( );
  1481           in sertFacade .insertEnt ityNameFro mStaging(c rStg835Clp Name
  1482                , vFileN umber, vCl pKey, vSt0 2txnCtlNbr Padded, db EMErepos);
  1483           vS egmentCoun t++;
  1484       }
  1485  
  1486     } // end  method in sertNameNM 1
  1487  
  1488     /**
  1489      *  This  method, l ike the in serNameNM1 , method p opulates t he EntityN ame
  1490      *  tabl e for 835  Service Pr ovider Nam e segment.   But for  FEE, and u nlike
  1491      *  the  HAC CPS, t he informa tion retur ned from t he FEE CPS  is incorr ect
  1492      *  and  needs to b e gathered  from the  informatio n sent in  the 837 in stead
  1493      *  of t he informa tion sent  in from th e CPS.
  1494      *
  1495      *  @par am claimKe y the clai m key used  to look u p the Serv ice Provid er
  1496      *          name.
  1497      */
  1498     // This  method rea ds info fr om ENTITY_ NAME that  came in on  the 837,  and
  1499     //   cre ates anoth er record  in the sam e table, l inked to c laim_pymt_ info,
  1500     //   tha t is, used  in creati ng the 835  going out .
  1501     private  void inser tServicePr oviderName _NM1(final  String cl aimKey, En tityManage r dbEMStg,  EntityMan ager dbEME repos)
  1502     throws S QLExceptio n
  1503     {
  1504       // Get  the recor d from tab le ENTITY_ NAME, fill ed by the  837 proces s,
  1505       //   t hat holds  physician  name infor mation for  the claim  with the  given key
  1506                    //En tityName e ntityNameT oReturn =  null;
  1507                    
  1508                    //TW P:REMEDIAT ED FOR PER FORMANCE
  1509   //               Quer y getEntit yNameQuery  = 
  1510   //               dbEM Erepos.cre ateQuery(" SELECT en"
  1511   //                    + "  FROM  gov.va.med .domain.er epos.batch load.Entit yNameDAO e n "
  1512   //                    + "   WHER E  en.clai m.claimKey =?1 AND en .loopId=?2  AND en.nm 101entyIdC d IN (?3)" );
  1513           
  1514                Query ge tEntityNam eQuery = 
  1515                    dbEM Erepos.cre ateNativeQ uery("SELE CT *"
  1516                         + "  FROM  ENTITY_NAM E "
  1517                         + "   WHER E  CLAIM_K EY=?1 AND  LOOP_ID IN  (?2,?3) A ND NM101EN TY_ID_CD=? 4", Entity NameDAO.cl ass);
  1518                    getE ntityNameQ uery.setPa rameter(1,  claimKey) ;
  1519                    getE ntityNameQ uery.setPa rameter(2,  "2310B");
  1520                    getE ntityNameQ uery.setPa rameter(3,  "2310D");
  1521                    //St ring [] co des = {"72 ","82"};
  1522                    //ge tEntityNam eQuery.set Parameter( 3, codes);
  1523                    getE ntityNameQ uery.setPa rameter(4,  "82");
  1524                    List  entityNam es = getEn tityNameQu ery.getRes ultList();
  1525                    Iter ator entit yNameItera tor = enti tyNames.it erator();
  1526                    //St ring vDate  = null;
  1527                    Enti tyNameDAO  rowEntityN ame = null ;
  1528                    if ( entityName Iterator.h asNext())  {
  1529                             rowEnt ityName =  (EntityNam eDAO) enti tyNameIter ator.next( );
  1530                    }
  1531  
  1532       // If  one was fo und, inser t a new re cord into  the same t able, link ed to
  1533       //   t he new cla im payment  record
  1534       // Man ual merge:  9-23-08 h ead change
  1535       //if ( rowEntityN ame != nul l) {
  1536       if (ro wEntityNam e != null
  1537         && v alidRender ingProvide rId(rowEnt ityName.ge tNm108idCd Qual(), ro wEntityNam e.getNm109 idCd())) {
  1538       // End  manual me rge
  1539         inse rtFacade.i nsertEntit yNameFromE Repos(rowE ntityName,
  1540              vFileNumbe r, vClpKey , vSt02txn CtlNbrPadd ed, dbEMEr epos);
  1541         vSeg mentCount+ +;
  1542       }
  1543       
  1544       
  1545           Qu ery getCla imDtQuery 
  1546                    dbEM Erepos.cre ateNativeQ uery("SELE CT * "
  1547                         + "  FROM  CLAIM_DT "
  1548                         + "   WHER E  CLAIM_K EY=?1 AND  DTP01DTTM_ QUAL=?2 ",  ClaimDtDA O.class);
  1549           ge tClaimDtQu ery.setPar ameter(1,  claimKey);
  1550           ge tClaimDtQu ery.setPar ameter(2,  "434");
  1551  
  1552           Li st claimDt l = getCla imDtQuery. getResultL ist();
  1553           It erator cla imDtIterat or = claim Dtl.iterat or();
  1554           // String vDa te = null;
  1555           Cl aimDtDAO r owClaimDt  = null;
  1556           if  (claimDtI terator.ha sNext()) {
  1557                    rowC laimDt = ( ClaimDtDAO ) claimDtI terator.ne xt();
  1558           }     
  1559    
  1560       if (ro wClaimDt ! = null) {
  1561           St ring vStmt Date = row ClaimDt.ge tDtp03dtFl d();
  1562           
  1563           if  (rowClaim Dt.getDtp0 2dttmFmtQu al().equal sIgnoreCas e("D8"))
  1564           {
  1565                // Claim  Date
  1566                insertFa cade.inser tDate
  1567                    (nul l, null, v ClpKey, vS vcKey, "23 2", vStmtD ate, dbEME repos);                     
  1568           }   
  1569           el se if (row ClaimDt.ge tDtp02dttm FmtQual(). equalsIgno reCase("RD 8"))
  1570           {
  1571                insertFa cade.inser tDate
  1572                    (nul l, null, v ClpKey, vS vcKey, "23 2", vStmtD ate.substr ing(0,8),  dbEMErepos );
  1573                vSegment Count++;
  1574                
  1575                insertFa cade.inser tDate
  1576                    (nul l, null, v ClpKey, vS vcKey, "23 3", vStmtD ate.substr ing(9), db EMErepos);   
  1577           }
  1578  
  1579         vSeg mentCount+ +;
  1580       }
  1581       
  1582     } // end  method in sertFeePro vNameNM1
  1583  
  1584     
  1585     // Inser t claim ad justments  at the ser vice line  level
  1586     private  void inser tServiceLe velAdjustm ents_CAS(E ntityManag er dbEMStg , EntityMa nager dbEM Erepos)
  1587     throws S QLExceptio n
  1588     {
  1589       // Get  the claim  adjustmen ts for the  current s ervice lin e
  1590       Query  getCalimAd justmentsQ uery = dbE MStg.creat eQuery("SE LECT adj"
  1591                + "  FRO M gov.va.m ed.domain. erepos.Stg 835SvcCas  adj "
  1592                + "   WH ERE adj.sv cKey=?1 AN D adj.clpK ey=?2 ");
  1593       getCal imAdjustme ntsQuery.s etParamete r(1, vStgS vcKey);
  1594       getCal imAdjustme ntsQuery.s etParamete r(2, vStgC lpKey);
  1595       
  1596       List c laimAdjust ments = ge tCalimAdju stmentsQue ry.getResu ltList();    
  1597       Iterat or claimAd justmentIt erator = c laimAdjust ments.iter ator();
  1598       
  1599       int se rviceCases SeqNbr = 0 ;
  1600  
  1601       // Loo p through  the claim  adjustment s
  1602       while  (claimAdju stmentIter ator.hasNe xt()) {
  1603         vSeg mentCount+ +;
  1604         serv iceCasesSe qNbr++;
  1605         fina l Stg835Sv cCas crStg 835SvcCas  = (Stg835S vcCas) cla imAdjustme ntIterator .next();
  1606         // O nly do thi s if a cla im adjustm ent group  is present
  1607         if (  crStg835S vcCas.getC as01clmAdj Grp() != n ull &&
  1608           !( crStg835Sv cCas.getCa s03adjAmt1 ().equals( new BigDec imal(0))))  {
  1609           in sertFacade .insertSer viceLevelA djustment( crStg835Sv cCas,
  1610                vClpKey,  vSvcKey,  serviceCas esSeqNbr,  dbEMErepos );
  1611         }
  1612       }
  1613     } // end  method in sertServic eLevelAdju stmentsCAS
  1614  
  1615     // Inser t records  into table  HCARE_REM ARK_CD
  1616     private  void inser tHealthCar eRemarkCod es_LQ(Enti tyManager  dbEMStg, E ntityManag er dbEMEre pos)
  1617     throws S QLExceptio n
  1618     {
  1619       // Get  the recor ds from ST G_835_SVC_ LQ for thi s service  line
  1620       Query  getSvcReco rdsQuery =  dbEMStg.c reateQuery ("SELECT r "
  1621                + "  FRO M gov.va.m ed.domain. erepos.Stg 835SvcLq r  "
  1622                + "   WH ERE r.svcK ey=?1 AND  r.clpKey=? 2 ");
  1623       getSvc RecordsQue ry.setPara meter(1, v StgSvcKey) ;
  1624       getSvc RecordsQue ry.setPara meter(2, v StgClpKey) ;
  1625       
  1626       List s vcRecords  = getSvcRe cordsQuery .getResult List();   
  1627       Iterat or svcReco rdsIterato r = svcRec ords.itera tor();
  1628       int re markCodesS eqNbr = 0;
  1629  
  1630       // Loo p through  the result s
  1631       while  (svcRecord sIterator. hasNext())  {
  1632         vSeg mentCount+ +;
  1633         rema rkCodesSeq Nbr++;
  1634         fina l Stg835Sv cLq crStg8 35SvcLq =  (Stg835Svc Lq) svcRec ordsIterat or.next();
  1635         // O nly do thi s if both  a qualifie r and rema rk code ar e present
  1636         if (   ( crStg8 35SvcLq.ge tLq01cdQua l() != nul l ) &&
  1637                  ( crSt g835SvcLq. getLq02rmk Cd() != nu ll )  ) {
  1638  
  1639           //  Insert a  row into H CARE_REMAR K_CD
  1640           in sertFacade .insertHca reRemarkCd (crStg835S vcLq,
  1641                  vSvcKe y, remarkC odesSeqNbr , dbEMErep os);
  1642         }
  1643       }
  1644     } // end  method in sertHealth CareRemark CodesLQ
  1645  
  1646     // Inser t a single  row into  table PRV_ ADJ, which  represent s an adjus tment
  1647     //   at  the provid er level
  1648     private  void inser tProviderA djustment_ PLB(Entity Manager db EMStg, Ent ityManager  dbEMErepo s)
  1649     throws S QLExceptio n
  1650     {
  1651         // G et the rec ord from S TG_835_PLB  for this  transactio n
  1652         // ( There shou ld always  be exactly  one.)       
  1653         Quer y getAdjIn foQuery =  dbEMStg.cr eateQuery( "SELECT pl b"
  1654                  + "  F ROM gov.va .med.domai n.erepos.S tg835Plb p lb "
  1655                  + "    WHERE plb. fileNumber =?1 AND pl b.st02txnC tlNbr=?2 A ND plb.plb 04prvdAdjA mt<>?3");
  1656         getA djInfoQuer y.setParam eter(1, vF ileNumber) ;
  1657         getA djInfoQuer y.setParam eter(2, vS t02txnCtlN umberNoPad );
  1658         getA djInfoQuer y.setParam eter(3, ne w BigDecim al(0));
  1659        
  1660         List  adjInfos  = getAdjIn foQuery.ge tResultLis t(); 
  1661         Stg8 35Plb crSt g835Plb =  null;
  1662       
  1663         if(a djInfos.si ze()>0)
  1664         {
  1665              crStg835Pl b = (Stg83 5Plb) adjI nfos.get(0 );
  1666  
  1667              // Insert  a row into  table PRV _ADJ 
  1668              //5010: Th is is now  a conditio nal segmen t
  1669              //we are n ot inserti ng rows wi th 0 in th em.
  1670              insertFaca de.insertP roviderAdj ustment(vF ileNumber,
  1671                  vSt02t xnCtlNbrPa dded, crSt g835Plb, d bEMErepos) ;
  1672              vSegmentCo unt++;
  1673         }
  1674               
  1675         
  1676  
  1677     } // end  method in sertProvid erAdjustme ntPLB
  1678  
  1679     /**
  1680      * For t he file nu mber curre ntly store d in vFile Number, co nvert all  the
  1681      *   pro cedure cod es from th e old XCOD E standard
  1682      * The s trategy is  to match  back to th e Claim ta ble (fille d before t he data
  1683      *   pas sed throug h Cache/Mu mps) accor ding to th e charge a mount on t he service  line.
  1684      * If a  single mat ch is foun d, use the  procedure  code in o ne of the  three
  1685      *   sub sidiary ta bles for s ervice lin es.
  1686      * If un able to ma tch becaus e a claim  has multip le lines w ith the sa me charge
  1687      *   amo unt, try t o convert  the XCODE  through ou r table.
  1688      * If th at doesn't  work, giv e up and m ark it as  an error.
  1689      *
  1690      * @thro ws java.la ng.Excepti on
  1691      */
  1692     private  void conve rtProcCode (EntityMan ager dbEMS tg, Entity Manager db EMErepos)
  1693     throws B adInputDat aException , DbTransa ctionEnder Exception
  1694     {
  1695       try {
  1696         Stri ng tProcCo de = "";
  1697         int  numConvert edNormally  = 0;
  1698         int  numConvert edThroughX CodeTable  = 0;
  1699         int  numErrors  = 0;
  1700  
  1701         // W ere all th e service  lines prec essable fo r the curr ent claim  payment?
  1702         bool ean allSvc Clear = tr ue;
  1703  
  1704         // W ere all th e claim pa yments pro cessable f or the cur rent heade r?
  1705         bool ean allClp Clear = tr ue;
  1706  
  1707         // G et all the  header re cords for  this files et that ar e in NEW s tatus
  1708                    Quer y getNewHe adersQuery  = dbEMStg .createNat iveQuery(" SELECT * F ROM STG_83 5_HDR " +
  1709                                       " WHERE  STSE_STAT US = ?1 AN D FILE_NUM BER = ?2 "  + 
  1710                                       testTra nsactionRe strictionC lause +
  1711                                       " ORDER  BY TO_NUM BER(ST02TX N_CTL_NBR) ", Stg835H dr.class ) ;                               
  1712                    getN ewHeadersQ uery.setPa rameter(1, "NEW");
  1713                    getN ewHeadersQ uery.setPa rameter(2, vFileNumbe r);
  1714                    List  newHeader s = getNew HeadersQue ry.getResu ltList();
  1715                    Iter ator newHe aderIterat or = newHe aders.iter ator();
  1716  
  1717              int header Counter =  0;
  1718         whil e (newHead erIterator .hasNext() ) {
  1719              headerCoun ter++;           
  1720              if(headerC ounter % 2 00 == 0)
  1721              {
  1722                      
  1723                      db EMStg.flus h();
  1724                      db EMErepos.f lush();
  1725                      db EMErepos.c lear();
  1726              }
  1727             
  1728           fi nal Stg835 Hdr  crStg 835HdrA =  (Stg835Hdr ) newHeade rIterator. next();
  1729           
  1730           //  Get all t he new cla im payment  records f or the cur rent files et
  1731           //    and tra nsaction
  1732           vS t02txnCtlN brPadded =  crStg835H drA.getSt0 2txnCtlNbr ();
  1733  
  1734   // START H ERE....... .........         
  1735           Qu ery getNew ClaimPayme ntsQuery =  dbEMStg.c reateQuery ("SELECT c p"
  1736                    + "   FROM gov. va.med.dom ain.erepos .Stg835Clp  cp "
  1737                    + "    WHERE cp .fileNumbe r=?1 AND c p.st02txnC tlNbr=?2 A ND cp.clpS tatus=?3") ;
  1738           
  1739           
  1740           ge tNewClaimP aymentsQue ry.setPara meter(1, v FileNumber );                            //  AND IF TH IS IS EMPT Y?
  1741           ge tNewClaimP aymentsQue ry.setPara meter(2, v St02txnCtl NbrPadded) ;          // WHERE D OES THIS C OME FROM?
  1742           ge tNewClaimP aymentsQue ry.setPara meter(3, " NEW");
  1743           
  1744           Li st newClai mPayments  = getNewCl aimPayment sQuery.get ResultList ();    
  1745           It erator new ClaimPayme ntsIterato r = newCla imPayments .iterator( );             
  1746           
  1747           
  1748           //  Loop thro ugh the cl aim paymen t records
  1749           wh ile (newCl aimPayment sIterator. hasNext())  {
  1750             
  1751             
  1752              final Stg8 35Clp crSt g835ClpA =  (Stg835Cl p) newClai mPaymentsI terator.ne xt();
  1753              vClpKey =  crStg835Cl pA.getClpK ey();
  1754              vClaimKey  = crStg835 ClpA.getCl aimKey();
  1755             
  1756              // Get all  the servi ce lines f or the giv en claim p ayment           
  1757              Query getS erviceLine sForClaimP aymentQuer y = dbEMSt g.createQu ery("SELEC T sl"
  1758                      +  "  FROM go v.va.med.d omain.erep os.Stg835S vc sl "
  1759                      +  "   WHERE  sl.clpKey= ?1 AND sl. svcStatus= ?2");
  1760              getService LinesForCl aimPayment Query.setP arameter(1 , vClpKey) ;
  1761              getService LinesForCl aimPayment Query.setP arameter(2 , "NEW");
  1762             
  1763              List servi ceLinesFor ClaimPayme nt = getSe rviceLines ForClaimPa ymentQuery .getResult List();     
  1764              Iterator s erviceLine sForClaimP aymentIter ator = ser viceLinesF orClaimPay ment.itera tor();
  1765             
  1766              // Loop th rough the  service li nes
  1767              while (ser viceLinesF orClaimPay mentIterat or.hasNext ()) {
  1768                final St g835Svc cr Stg835SvcA  = (Stg835 Svc) servi ceLinesFor ClaimPayme ntIterator .next();
  1769                tProcCod e = crStg8 35SvcA.get Svc01procC d();
  1770                
  1771                // If th is service  line's pr ocedure co de starts  with X,
  1772                //   it  needs to b e converte d
  1773                if (tPro cCode.subs tring(0, 1 ).equalsIg noreCase(" X")) {
  1774                  String  transacti onType      = "";
  1775                  String  vRevCode     = null;
  1776                  String  vMedCode     = null;
  1777                  boolea n convertT hroughXCod eTable = f alse;
  1778  
  1779                  // Get  the claim  to which  this claim  payment r ecord is l inked
  1780                  // TOD O:  Can't  this be do ne once pe r claim pa yment,
  1781                  //   o utside of  the servic e line loo p?
  1782                               
  1783                  Query  getClaimFo rPaymentQu ery = dbEM Erepos.cre ateQuery(" select cl  from gov.v a.med.doma in.erepos. Claim cl w here cl.cl aimKey=?1" );
  1784                  getCla imForPayme ntQuery.se tParameter (1, vClaim Key);
  1785                  
  1786                  List c laimsForPa yment = ge tClaimForP aymentQuer y.getResul tList();     
  1787                  Iterat or claimsF orPaymentI terator =  claimsForP ayment.ite rator();
  1788  
  1789                  if (cl aimsForPay mentIterat or.hasNext ()) {
  1790                      Cl aim claimF orPayment  = (Claim)  claimsForP aymentIter ator.next( );
  1791                      tr ansactionT ype = clai mForPaymen t.getClaim Type();
  1792                  } else
  1793                  {
  1794                    // T here are a  small num ber of sit uations wh ere a CLAI M_KEY in
  1795                    //    STG_835_C LP does no t correspo nd to any  in table C LAIM.
  1796                    // I n such a s ituation,  transactio nType will  be left b lank.
  1797                    // W e want to  go to the  XCODE conv ersion tab le.
  1798                    // S etting tra nsactionTy pe will sk ip the thr ee followi ng queries , and
  1799                    //    setting c onvertThro ughXCodeTa ble will c ause the X CODE table
  1800                    //    to be use d
  1801                    tran sactionTyp e = "Claim  Not Found ";
  1802                    conv ertThrough XCodeTable  = true;
  1803                  }
  1804  
  1805                  // For  instituti onal claim s, look at  the entri es in
  1806                  //   I NST_SVC_LI NE, matchi ng by this  service l ine's amou nt
  1807                  if ((t ransaction Type.equal sIgnoreCas e("004010X 096A1")) |
  1808                      (t ransaction Type.subst ring(0, 10 ).equalsIg noreCase(" 005010X223 "))) {
  1809                    
  1810                    //TW P:REMEDIAT E - ? we l oad 1 tabl e at a tim e and tric k hibernat e by using  transient  in the co nfig file
  1811                    // s o associat ed object  do not get  stored as  null - th is prevent s us from  querying . claim.clai mKey since  claim is  transient.
  1812                      
  1813   //               Quer y getInsti tutionalSe rviceLineA mountQuery  = dbEMEre pos.create Query("sel ect svclin e "
  1814   //                            +  "  FROM go v.va.med.d omain.erep os.InstSvc Line svcli ne "
  1815   //                            +  "   WHERE  svcline.cl aim.claimK ey=?1 AND  svcline.sv 203lnItmCh rg=?2");
  1816                      
  1817                    Quer y getInsti tutionalSe rviceLineA mountQuery  = dbEMEre pos.create NativeQuer y("select  * FROM "
  1818                             + "  I NST_SVC_LI NE  WHERE  CLAIM_KEY= ?1 AND SV2 03LN_ITM_C HRG=?2", I nstSvcLine .class);
  1819                    getI nstitution alServiceL ineAmountQ uery.setPa rameter(1,  vClaimKey );
  1820                    getI nstitution alServiceL ineAmountQ uery.setPa rameter(2,  crStg835S vcA.getSvc 02chrgAmt( ));
  1821                    trac eLOGGER.de bug(" getI nstitution alServiceL ineAmountQ uery claim  key:" + v ClaimKey);
  1822                    List  instituti onalServic eLineAmoun ts = getIn stitutiona lServiceLi neAmountQu ery.getRes ultList();     
  1823                    Iter ator insti tutionalSe rviceLineA mountItera tor = inst itutionalS erviceLine Amounts.it erator();
  1824  
  1825                    // I f there is  only one  institutio nal servic e
  1826                    //    for this  amount, us e its code s
  1827                    fina l int inst itutionalS erviceLine sCount = i nstitution alServiceL ineAmounts .size();
  1828                    if ( institutio nalService LinesCount  == 1) {
  1829                         final Inst SvcLine ro wInstSvcLi ne = (Inst SvcLine) i nstitution alServiceL ineAmountI terator.ne xt();
  1830                         vRevCode =  rowInstSv cLine.getS v201svcLnR evCd();
  1831                         vMedCode =  rowInstSv cLine.getS v202procCd ();
  1832  
  1833                    // I f there ar e more tha n one, con vert throu gh the XCO DE table
  1834                    } el se {
  1835                      co nvertThrou ghXCodeTab le = true;
  1836                    }
  1837  
  1838                  // For  dental cl aims, look  at the en tries in
  1839                  //   D ENTAL_SVC_ LINE for t his servic e line's a mount
  1840                  } else  if ((tran sactionTyp e.equalsIg noreCase(" 004010X097 A1")) || 
  1841                               (tra nsactionTy pe.substri ng(0, 10). equalsIgno reCase("00 5010X224") )) {                                       
  1842                    
  1843                    //TW P:REMEDIAT E - ? we l oad 1 tabl e at a tim e and tric k hibernat e by using  transient  in the co nfig file
  1844                    // s o associat ed object  do not get  stored as  null - th is prevent s us from  querying . claim.clai mKey since  claim is  transient.
  1845                      
  1846   //                 Qu ery getDen talService LineAmount Query = db EMErepos.c reateQuery ("SELECT d s"
  1847   //                        + "  F ROM gov.va .med.domai n.erepos.D entalSvcLi ne ds "
  1848   //                        + "    WHERE ds.c laim.claim Key=?1 AND  ds.sv302l nItmChrg=? 2");
  1849                      
  1850                      Qu ery getDen talService LineAmount Query = db EMErepos.c reateNativ eQuery("SE LECT * fro m DENTAL_S VC_LINE "  +
  1851                                      "WHERE C LAIM_KEY=? 1 AND SV30 2LN_ITM_CH RG=?2", De ntalSvcLin e.class);
  1852                      ge tDentalSer viceLineAm ountQuery. setParamet er(1, vCla imKey);
  1853                      ge tDentalSer viceLineAm ountQuery. setParamet er(2, crSt g835SvcA.g etSvc02chr gAmt());
  1854                      Li st dentlaS erviceLine Amounts =  getDentalS erviceLine AmountQuer y.getResul tList();     
  1855                      It erator den tlaService LineAmount Iterator =  dentlaSer viceLineAm ounts.iter ator();
  1856                      
  1857                    // I f there is  only one  dental ser vice for t his amount , use its  code
  1858                    if ( dentlaServ iceLineAmo unts.size( ) == 1) {
  1859                         final Dent alSvcLine  rowDentalS vcLine = ( DentalSvcL ine) dentl aServiceLi neAmountIt erator.nex t();
  1860                         vMedCode =  rowDental SvcLine.ge tSv301adaC d();
  1861  
  1862                    // I f there ar e more tha n one, use  the XCode  table
  1863                    } el se {
  1864                         convertThr oughXCodeT able = tru e;
  1865                    }
  1866  
  1867                  // For  professio nal claims , look at  the entrie s in
  1868                  //   P RFSN_SVC_L INE for th is service  line's am ount
  1869                  } else  if ((tran sactionTyp e.equalsIg noreCase(" 004010X098 A1")) || 
  1870                               (tra nsactionTy pe.substri ng(0, 10). equalsIgno reCase("00 5010X222") )) {
  1871  
  1872  
  1873   //                 // TWP:Was no t a join b ut using h ql require d join - R EMEDIATED  for PERFOR MANCE
  1874   //                    Query getI nitialConv ersionCode Query = db EMErepos.c reateQuery ("SELECT p s"
  1875   //                            +  "  FROM go v.va.med.d omain.erep os.PrfsnSv cLine ps "
  1876   //                            +  "   WHERE  ps.claim.c laimKey=?1  AND ps.sv 102lineItm Chrg=?2");
  1877                      
  1878                      Qu ery getIni tialConver sionCodeQu ery = dbEM Erepos.cre ateNativeQ uery("SELE CT *"
  1879                               + "   FROM PRFS N_SVC_LINE  "
  1880                               + "    WHERE CL AIM_KEY=?1  AND SV102 LINE_ITM_C HRG=?2", P rfsnSvcLin e.class);
  1881                      
  1882                      ge tInitialCo nversionCo deQuery.se tParameter (1, vClaim Key);
  1883                      ge tInitialCo nversionCo deQuery.se tParameter (2, crStg8 35SvcA.get Svc02chrgA mt());
  1884                      Li st initial Xcodes = g etInitialC onversionC odeQuery.g etResultLi st();    
  1885                      It erator ini tialXcodes Iterator =  initialXc odes.itera tor();
  1886                     
  1887                      //  If there  is only on e professi onal servi ce for thi s amount,  use it
  1888                      if  (initialX codes.size () == 1) {
  1889                           final Pr fsnSvcLine  rowPrfsnS vcLine = ( PrfsnSvcLi ne) initia lXcodesIte rator.next ();
  1890                           vMedCode  = rowPrfs nSvcLine.g etSv101pro cCd();
  1891  
  1892                      //  If there  are more t han one, u se the XCo de table
  1893                      }  else {
  1894                           convertT hroughXCod eTable = t rue;
  1895                      }
  1896                    }
  1897  
  1898                    // I f more tha n one matc h was foun d, perform  a lookup  into
  1899                    //    our conve rsion tabl e
  1900                    if ( convertThr oughXCodeT able) {
  1901                         crStg835Sv cA.setSvcS tatus(INPR OCESS_STAT US);
  1902   //                      Query ge tConversio nCodeQuery  = dbEMStg .createQue ry("SELECT  xc "
  1903   //                               + "  FROM  gov.va.med .domain.er epos.Stg83 5Xcode xc  "
  1904   //                               + "   WHER E xc.id.xc ode=?1 AND  xc.id.sta tus=?2 ");
  1905  
  1906                         //JPA IS h aving a pr oblem popu lating xco de object  (table has  no PK - o bject only  has 1 fie ld id) 
  1907                         //using th e query co mmented ou t above. T herefore,  I changed  it to use  a native q uery - TWP  
  1908                        
  1909                         Query getC onversionC odeQuery =  dbEMStg.c reateNativ eQuery("SE LECT PROCE DURE_CODE  "
  1910                               + "   FROM STG_ 835_XCODE  WHERE XCOD E=?1 AND S TATUS=?2") ;                   
  1911                         getConvers ionCodeQue ry.setPara meter(1, t ProcCode);
  1912                         getConvers ionCodeQue ry.setPara meter(2, " ACTIVE");
  1913                         List xcode s = getCon versionCod eQuery.get ResultList ();    
  1914                         Iterator x codeIterat or = xcode s.iterator ();
  1915                         if (xcodeI terator.ha sNext()) {
  1916                             final  String crS tg835Xcode  = (String ) xcodeIte rator.next ();
  1917                             crStg8 35SvcA.set Svc01procC d(crStg835 Xcode);
  1918                             numCon vertedThro ughXCodeTa ble += 1;
  1919  
  1920                         // If no m atch was f ound in th e conversi on table,
  1921                         //   mark  the servic e line as  an error
  1922                         } else {
  1923                             allSvc Clear = fa lse;
  1924                             crStg8 35SvcA.set SvcStatus( ERROR_STAT US);
  1925                             hasXCo deError =  true;
  1926                             numErr ors += 1;
  1927                         }
  1928  
  1929                    // I f only one  match was  found in  the subsid iary table s
  1930                    //    for the c urrent cla im amount,  use it to
  1931                    //     set the  procedure  code in th e staging  area
  1932                    } el se {
  1933                      //  A Procedu re Code is  optional  for Inst C laims but  Rev Code i s required  on inboun d.
  1934                      if  (vMedCode  == null)  {
  1935                           crStg835 SvcA.setSv c01procCd( vRevCode);
  1936                           crStg835 SvcA.setSv c01svcIdQu al("NU");
  1937                      }  else {
  1938                           crStg835 SvcA.setSv c01procCd( vMedCode);
  1939                      }
  1940                      cr Stg835SvcA .setSvcSta tus(INPROC ESS_STATUS );
  1941                      nu mConverted Normally + = 1;
  1942                    }
  1943  
  1944                // If th is service  line's pr ocedure co de does no t start
  1945                //   wit h X, we're  done, jus t change i ts status
  1946                } else {
  1947                    crSt g835SvcA.s etSvcStatu s(INPROCES S_STATUS);
  1948                }
  1949                dbEMStg. persist(cr Stg835SvcA );
  1950              } // end o f loop ove r service  lines
  1951  
  1952              // If all  the servic e lines we re process able, the  claim
  1953              //   payme nt record  is process able
  1954              if (allSvc Clear) {
  1955                crStg835 ClpA.setCl pStatus(IN PROCESS_ST ATUS);
  1956  
  1957              // If some  service l ine had an  unconvert able proce dure code,
  1958              //   mark  the claim  payment as  an error
  1959              } else {
  1960                crStg835 ClpA.setCl pStatus(ER ROR_STATUS );
  1961  
  1962                // This  means not  all claim  payments w ere proces sable
  1963                allClpCl ear = fals e;
  1964  
  1965                // Reset  for the n ext servic e line
  1966                allSvcCl ear = true ;
  1967                hasXCode Error = tr ue;
  1968              }           
  1969              dbEMStg.pe rsist(crSt g835ClpA);
  1970           }  // end of  this claim  payment r ecord
  1971  
  1972           //  If all th e claim pa yments wer e processa ble, the h eader
  1973           //    is proc essable
  1974           if  (allClpCl ear) {
  1975              crStg835Hd rA.setStse Status(INP ROCESS_STA TUS);
  1976  
  1977           //  Otherwise , the head er contain s an error
  1978           }  else {
  1979              crStg835Hd rA.setStse Status(ERR OR_STATUS) ;
  1980  
  1981              // Reset f or the nex t claim pa yment
  1982              allClpClea r = true;
  1983              hasXCodeEr ror = true ;
  1984           }
  1985           db EMStg.pers ist(crStg8 35HdrA);
  1986         }
  1987        
  1988         tPro cCode = nu ll;
  1989         Syst em.out.pri ntln("Comm itting the  Staging t ransaction  with the  changed pr ocedure co des at "
  1990                + DateUt il.getCurr entTimeFor matted(DAT E_FORMAT)) ;
  1991         dbEM Stg.getTra nsaction() .commit();
  1992         Syst em.out.pri ntln("Comm it success ful");
  1993         
  1994         dbEM Stg.getTra nsaction() .begin();
  1995         // R eport the  number of  XCodes con verted
  1996         Syst em.out.pri ntln("XCod e conversi on complet ed");
  1997         Syst em.out.pri ntln("XCod e conversi on complet ed");
  1998         Syst em.out.pri ntln("XCod es convert ed normall y: " + num ConvertedN ormally);
  1999         Syst em.out.pri ntln("XCod es convert ed normall y: " + num ConvertedN ormally);
  2000         Syst em.out.pri ntln("XCod es convert ed through  XCode loo kup: "
  2001              + numConve rtedThroug hXCodeTabl e);
  2002         Syst em.out.pri ntln("XCod es convert ed through  XCode loo kup: "
  2003                  + numC onvertedTh roughXCode Table);
  2004         Syst em.out.pri ntln("XCod e conversi on problem s: " + num Errors);
  2005         Syst em.out.pri ntln("XCod e conversi on problem s: " + num Errors);
  2006  
  2007  
  2008       } catc h(Exceptio n ex) {
  2009           Sy stem.out.p rintln("An  exception  occured w hile conve rting proc  codes" +  ex.getMess age());
  2010         Syst em.out.pri ntln("An e xception o ccured whi le convert ing proc c odes" + ex .getMessag e());
  2011         thro w new DbTr ansactionE nderExcept ion(ex);
  2012       }
  2013     } // end  method co nvertProcC ode
  2014  
  2015     // Set i nstance va riables ba ck to blan k strings  in prepara tion for p rocessing
  2016     //   ano ther heade r
  2017     private  void initi alizeHeade rVariables ()
  2018     {
  2019         vSt0 2txnCtlNbr Padded = " ";
  2020         vSt0 2txnCtlNum berNoPad =  "";
  2021         vCla imKey = "" ;
  2022         vDtl HeadInfoKe y = "";
  2023         vClp Key = "";
  2024         vSvc Key = "";
  2025         vStg ClpKey = " ";
  2026         vStg SvcKey = " ";
  2027         vFac ilityId =  "";
  2028         vPro viderId =  "";
  2029         vPro viderNpi =  null;
  2030         vPay eeName  =  "";
  2031         vPro dDate   =  "";
  2032         vCla imDate  =  "";
  2033         vInt Amt = zero BD;
  2034         v837 FileNumber  = "";
  2035         v837 St02txnCtl Nbr = "";
  2036         v837 SbsrId = " ";
  2037         v837 BillHrchlK ey = "";
  2038         v837 SbsrHrchlK ey = "";
  2039     }
  2040  
  2041       /**
  2042        * Tra nslates th e 837 Rend ering prov ider id qu alifier in to a valid
  2043        * 835  Service P rovider id  qualifier .  Valid v alues for  the 837
  2044        * Ren dering pro vider id q ualifier a re "XX", " 24", and " 34"; Advis ed
  2045        * val ues for th e Service  provider a re "XX", a nd "FI".   Inputs of
  2046        * "34 ", and "24 " will ret urn "FI";  and "XX" w ill return  "XX".
  2047        *
  2048        * @pa ram qualif ier 837 Re ndering pr ovider cod e qualifie r.
  2049        *
  2050        * @re turn 835 s ervice pro vider code  qualifier . null if  the input
  2051        *     is other t han "XX",  "34", or " 24".
  2052        */
  2053       public  static St ring trans RenderProv IdQual(fin al String  qualifier)  {
  2054           St ring rtn =  null;
  2055           if  ("XX".equ als(qualif ier)) {
  2056                rtn = qu alifier;
  2057           }  else if (" 24".equals (qualifier ) || "34". equals(qua lifier)) {
  2058                rtn = "F I";
  2059           }
  2060           re turn rtn;
  2061       }
  2062  
  2063       /**
  2064        * Che cks whethe r the valu e in the R endering p rovider Id  is in the
  2065        * val id format  for the gi ven Qualif ier.  "24" , and "34"  qualifier s
  2066        * sho uld contai n TINs, th erefore mu st be 9 di gits.  "XX " qualifie rs
  2067        * sho uld contai n NPIs and  must be 1 0 digits.   Any quali fier other  than
  2068        * "24 ", 34", or  "XX" will  return fa lse.
  2069        *
  2070        * @pa ram idQual ifier  the  837 Rende ring provi der's qual ifier
  2071        * @pa ram id the  837 Rende ring provi ders id
  2072        * @re turn true  if the idQ ualifier i s "24" or  "34" and t he id is n ine digits ; or
  2073        *   i f the idQu alifier is  "XX" and  the id is  ten digits . false ot herwise.
  2074        */
  2075       privat e static b oolean val idRenderin gProviderI d(final St ring idQua lifier, fi nal String  id) {
  2076           //  invalid o n null val ues
  2077           if  (idQualif ier == nul l || id ==  null) {
  2078                return f alse;
  2079           }
  2080  
  2081           //  24 is the  Empoyer's  Identific ation Numb er and 34  is the
  2082           //  Social Se curity Num ber the Id  contained  should be  the 9
  2083           //  digit tax  id.
  2084           if  (("24".eq uals(idQua lifier) ||  "34".equa ls(idQuali fier)) &&  id.matches ("\\d{9}") ) {
  2085                return t rue;
  2086           }
  2087  
  2088           //  XX is the  National  Provider I dentifier  and should  be
  2089           //  a ten dig it id.
  2090           if  ("XX".equ als(idQual ifier) &&  id.matches ("\\d{10}" )) {
  2091                return t rue;
  2092           }
  2093  
  2094           re turn false ;
  2095       }
  2096   }