4. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 7/6/2017 8:32:13 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.

4.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\extract\feeclaimstatus\feeFinal ProcessFee277FlatFileGeneration.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\extract\feeclaimstatus\feeFinal ProcessFee277FlatFileGeneration.java Wed Jul 5 13:05:20 2017 UTC

4.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 3 4784
Changed 2 4
Inserted 0 0
Removed 0 0

4.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

4.4 Active regular expressions

No regular expressions were active.

4.5 Comparison detail

  1   package go v.va.med.h ac.edi.ext ract.feecl aimstatus. feeFinal;
  2  
  3  
  4   import gov .va.med.do main.fppso wner.Claim ;
  5   import gov .va.med.do main.erepo s.Demograp hicInfo;
  6   import gov .va.med.do main.erepo s.EntityNa me;
  7   import gov .va.med.do main.fppso wner.Perso nInfo;
  8   import gov .va.med.ha c.edi.util s.StringUt ils;
  9  
  10   import org .hibernate .ScrollMod e;
  11   import org .hibernate .Scrollabl eResults;
  12   import org .hibernate .Session;
  13   import org .slf4j.Log ger;
  14   import org .slf4j.Log gerFactory ;
  15  
  16   import jav a.io.File;
  17   import jav a.io.FileN otFoundExc eption;
  18   import jav a.io.FileO utputStrea m;
  19   import jav a.io.Print Writer;
  20  
  21   import jav a.math.Big Decimal;
  22  
  23  
  24   import jav a.sql.Conn ection;
  25   import jav a.sql.Prep aredStatem ent;
  26   import jav a.sql.SQLE xception;
  27   import jav a.sql.Time stamp;
  28   // import  java.sql.W rapper;
  29   import jav a.text.Sim pleDateFor mat;
  30  
  31   import jav a.util.Arr ayList;
  32   // import  java.util. Arrays;
  33   import jav a.util.Cal endar;
  34   // import  java.util. Collection ;
  35   import jav a.util.Dat e;
  36   import jav a.util.Gre gorianCale ndar;
  37   // import  java.util. HashSet;
  38   import jav a.util.Ite rator;
  39   import jav a.util.Lis t;
  40  
  41   import jav ax.persist ence.Entit yManager;
  42   import jav ax.persist ence.Entit yTransacti on;
  43   // import  javax.pers istence.Pe rsistenceE xception;
  44   import jav ax.persist ence.Query ;
  45  
  46   /**
  47    *
  48    * HAPE PO R VA DO# 1 18-11-D-10 09, TO#118 -1009-0001 ; HARRIS
  49    *
  50    * @author  Bill Blac kmon
  51    * @versio n R1.0.0
  52    *
  53   */
  54  
  55   class Proc essFee277F latFileGen eration {
  56  
  57           bo olean DEBU G = false;
  58  
  59  
  60       static  final Log ger LOGGER  = LoggerF actory.get Logger( Pr ocessFee27 7FlatFileG eneration. class);
  61  
  62   //TODO: RE SET FOR PR ODUCTION T O 1000
  63       static  final int  BATCH_SIZ E = 1000;
  64       static  final int  MAX_RECOR DS = 5000;                  // U SED FOR TE STING
  65  
  66       privat e static f inal Strin g PAYER_ID  = "VAFEE" ;                       // was V A FEE befo re it was  VAFEE befo re it was  VA FEE.... ...
  67       privat e static f inal Strin g TRADING_ PARTNER_ID  = "VAFNH" ;
  68  
  69       static  final Str ing DEFAUL T_NULL = " ";
  70       static  final Str ing DEFAUL T_ZERO = " 0.00";           // c reated 8/2 2 - per Je ff Neibaue r change r equest
  71       static  final Str ing CRLF =  "\r\n";
  72       static  final Str ing DELIMI TER = "|";
  73       static  final boo lean REQUI RED = true ;
  74       static  final boo lean OPTIO NAL = fals e;
  75  
  76       java.s ql.Timesta mp runTime stamp;
  77       String  hdrRunTim e;
  78  
  79       Entity Manager em ;
  80       boolea n dailyCst at;
  81       boolea n bInClaim  = true;
  82       String  ereposCla imKey = "" ;
  83       String  fileNbr =  "";
  84       String  st02CtlNb r = "";
  85       String  billPrvdI d = "";
  86       String  sbcrId =  "";
  87       String  claimType  = "";
  88       String  statusCd= "";
  89       String  currentDa te = "";
  90       String  currentTi me = "";
  91       
  92       String  strFileTi me = "";
  93  
  94       // B.B . - new va riables fo r fpps cla im class
  95       long c laimKey;
  96       String  ediClaimK ey = "";
  97       String  sClaimKey  = "";
  98       String  statusCod e = "";
  99       String  claimStat usCategory Code="";                                      // holds  F values  for fee pa yment stat us
  100  
  101  
  102       int cl aimsRecord Count = 0;                             // r unning tot al of clai ms in loop  used in b atch proce ssing
  103       int cn t = 0;
  104       int re jCnt = 0;
  105       int ac cCnt = 0;
  106       int cu rFileNumbe r = 0;
  107  
  108       String  sysdateti me = null;
  109       int wr ittenRecor dCount = 0 ;
  110  
  111  
  112       int ba tchUpdateC ount = 0;
  113  
  114  
  115       Paymen tDataExtra ction paym entDataExt raction =  new Paymen tDataExtra ction();
  116  
  117       // mul ti-file gl obal varia bles
  118       File c sFile = nu ll;
  119       String  filePath  = "";
  120  
  121       String  loadType  = null;
  122  
  123   // TEST SI ZES......
  124   // 24 reco rds = file  size of 2 6404
  125   /** FROM S PEC.
  126    * Maximum  single fi le size sh ould not e xceed 500  MB. In oth er words
  127   there can  be multipl e files in  a file gr oup where  each file  in the gro up is less  than or e qual to 50 0 MB,
  128   but the co mbined siz e for the  file group  has no li mitation.
  129    */
  130  
  131   /**
  132    * Change  - 11/15 pe r A.J. Mag dub
  133    * Per AJ  Magdub we  would like  to limit  the CSTAT  file size  to Max Siz e: 150mg &  Cut Off:   130 mg.
  134    * If you  can have a n update t o me on Mo nday 11/19  COB, that  will be f ine.
  135    * It can  be a separ ate instal l package.   We’ll in stall the  regular in stall and  then run t he applica tion.
  136    */
  137       // ORI GINAL VALU ES
  138       
  139           st atic final  long MAX_ FILE_SIZE  = 15000000 0;
  140           st atic final  long CUT_ OFF_FILE_S IZE = 1300 00000;
  141           
  142       // tes t values
  143           /* *
  144           st atic final  long MAX_ FILE_SIZE  = 15000;
  145           st atic final  long CUT_ OFF_FILE_S IZE = 1300 0;
  146           ** /
  147  
  148  
  149           lo ng fileSiz e=0;
  150       long h eaderSize= 0;
  151       long t railerSize =0;
  152       long d etailSize= 0;
  153       long c umulativeD etailSize= 0;
  154       PrintW riter vCsF ile = null ;
  155  
  156       // row  count - i ncremented  at each o utput line  EXCEPT he ader and f ooter - ad ded 6/14/2 013 -
  157       int ro wCount = 2 ;
  158  
  159       // Fil e Group Co unt- Ident ifies the  total numb er of file s within t he file gr oup.
  160       int fi leGroupCou nt=1;                                                             // increme nt with ne w file
  161       // Ide ntifies th e position  of the fi le within  the file g roup. Numb ers must b e consecut ive so tha t the max  sequence n umber equa ls the fil e group co unt.
  162       int fi leGroupSeq uenceNumbe r=0;                                          // incre ment with  each new f ile
  163  
  164       // sta rt days to  look back  from comm and line a rgs
  165       int iL ookBackDay s = 1;
  166       // end  lookback  days from  command li ne args
  167       int iL ookBackEnd Days;
  168  
  169       // Fil e Group ID - Links mu ltiple fil es of the  same type  together i nto one lo ad. All fi les in the  same load  must have  the same  File Group  ID.
  170       String  fileGroup ID="";
  171  
  172       // dat e-time for  updateWri ttenRecord ()
  173       String  updateDat eTime = "" ;
  174  
  175       Connec tion conn;
  176           Pr eparedStat ement pSta tement;
  177  
  178  
  179  
  180            / **
  181              * @author  Bill Black mon
  182              * @since 1 2/3/2013
  183              * Writes l eftover re cords that  were left  over from  batch pro cess
  184              */
  185            p rivate voi d writeOrp hanedRecor ds()  {
  186  
  187  
  188                     boo lean DEBUG  = false;
  189  
  190                     try  {
  191                              pStat ement.exec uteBatch()  ;
  192                              conn. commit();
  193                    }cat ch(Excepti on e) {
  194                                      if(DEBUG ) {
  195                                               System.out .println(" writeOrpha nedRecords () - ERROR  WRITING O RPHAN RECO RDS: " + e .getMessag e());
  196                                      }
  197                                      LOGGER.e rror("writ eOrphanedR ecords() -  error wri ting orpha ned record s");
  198                             LOGGER .error(e.g etMessage( ), e);
  199  
  200                             }
  201            }
  202  
  203  
  204  
  205            / **
  206              * Top leve l method t o setup co nnection f or referen ce through out app... ...test
  207              * @author  Bill Black mon
  208              * @since 1 1/27
  209              * @return  boolean
  210              */
  211            @ SuppressWa rnings("de precation" )
  212           pr ivate void  setupPrep aredStatem ent() {
  213  
  214                    Stri ng sqlInse rt = "inse rt into FP PS_OWNER.S TG_277(CLA IM_INDEX,  CLAIM_STAT US_CD, CRE ATED_BY, D ATE_CREATE D, MODIFIE D_BY, DATE _MODIFIED)  values(?,  ?, ?, ?,  ?,?)";
  215  
  216                    // s et runtime  Timestamp  for inser t statemen t
  217                    this .runTimest amp = new  java.sql.T imestamp(C alendar.ge tInstance( ).getTime( ).getTime( ));
  218  
  219  
  220                    try  {
  221                              Sessi on session  = (Sessio n) em.getD elegate();
  222                              conn  = session. connection ();
  223  
  224                              pStat ement = co nn.prepare Statement( sqlInsert) ;
  225  
  226                              conn. setAutoCom mit(false) ;
  227                     }ca tch (SQLEx ception sq lEx) {
  228                      LO GGER.error ("setupPre paredState ment() sql Exception  - ERROR: "  + sqlEx.g etMessage( ));
  229                     } c atch(Excep tion e) {
  230                              LOGGE R.error("s etupPrepar edStatemen t() Except ion - ERRO R: " + e.g etMessage( ));
  231                     }
  232            }
  233  
  234       /**
  235        * to  do:
  236        * put  header an d footer o n EACH fil e, numberi ng starts  over on ea ch output  file
  237        *
  238        * Cre ates a new  output fi le
  239        * @pa ram filePa th variabl e read fro m command  line args
  240        * @re turn File
  241        */
  242       privat e File cre ateNewOutp utFile(Str ing filePa th) {
  243  
  244            F ile csFile  = null;
  245            
  246            t ry {
  247                     Cal endar cal  = new Greg orianCalen dar();
  248                     Str ing curren tDate = "" ;
  249                     Str ing curren tTime = "" ;
  250                     //  @SuppressW arnings("u nused")
  251                              // ja va.util.Da te date =  cal.getTim e();
  252                     Sim pleDateFor mat transD ate = new  SimpleDate Format("yy yyMMdd");
  253                     Sim pleDateFor mat transT ime = new  SimpleDate Format("HH mmss");
  254  
  255                     cur rentDate =  transDate .format(ca l.getTime( ));
  256                     cur rentTime=t ransTime.f ormat(cal. getTime()) ;
  257                     
  258                     //  create cla ss level v ariable fo r currentD ate + curr entTime to  be used i n writeHDR () for fie ld 4 - cal led strFil eTime
  259                     thi s.strFileT ime = curr entDate +  currentTim e;
  260                     
  261                     //  CHANGED TO  UPPER-CAS E 9/10/201 3
  262                     Str ing fileNa me = curre ntDate + c urrentTime  + "_" +   "VAFEE" +  ".cstat";
  263  
  264                     //  increment  output ite ms.....
  265                     thi s.fileGrou pCount++;
  266                     thi s.fileGrou pSequenceN umber++;
  267  
  268                     csF ile = new  File(fileP ath + file Name);
  269  
  270                     cur FileNumber ++;
  271  
  272            } catch(Exce ption ex)  {
  273                      LO GGER.error ("Error on  createNew OutputFile (), UNABLE  TO CREATE  NEW OUTPU T FILE - C URRENT fil eGroupCoun t is: ",   this.fileG roupCount) ;
  274                      LO GGER.error (ex.getMes sage(), ex );
  275            }
  276  
  277            r eturn csFi le;
  278       }   //  end creat eNewOutput File()
  279  
  280  
  281  
  282  
  283       /**
  284        * @au thor Bill  Blackmon
  285        * @pa ram sender  Id cleari nghouseId
  286        * @pa ram filePa th  path o f output f ile
  287        */
  288       @Suppr essWarning s({ "unuse d", "unche cked" })
  289           fi nal void p rocessClai mStatus(St ring chId,  String fi lePath) {
  290  
  291  
  292           bo olean DEBU G = false;
  293  
  294           tr y {
  295  
  296                    this .filePath  = filePath ;
  297  
  298                this.cnt  = 0;
  299  
  300                Calendar  cal = new  Gregorian Calendar() ;
  301                java.uti l.Date dat e = cal.ge tTime();
  302                SimpleDa teFormat t ransDate =  new Simpl eDateForma t("yyyyMMd d");
  303                SimpleDa teFormat t ransTime =  new Simpl eDateForma t("HHmmss" );
  304  
  305  
  306                SimpleDa teFormat u pdateTrans Date = new  SimpleDat eFormat("y yyy-MM-dd" );
  307                SimpleDa teFormat u pdateTrans Time = new  SimpleDat eFormat("H H:mm");
  308  
  309                // use t his variab le to inse rt into up dateWritte nRecord(). .......... .......
  310                String u pdateTime  = "";
  311  
  312                 // this  is used i n updateWr ittenRecor d() insert  statement
  313                updateDa teTime = n ew SimpleD ateFormat( "yyyy-MM-d d HH:mm:ss ").format( new Date() );    // m ust be :mm  - not :mi
  314  
  315                 // put  single quo tes around  updateDat eTime for  Oracle
  316                final St ring SINGL E_QUOTE =  "'";
  317                updateDa teTime = S INGLE_QUOT E + update DateTime +  SINGLE_QU OTE;
  318  
  319  
  320                // setup  the prepa redStateme nt to be u sed in bat ch updatin g
  321                setupPre paredState ment();
  322  
  323                Session  session =  (Session)  em.getDele gate();
  324  
  325                String q str = "";
  326  
  327                Scrollab leResults  claims = n ull;
  328  
  329  
  330  
  331  
  332                    // g et session  handle
  333                    sess ion = (Ses sion) em.g etDelegate ();
  334  
  335                             // NEW  SQL - 12/ 5
  336                                       String  sqlSelectA ll = " SEL ECT  /*+ I NDEX (c ed i_cliam_ke y_uk1) IND EX (e clai m_idx3) */  c.*   FRO M fpps_own er.claims  c , e_repo s.claim e   " +
  337                                      " WHERE  " +
  338                                      " e.clai m_key = c. edi_claim_ key " +                                                                                     // par am b                                                                                                                // p aram e
  339                                      " and c. claim_stat us_cd = 'C OMPLETE' a nd (sysdat e-c.date_m odified) < = " + this .iLookBack Days + "   and (sysda te-c.date_ modified)  >= " + thi s.iLookBac kEndDays +  " " +
  340                                      " and no t exists ( SELECT 1 F ROM fpps_o wner.stg_2 77 s WHERE  s.claim_i ndex = c.c laim_index  and s.cla im_status_ cd = 'SENT ')";
  341  
  342                                       
  343   if(DEBUG)        {
  344           Sy stem.out.p rintln("pr ocessClaim Status() c md args ar e b: " + t his.iLookB ackDays +  ", e: " +  this.iLook BackEndDay s);
  345           Sy stem.out.p rintln("pr ocessClaim Status() -  generated  SQL is: "  + sqlSele ctAll);
  346           Sy stem.out.p rintln("re turned rec ord count  is: " + ge tAvailable Records()) ;
  347   }
  348                    org. hibernate. Query clai mQuery = s ession.cre ateSQLQuer y(sqlSelec tAll).addE ntity(Clai m.class);
  349                             claims  = claimQu ery.scroll (ScrollMod e.FORWARD_ ONLY);
  350  
  351                 // star t loop for  processin g claims i n the clai ms results et
  352                 if (cla ims != nul l) {
  353  
  354                    this .csFile =  createNewO utputFile( filePath);
  355  
  356                    this .vCsFile =  new Print Writer(new  FileOutpu tStream(cs File));
  357                    
  358                    crea teHdrRec(t his.vCsFil e);
  359                    
  360                    crea tePrimaryD etailRec(c laims, ses sion, this .vCsFile);
  361  
  362                    crea teTrlRec(t his.vCsFil e);
  363  
  364   // clean u p and clos e referenc es
  365                    this .vCsFile.f lush();
  366                    this .vCsFile.c lose();
  367  
  368   // clear s tatement a nd close c onnection
  369                    pSta tement.clo se();
  370                    conn .close();
  371  
  372  
  373                    LOGG ER.info("C laim Statu s File is  Successful ly Created !!!");
  374  
  375  
  376   // END OF  PROCESS
  377   if(DEBUG)  {
  378            g etNow();
  379   }
  380  
  381  
  382                }   // e nd if
  383           }  catch (Exc eption ex)  {
  384                             System .out.print ln("proces sClaimStat us()() - E RROR: " +  ex.getMess age());
  385                             ex.pri ntStackTra ce();
  386                             LOGGER .error("pr ocessClaim Status() -  Unable to  create CS TAT, error ed on Clai m Key: {}" ,  this.cl aimKey);
  387                             LOGGER .error(ex. getMessage (), ex);
  388                             System .exit(1);
  389         }
  390  
  391   }       //  end proce ssClaimSta tus() END  OF APP
  392  
  393       /**
  394        *
  395        * @re turn java. sql.Timest amp for us e in JDBC
  396        * @au thor Bill  Blackmon
  397        * @si nce 11/27/ 2013
  398        */
  399       /**
  400       privat e static j ava.sql.Ti mestamp ge tCurrentTi meStamp()  {
  401           ja va.util.Da te today =  new java. util.Date( );
  402           re turn new j ava.sql.Ti mestamp(to day.getTim e());
  403       }
  404       **/
  405  
  406       /**
  407        * Cal led to upd ate writte n record a fter it ha s been wri tten
  408        * usi ng non-Hib ernate JDB C
  409          * @author 
D NS     BLACKW
  410        * @pa ram Claim  indexid
  411        * @si nced 11/27 /2013
  412        */
  413        @Supp ressWarnin gs("deprec ation")
  414           pr ivate void  updateWri ttenRecord JDBC(Strin g claimInd exId) {
  415  
  416  
  417  
  418            b oolean DEB UG = false ;
  419  
  420           //  TEST BATC H INSERT F IRST......
  421            t ry {
  422  
  423  
  424                                      // fill  in paramet ers
  425                                      pStateme nt.setLong (1, new Lo ng(claimIn dexId).lon gValue());                                  // CLAIM_I NDEX what  is the Ora cle value  here?
  426                                      pStateme nt.setStri ng(2,"SENT ");                                                                                         // CLA IM_STATUS_ CD
  427                                      pStateme nt.setStri ng(3, "Fin alFee277Fl atFile");                                                      //  CREATED_B Y
  428                                      pStateme nt.setTime stamp(4, t his.runTim estamp);                                                       //  DATE_MODI FIED
  429                                      pStateme nt.setStri ng(5, "Fin alFee277Fl atFile");                                                      //  MODIFIED_ BY
  430                                      pStateme nt.setTime stamp(6,ge tCurrentTi meStamp()) ;                                                   //  DATE_CREA TED - MUST  BE CONSTA NT FROM TO P OF RUN.. ...
  431  
  432                                      pStateme nt.addBatc h();
  433                                      
  434                         if (this.c nt % this. BATCH_SIZE  == 0) {
  435                                               pStatement .executeBa tch();
  436                             conn.c ommit();
  437  
  438   // TEST -  CHECK DATA  VIA TOAD  TO BE SURE  IT'S VISI BLE AFTER  COMMIT.... .
  439                             batchU pdateCount ++;
  440  
  441  
  442                             if(DEB UG)
  443                             {
  444                                      // LOGGE R.info("up dateWritte nRecordJDB C() - batc h UPDATE E ND at: " +  getNow()) ;
  445                             }
  446                         }   // end  if
  447  
  448                     } c atch (OutO fMemoryErr or e) {
  449                              LOGGE R.error("u pdateWritt enRecordJD BC() Out O f Memory E rror !!!!! ", e);
  450                  try {
  451                      co nn.rollbac k();
  452                  }catch (Exception  rback) {
  453                      if (DEBUG) {
  454                      }
  455                                        LOGGER .error(e.g etMessage( ), e);
  456                               LOGG ER.error(" updateWrit tenRecordJ DBC() - FA ILED trans action rol led back") ;
  457                  }
  458            } catch(SQLE xception e xSQL) {
  459                     try  {
  460                              conn. rollback() ;
  461                              if(DE BUG) {
  462                              }
  463                                      LOGGER.e rror(exSQL .getMessag e(), exSQL );
  464                                      LOGGER.e rror("App  1 - update WrittenRec ordJDBC()  - FAILED t ransaction  rolled ba ck");
  465  
  466                     } c atch(Excep tion e) {
  467                             if(DEB UG) {
  468                             }
  469                             LOGGER .error(e.g etMessage( ), e);
  470                             LOGGER .error("Ap p 1 - upda teWrittenR ecordJDBC( ) - FAILED  transacti on rolled  back");
  471                     }
  472  
  473  
  474            }  catch(Exc eption ex)  {
  475                             if(DEB UG) {
  476                             }
  477                                      LOGGER.e rror("upda teWrittenR ecordJDBC( ), errored  on Claim  Key: {}",   claimInde xId);
  478                             LOGGER .error(ex. getMessage (), ex);
  479                             LOGGER .error("up dateWritte nRecordJDB C() - tran saction ro lled back  for claim:  " + claim IndexId);
  480            }
  481  
  482        }  //  end updat eWrittenRe cordJDBC()
  483  
  484  
  485  
  486       /**
  487        * Cal led to upd ate writte n record a fter it ha s been wri tten
  488          * @author 
D NS     BLACKW
  489        * @pa ram Claim  indexid
  490        */
  491       @Suppr essWarning s("unused" )
  492           pr ivate void  updateErr oredClaim( long claim IndexId) {
  493  
  494   // declare  transacti on
  495           En tityTransa ction txUp dateDataba se = em.ge tTransacti on();
  496  
  497           St ring SINGL E_QUOTE =  "'";
  498  
  499           Qu ery q;
  500           Li st<?> l;
  501           It erator<?>  it;
  502           St ring tmp =  "";
  503  
  504           //  this is u sed in upd ateWritten Record() i nsert stat ement
  505           St ring updat eNow = new  SimpleDat eFormat("y yyy-MM-dd  HH:mm:ss") .format(ne w Date());       // m ust be :mm  - not :mi
  506  
  507            / / put sing le quotes  around upd ateDateTim e for Orac le
  508            u pdateNow=  SINGLE_QUO TE + updat eNow + SIN GLE_QUOTE;
  509  
  510            / **
  511              * This.Upd ateTime sh ould be th e time of  the run =  date_creat ed
  512  
  513   updateNow  should  be  date_modi fied
  514  
  515              */
  516           St ring sqlIn sert =
  517                     " i nsert into  FPPS_OWNE R.STG_277  (claim_ind ex, claim_ status_cd,  created_b y, date_mo dified, mo dified_by,  date_crea ted) " +
  518                     " v alues (" +  claimInde xId + ", ' ERROR', 'F inalFee277 FlatFile',  " +
  519                     " t o_date(" +  updateNow  + ",'yyyy -mm-dd hh2 4:mi:ss'),  'FinalFee 277FlatFil e',  to_da te(" + thi s.updateDa teTime + " ,'yyyy-mm- dd hh24:mi :ss'))";
  520  
  521                   try {
  522  
  523   // begin t ransaction
  524   txUpdateDa tabase.beg in();
  525  
  526  
  527   // TODO -  ENABLE exe cuteUpdate ()
  528   this.em.cr eateNative Query(sqlI nsert).exe cuteUpdate ();
  529  
  530   // run tra nsaction
  531  
  532   txUpdateDa tabase.com mit();
  533  
  534  
  535                         } catch(Ex ception ex ) {
  536                                                                // r ollback tr ansaction
  537                                                          txUpdateDa tabase.rol lback();
  538                               LOGG ER.error(" updateErro redClaim() , errored  on Claim K ey: {}",   claimIndex Id);
  539                               LOGG ER.error(e x.getMessa ge(), ex);
  540                               LOGG ER.error(" updateErro redClaim()  - transac tion rolle d back for  claim: "  + claimInd exId);
  541                         }
  542  
  543          }         // e nd of upda teErroredC laim
  544  
  545  
  546  
  547  
  548  
  549  
  550  
  551       /**
  552       * Call ed during   Fee 277 F lat File G eneration
  553       * Set  EntityMana ger
  554       * Set  senderId/c learinghou seId
  555       * Set  output fil e path
  556       * @aut hor Bill B lackmon
  557       * @par am clearin ghouseId i d of clear inghouse
  558       * @par am filePat h   path o f output f ile
  559       * @par am entityM anager Ent ityManager  to config ure databa se access
  560        * @pa ram iLookB ackDays
  561       * @
  562       */
  563  
  564       // pec s.process( loadType,  senderId,  outputDir,  em, iLook BackDays,  iLookBackE ndDays);
  565       final  void proce ss(String  loadType,  String cle aringhouse Id, String  filePath,  EntityMan ager entit yManager,  int iLookB ackDays, i nt iLookBa ckEndDays)  {
  566  
  567           if (loadType  != null) {
  568                    this .loadType  = loadType ;
  569           }
  570  
  571           th is.iLookBa ckDays = i LookBackDa ys;
  572           th is.iLookBa ckEndDays  = iLookBac kEndDays;
  573  
  574           th is.hdrRunT ime = setH drRunTime( );
  575  
  576  
  577           //  LOGGER.de bug("proce ssing with  clearingh ouseId: {}   filePath : {} ", cl earinghous eId, fileP ath);  Cal endar cal  = new Greg orianCalen dar();
  578  
  579           //  'yyyy-mm- dd hh colo n mi'
  580  
  581           Si mpleDateFo rmat fmt =  new Simpl eDateForma t("yyyy-MM -dd hh:mm" );
  582  
  583           tr y {
  584                    java .util.Date  today = n ew java.ut il.Date();
  585  
  586                    long  t = today .getTime() ;
  587                    java .sql.Date  dt = new j ava.sql.Da te(t);
  588  
  589  
  590                    Stri ng datestr 001 = (new  java.sql. Date(today .getTime() )).toStrin g();
  591  
  592                    Stri ng todaySt r = fmt.fo rmat(today );
  593   //               Syst em.out.pri ntln("toda yStr value : " +today Str);
  594  
  595                             this.s ysdatetime  = todaySt r;
  596  
  597   //       S ystem.out. println("p rocess() -  current D ate and Ti me is: " +  sysdateti me.getTime ());
  598           }  catch(Exce ption ex)  {
  599                    Syst em.out.pri ntln("proc ess() erro r: " + ex. getMessage ());
  600  
  601           }
  602  
  603  
  604           th is.dailyCs tat = fals e;                                   // no  date range
  605           th is.em = en tityManage r;
  606  
  607           pa ymentDataE xtraction. setEntityM anager(ent ityManager );
  608  
  609           pr ocessClaim Status(cle aringhouse Id, filePa th);
  610       }
  611  
  612  
  613  
  614       privat e void set FinalizedC odes() {
  615  
  616           in t availabl eDetails =  0;
  617           in t paidDeta ils = 0;
  618  
  619           //  clear the se values  upon entry  and reset  in code
  620           th is.claimSt atusCatego ryCode="F0 ";
  621           th is.statusC ode="1";
  622  
  623  
  624  
  625   // 6/26/20 13 - SAME  - unchange d 7/11/201 3
  626           St ring sLine sAvailable  =
  627                    "sel ect count( *) from fp ps_owner.c laim_proce dure cp wh ere  cp.cl aim_index  = " + this .sClaimKey ;
  628  
  629           //  7/17
  630           St ring sLine sPaid = "s elect coun t (distinc t claim_pr oc_id) fro m claim_pr oc_recon w here claim _index = "  + this.sC laimKey +  " and paid _amount >  0";
  631  
  632  
  633                             try {
  634                                      Query qL inesAvaila ble = em.c reateNativ eQuery(sLi nesAvailab le);
  635                                      // fails  with 87St ring sLine sPaid = "3 07869
  636                                      BigDecim al x = (Bi gDecimal)  qLinesAvai lable.getS ingleResul t();
  637                                      if(x !=  null) {
  638                                               availableD etails = x .intValue( );
  639                                      } else {
  640   // System. out.printl n("setFina lizedCodes (): - avai lableDetai ls is NULL ....");
  641                                      }
  642   //                                 System.o ut.println ("setFinal izedCodes( ): - Count  of AVAILA BLE detail  lines: "  + availabl eDetails);
  643                             } catc h(Exceptio n ex) {
  644                                      System.o ut.println ("setFinal izedCodes( ) ERROR: "  + ex.getM essage());
  645                                      ex.print StackTrace ();
  646                                      LOGGER.e rror("Erro r on setFi nalizedCod es(), erro red on Cla im Key: {} ",  this.c laimKey);
  647                             LOGGER .error(ex. getMessage (), ex);
  648                             }
  649  
  650  
  651  
  652   // System. out.printl n("setFina lizedCodes () - sLine sPaid is:  " + sLines Paid);
  653                             try {
  654                                      Query qL inesPaid =  em.create NativeQuer y(sLinesPa id);
  655                                      BigDecim al y = (Bi gDecimal)  qLinesPaid .getSingle Result();
  656  
  657                                      if(y !=  null) {
  658                                               paidDetail s = y.intV alue();
  659                                      } else {
  660   // System. out.printl n("setFina lizedCodes (): -paidD etails is  NULL....") ;
  661                                      }
  662   //      Sy stem.out.p rintln("se tFinalized Codes() -  count of P AID detail  lines: "  + paidDeta ils);
  663                             } catc h(Exceptio n ex2) {
  664                                      ex2.prin tStackTrac e();
  665                                      LOGGER.e rror("Erro r on setFi nalizedCod es(), erro red on Cla im Key: {} ",  this.c laimKey);
  666                             LOGGER .error(ex2 .getMessag e(), ex2);
  667                             }
  668  
  669  
  670   /**
  671    * F0 Fina lized/Paym ent-The cl aim/line h as been pa id. - Paid  lines cou nt == avai lable line s count
  672    * I think  the highe st priorit y would be  to get a  new 277Fee FlatFile t hat addres ses Anne D ebacker’s  concern be low.
  673    * The val ue of 1 sh ould be us ed only if  NOT paid,  so only f or F0 or F 2.
  674    *
  675    * 65 is o nly used f or a paid  (F1).
  676    * Also im proved map ping file  that state s the orac le table,  column, va lue used t o drive th e 277FeeFl atFile pie ce.
  677  
  678   F0 - MIXED  - 1 STATU S CODE FOR  NOW
  679   F1 - ALL P AID - STAT US CODE =  65
  680   F2 - NONE  PAID - 1 S TATUS CODE  FOR NOW
  681   **/
  682  
  683  
  684   /**
  685    * 6/17/20 13
  686    * 'defect ' issue fr om Jeffrey  Neinhaus:
  687    * 'TC POR 2-1, Run 1 , All CLM/ STC pairs  have statu s code of  F1 regardl ess of
  688    * whether  the claim  was rejec ted or not . Expected  to see St atus Categ ory Code o f F2 for a ll rejecte d claims i n the
  689    * batch a nd F0 for  all claims  with reje cted lines .
  690    *
  691  
  692    **/
  693  
  694   /**
  695    * New not es from Jo hn S., 6/2 6
  696    * For the  CLM level , if all l ines are F 1, then CL M level is  F1 / 65 F or CLM lev el, if all  lines are  F2,
  697    * then CL M level is  F2 / 1 If  there are  a combina tion of F1  and F2 li nes, then  the CLM le vel is F0  / 1
  698    */
  699  
  700  
  701           //  none paid
  702           if ( (availab leDetails  > 0) && (p aidDetails  == 0) ) {
  703                    // S ystem.out. println("s etFinalize dCodes() -  NO BILLS  PAID for:  " + this.s ClaimKey);
  704                    this .claimStat usCategory Code="F2";
  705                    this .statusCod e="1";
  706           }
  707  
  708           //  all paid
  709           if (available Details ==  paidDetai ls) {
  710   // System. out.printl n("setFina lizedCodes () - ALL B ILLS PAID  for: " + t his.sClaim Key);
  711                    this .claimStat usCategory Code="F1";
  712                    this .statusCod e="65";
  713  
  714           }
  715  
  716           //  some paid  - mixed
  717           if ( ( (avail ableDetail s > 0) &&  (paidDetai ls > 0) )  && (availa bleDetails  > paidDet ails) ) {
  718                    this .claimStat usCategory Code="F0";
  719                    this .statusCod e="1";
  720           }
  721  
  722  
  723           if (this.clai mStatusCat egoryCode. equalsIgno reCase("") )  {
  724  
  725                    // S ystem.out. println("s etFinalize dCodes() -  claimStat usCategory Code IS NU LL");
  726           }
  727  
  728   }       //  end setFi nalizedCod es()
  729  
  730  
  731  
  732  
  733  
  734  
  735  
  736           pr ivate Stri ngBuffer a ppend(Stri ngBuffer s b, String  value) {
  737           sb .append(va lue);
  738           sb .append(DE LIMITER);
  739  
  740           re turn sb;
  741  
  742       }
  743  
  744           /* **
  745            *  @author B ill Blackm on
  746            *  @since 7/ 23/2013
  747            *  @return S tring curF ileNumber
  748            * /
  749           St ring getGe tCurFileNu mber() {
  750  
  751                    retu rn String. format("%0 2d",curFil eNumber);
  752           }
  753  
  754  
  755           pu blic Strin g setHdrRu nTime() {
  756                     Cal endar cal  = new Greg orianCalen dar();
  757                     //  @SuppressW arnings("u nused")
  758                    // j ava.util.D ate date =  cal.getTi me();
  759                     Sim pleDateFor mat transD ate = new  SimpleDate Format("yy yyMMdd");
  760                     Sim pleDateFor mat transT ime = new  SimpleDate Format("HH mmss");
  761  
  762                     Str ing strDat e = transD ate.format (cal.getTi me());
  763                     Str ing strTim e = transT ime.format (cal.getTi me());
  764  
  765                     Str ing strDat eTime = st rDate+strT ime;
  766  
  767                     ret urn strDat eTime;
  768           }
  769  
  770           /* *
  771            *  Write hea der row -  no data ac cess requi red
  772            *  Size=126  bytes
  773              Date forma ts changed  5/20/2013
  774             
  775            C ompromise  solution:  12/9/2013:
  776              A proposed  solution  is to send  each file  as a sing le file, n ot part of  a file gr oup.  
  777              The staff  at Emdeon  believes t hey will b e able to  process th ese files  effectivel y.
  778              This would  mean that  in the HD R record f or each fi le created , the File  Group ID  would be u nique, CCY YMMDDHHMMS S, 
  779              when the f ile is cre ated.
  780  
  781              Also, fiel d 3 File G roup Seque nce Number , would be  set to 1,  
  782              and field  4 File Gro up Count w ould be se t to 1 for  all files  generated  by any gi ven run of  the Fee F inal Statu s file pro cess.
  783  
  784         The  physical f iles are a ll named u niquely as , CCYYMMDD HHMMSS_FEE  Final Sta tus.cstat,  where CCY YMMDDHHMMS S is defin ed when th e file is  initially  created.
  785  
  786  
  787            *  @param vC sFile
  788            * /
  789       final  void creat eHdrRec(Pr intWriter  vCsFile) {
  790  
  791                     Cal endar cal  = new Greg orianCalen dar();
  792                     //  @SuppressW arnings("u nused")
  793                    // j ava.util.D ate date =  cal.getTi me();
  794                     Sim pleDateFor mat transD ate = new  SimpleDate Format("yy yyMMdd");
  795                     Sim pleDateFor mat transT ime = new  SimpleDate Format("HH mmss");
  796  
  797                     Str ing strDat e = transD ate.format (cal.getTi me());
  798                     Str ing strTim e = transT ime.format (cal.getTi me());
  799  
  800                     Str ing strDat eTime = st rDate+strT ime;
  801  
  802           St ringBuffer  sbHdrRec  = new Stri ngBuffer() ;
  803  
  804   // 1    Re cord ID
  805           sb HdrRec.app end("HDR") ; //Record  ID  - TWP : Changed  to 3 char  for 5010
  806           de limit(sbHd rRec);
  807  
  808   // 2    Fi le Group I D
  809           //  this.runT imestamp
  810           //  yyyymmddh hmmss
  811            / / changed  to global  date - wil l be same  for each h eader..... .....if th ere's more  than one.
  812  
  813           //  12/9 - ma ke same as  file name .......
  814           //  set to sa me value a s time val ue on file  name.....
  815           
  816           sb HdrRec.app end(this.s trFileTime );
  817           de limit(sbHd rRec);
  818  
  819   // 3    Fi le Group S equence Nu mber  CURR ENT FILE ( 1 of...)
  820            / / sbHdrRec .append(ge tGetCurFil eNumber()) ;
  821           //  changed o n recommen dation of  A.J. Magdu b 12/5
  822           sb HdrRec.app end("1");    // final  - 12/9
  823           de limit(sbHd rRec);
  824  
  825   // 4    Fi le Group C ount - tot al number  of output  files - UN KNOWN AT R UN TIME... ..
  826           //  changed t o "1" from  "01" on r ecommendat ion of A.J . Magdub.. ..12/5
  827           //  changed b ack to 01  as passed  by IV/V 12 /6
  828           sb HdrRec.app end("1");  //File Gro up Count -  looks lik e we are n ot using t he whole f ile group  concept
  829           de limit(sbHd rRec);
  830  
  831   // 5    Cr eation Dat e
  832           sb HdrRec.app end(strDat e); //Crea tion Date  8 chars yy yyMMdd
  833           de limit(sbHd rRec);
  834           // sbHdrRec.a ppend(this .currentTi me); //Cre ation Time  6 chars H Hmmss
  835  
  836   // 6    Cr eation Tim e
  837           sb HdrRec.app end(strTim e); //Crea tion Time  6 chars HH mmss
  838           de limit(sbHd rRec);
  839  
  840   // 7    Tr ading Part ner Id
  841           sb HdrRec.app end(TRADIN G_PARTNER_ ID);
  842           de limit(sbHd rRec);
  843  
  844   // 8    Su bmitter na me
  845           sb HdrRec.app end("VA FE E BASIS Pr ogram"); / /Submitter  Name  - T WP: is thi s correct?  NO....VA  FEE BASIS
  846           de limit(sbHd rRec);
  847  
  848  
  849   //    Move  “Contact  Local VAMC ” to posit ion 9, pos ition 10 w ill be nul l
  850   // 9    Pa yer Contac t Name
  851           sb HdrRec.app end("Conta ct Local V AMC"); //   - TWP: is  this corr ect? NO... .VA FEE BA SIS
  852           de limit(sbHd rRec);
  853  
  854   // Contact  Local VAM C – Move “ Contact Lo cal VAMC”  to positio n 9, posit ion 10 wil l be null
  855  
  856           //  swap next  2 - look  at pending  for conf.
  857   // 10   Pa yer Suppor t Telephon e Number
  858           sb HdrRec.app end("");
  859           de limit(sbHd rRec);
  860  
  861           //  sbHdrRec. append("Co ntact Loca l VAMC");  //Payer Su pport Tele phone Numb er
  862  
  863   // 11   Pa yer Suppor t Email Ad dress
  864           //  delimit(s bHdrRec);
  865           sb HdrRec.app end(""); / /PayerSupp ort Email
  866           de limit(sbHd rRec);
  867  
  868   // 12   Lo ad Type -  value shou ld be "I",  7/1, Anne  DeBacker
  869  
  870  
  871   /**
  872    * 1)       FEE Final  Status –  add an abi lity to cr eate a FUL L file (LO AD TYPE fi eld in HDR  record an d 30 in Ma intenance  Type Code  field in C LM records ).  Bill B lackmon is  working o n this now .
  873    */
  874           if  (this.loa dType.equa lsIgnoreCa se("i")) {  //Load ty pe - full  or increme ntal
  875                sbHdrRec .append("I ");
  876            }  else {
  877                sbHdrRec .append("F ");
  878            }
  879  
  880           de limit(sbHd rRec);
  881  
  882   // System. out.printl n("createH drRec() -  loadType o ut is: " +  sbHdrRec. toString() );
  883  
  884  
  885  
  886   // 13   Pa yer Unique  File Iden tifier
  887           sb HdrRec.app end(String Utils.rPad Spaces(str DateTime +  "_VAFEE",  20)); //P ayer Uniqu e File Ide ntifier
  888           de limit(sbHd rRec);
  889  
  890   // 14   Fi le Type
  891           sb HdrRec.app end("CStat "); //File  Type - TW P updated  for 5010 b ut spec do es not mak e sense ma x len = 4  but value  must = Cst at which i s 5 long?
  892           de limit(sbHd rRec);
  893  
  894   // 15   Ve rsion Code
  895           sb HdrRec.app end("03");  //Version  Code TWP  updated fr om 02 to 0 3
  896           de limit(sbHd rRec);
  897  
  898   // 16   Re lease Code
  899           sb HdrRec.app end("00");  //Release  Code
  900           sb HdrRec.app end(CRLF);  //Record  Teminator  new for 50 10
  901  
  902  
  903   // System. out.printl n("HEADER  - FINAL LI NE IS: " +  sbHdrRec. toString() );
  904  
  905  
  906           th is.headerS ize=sbHdrR ec.length( );
  907  
  908           vC sFile.prin t(sbHdrRec ); //TWP C hanged to  print rath er than pr intln sinc e I am exp licitly ad ding CRLF
  909  
  910           vC sFile.flus h();
  911  
  912  
  913           sb HdrRec = n ull;
  914       }
  915  
  916  
  917       /**
  918        *
  919        * Thi s method v alidates a  claim ind ex id agai nst a corr esponding  EREPOS sch ema edi cl aim index  id
  920        * Rou gh draft,  6/27/2013
  921        *
  922        * @au thor Bill  Blackmon
  923        * @si nce 6/27/2 013
  924        * @pa ram claimI ndexId
  925        * @pa ram ediCla imIndexId
  926        * @re turn boole an
  927        */
  928       privat e boolean  validateEr eposClaim( long claim IndexId) {
  929           bo olean DEBU G = false;
  930  
  931           bo olean bRet Val = true ;
  932           En tityTransa ction txUp dateDataba se = em.ge tTransacti on();
  933           Qu ery q;
  934                List<?>  l;
  935                Iterator <?> it;
  936                int coun t = 0;
  937  
  938                String s qlGetEdiCl aims = "se lect count (*) from f pps_owner. claims c,  e_repos.cl aim cc whe re c.edi_c laim_key =  cc.claim_ key and c. claim_inde x = " + cl aimIndexId ;
  939  
  940   // System. out.printl n("validat eEreposCla im() - sql  is: " + s qlGetEdiCl aims);
  941  
  942  
  943           tr y {
  944  
  945   if(DEBUG)  {
  946           Sy stem.out.p rintln("\n validateEr eposClaim( ) TOP time  is....");
  947           ge tNow();
  948   }
  949  
  950                                                     q =  this.em.cr eateNative Query(sqlG etEdiClaim s);
  951                                                     l =  q.getResul tList();
  952                                                     it =  l.iterato r();
  953  
  954  
  955                                                     Obje ct row = ( BigDecimal ) it.next( );
  956  
  957                                                              if(row  != null)  {
  958  
  959                                                                         String  tmp = row .toString( );
  960                                                                         count  = new Inte ger(tmp).i ntValue();
  961  
  962   // System. out.printl n("validat eEreposCla im() - EDI  claims co unt is: "  + count);
  963  
  964                                                              }
  965  
  966                                                     if(c ount == 0)  {
  967   // System. out.printl n("validat eEreposCla im() - NO  CORRESPOND ING EREPOS  RECORD fo r claimInd exId: " +  claimIndex Id);
  968                                                                         bRetVa l = false;
  969                                                     }
  970                                      } catch( Exception  ex) {
  971                                               bRetVal =  false;
  972                                               System.out .println(" validateEr eposClaim( ) ERROR: "  + ex.getM essage());
  973                                                       ex .printStac kTrace();
  974                                                       LO GGER.error ("validate EreposClai m(), error ed on Clai m Key: {}" ,  claimIn dexId);
  975                                               LOGGER.err or(ex.getM essage(),  ex);
  976                                      }
  977  
  978   if(DEBUG)  {
  979           Sy stem.out.p rintln("\n validateEr eposClaim( ) END time  is....");
  980           ge tNow();
  981   }
  982  
  983           re turn bRetV al;
  984          }         // e nd of vali dateErepos Claim()
  985  
  986  
  987  
  988           /* *
  989        * Loo p through  claims res ults and w rite out d etail reco rd
  990        * @au thor Bill  Blackmon
  991        * @pa ram claims
  992        * @pa ram sessio n
  993        * @pa ram vCsFil e
  994        */
  995  
  996       @Suppr essWarning s({ "unuse d", "unche cked", "ra wtypes" })
  997           fi nal void c reatePrima ryDetailRe c(Scrollab leResults  claims, Se ssion sess ion, Print Writer vCs File) {
  998  
  999           bo olean DEBU G = false;
  1000  
  1001  
  1002           in t count =  0;
  1003          
  1004           St ring seqNu mber = "";
  1005           bo olean bCon tinueLoop  = true;
  1006  
  1007           St ringBuffer  sbDtlRec  = new Stri ngBuffer() ;              // set  length va lue to 0 N OT null at  end of me thod
  1008  
  1009           St ring sStar tDate="";
  1010                    Stri ng sEndDat e="";
  1011  
  1012           /* *
  1013               Fields th at can be  set to nul l (empty S tring) acc ording to  Mary S. em ail 3/20/2 013
  1014                Field 6  – Billing  Provider P ayer Assig ned Number —can set t o null
  1015                             Field  13 – Servi ce Provide r Payer As signed Num ber—can se t to null
  1016                             Field  19 – Emplo yer Identi fication N umber—can  set to nul l
  1017                             Field  20 – Emplo yer Name—c an set to  null
  1018                             Field  43 - Vouch er Identif ier—can se t to null
  1019                             Field  45 – Group  Number—ca n set to n ull.
  1020  
  1021            * /
  1022                    Arra yList erro redKeys =  new ArrayL ist();
  1023  
  1024   // MAIN RE CORDS LOOP
  1025   while (cla ims.next() ) {
  1026                                               // clear p revious en tries in P aymentData Extraction ...
  1027                                         this. paymentDat aExtractio n.clearAll ();
  1028  
  1029  
  1030                                             C laim claim  = (Claim)  claims.ge t(0);
  1031                                             l ong l  = c laim.getCl aimIndex() ;
  1032                                                  Long L  = new Long (l);
  1033                                                  this.sC laimKey =  L.toString ();
  1034                                                  this.cl aimKey = l ;
  1035  
  1036   // DO NOT  EDIT THIS  STATEMENT
  1037                                                  this.ed iClaimKey  = claim.ge tEdiClaimK ey();
  1038  
  1039                                                  this.cn t++;
  1040                                                  this.bI nClaim = t rue;
  1041  
  1042  
  1043                                                       St ring repos Str = "Sel ect e from  eClaim e  where e.cl aimKey = : ediClaimKe y";
  1044  
  1045  
  1046                                                       go v.va.med.d omain.erep os.Claim r eposClaim  = null;
  1047  
  1048   try {
  1049  
  1050                                                                if(D EBUG) {
  1051                                                                         System .out.print ln("\nCrea tePrimaryD etailRec()  - calling  getting e ReposClaim Info  at.. ..");
  1052                                                                         getNow ();
  1053                                                                }
  1054                                                                         Query  qErepos =  em.createQ uery(repos Str);
  1055  
  1056  
  1057  
  1058                                                                         qErepo s.setParam eter("ediC laimKey",  this.ediCl aimKey);
  1059  
  1060                                                                         // use  this clai m to handl e informat ion from e _repos sch ema
  1061                                                                         reposC laim = (go v.va.med.d omain.erep os.Claim)  qErepos.ge tSingleRes ult();
  1062  
  1063  
  1064                                                                                  // if ab ove is suc cessful, g et propert ies below. .....
  1065                                                                                  if(repos Claim != n ull ) {
  1066  
  1067  
  1068   // THESE V ALUES ARE  NECESSARY  FOR INHERI TED CODE T O FUNCTION  CORRECTLY  - DO NOT  DELETE AT  THIS POINT , B.B. - 6 /27 - Demo graphic, P erson Info  uses thes e values,
  1069   //  #41 -  Patient Ac count Numb er uses in fo,
  1070                                                                                           this.erepo sClaimKey  = reposCla im.getClai mKey();
  1071  
  1072                                                                                           this.fileN br = repos Claim.getF ileNumber( );
  1073  
  1074                                                                                           this.st02C tlNbr = re posClaim.g etSt02txnC tlNbr();
  1075  
  1076                                                                                           this.billP rvdId = re posClaim.g etNm109bil lPrvdId();
  1077  
  1078                                                                                           this.sbcrI d = reposC laim.getSu bscriberId ();
  1079  
  1080                                                                                           this.claim Type = rep osClaim.ge tClaimType ();
  1081  
  1082                                                                                           this.statu sCd = repo sClaim.get StatusCode ();
  1083  
  1084                                                                                  }
  1085  
  1086   setFinaliz edCodes();
  1087  
  1088  
  1089   //TODO ins ert this m ethod for  testing
  1090   // payment DataExtrac tion.setPr oviderInfo (this.sCla imKey);        // NOT  USED AS O F 12/4 - l eave in he re until c ode is fin alized.
  1091   paymentDat aExtractio n.setBilli ngProvider Info(this. sClaimKey) ;
  1092   paymentDat aExtractio n.setServi ceProvider Info(this. sClaimKey) ;
  1093   paymentDat aExtractio n.setEmdeo nClaimNumb er(this.sC laimKey);
  1094   paymentDat aExtractio n.setClaim ChargePaym entAmounts (this.sCla imKey);
  1095   paymentDat aExtractio n.setClaim Adjudicati onPaymentD ate(this.s ClaimKey);
  1096   paymentDat aExtractio n.setCheck DateAndNum ber(this.s ClaimKey);
  1097   paymentDat aExtractio n.setPharm acyPrescri ptionNumbe r(this.sCl aimKey);
  1098   //moved fr om payment DataExtrac tion.getDe tailRecord s()......1 1/25
  1099   paymentDat aExtractio n.setServi ceTypeCode (this.sCla imKey);
  1100   //moved fr om payment DataExtrac tion.getDe tailRecord s()......1 2/2
  1101   paymentDat aExtractio n.setServi ceQualifie rID(this.s ClaimKey);
  1102  
  1103  
  1104  
  1105   /********* ********** ********** ********** ******* ST ART OF OUT PUT SECTIO N ******** ********** ********** ********** ********** ********** ********** /
  1106  
  1107   // START C LAIM SECTI ON HERE
  1108   // #1 - Re cord ID
  1109                                               // StringB uffer sbDt lRec = new  StringBuf fer();
  1110                                               sbDtlRec.a ppend("CLM "); //Reco rd ID - 3  long in 50 10
  1111                                               delimit(sb DtlRec);
  1112  
  1113  
  1114  
  1115   // #2 - ro w count -  B.B. - cha nged 6/14/ 2013
  1116  
  1117                                               sbDtlRec.a ppend(form atOutputSt ring(Integ er.toStrin g(this.row Count),  R EQUIRED, 1 , 10, Stri ngFormat.L PADZERO));  // rowCou nt
  1118                                               this.rowCo unt++;
  1119  
  1120   // #3 - Pa yer Id
  1121                                               sbDtlRec.a ppend(PAYE R_ID);
  1122                                               delimit(sb DtlRec);
  1123  
  1124  
  1125   // #4 - Ma intenance  Type Code
  1126   // HERE -  CHANGE BAS ED ON COMM AND LINE A RG 'loadTy pe'....... ......
  1127   // from sp ec: For Fu ll Loads t he Mainten ance Type  Code value  will alwa ys be 030  for all re cords.
  1128   //
  1129  
  1130                                               if (this.l oadType.eq ualsIgnore Case("i"))  {
  1131                                                       sb DtlRec.app end("021") ;
  1132                                               } else {
  1133                                                       sb DtlRec.app end("030") ;
  1134                                               }
  1135  
  1136                                               delimit(sb DtlRec);
  1137  
  1138                                      //  #5 B illing Pro vider Fede ral Tax ID
  1139                                      sbDtlRec .append(fo rmatOutput String(pay mentDataEx traction.g etBillingP roviderFed eralTaxID( ), OPTIONA L, 1, 60,  null));
  1140  
  1141  
  1142                                      // #6 Bi lling Prov ider Assig ned Payer  Number
  1143                                      sbDtlRec .append(DE FAULT_NULL );
  1144                                      delimit( sbDtlRec);
  1145  
  1146  
  1147  
  1148  
  1149                                      // #7 Bi lling Prov ider Natio nal Provid er ID : ch anged to l ength 60 f rom 35
  1150                                      sbDtlRec .append(fo rmatOutput String(pay mentDataEx traction.g etBillingP roviderNat ionalProvi derID(), O PTIONAL, 1 , 60, null ));
  1151  
  1152  
  1153                                      // #8 Bi lling Prov ider Last  Name
  1154                                      sbDtlRec .append(fo rmatOutput String(pay mentDataEx traction.g etBillingP roviderLas tName(), O PTIONAL, 1 , 60, null ));
  1155  
  1156  
  1157                                      // #9 Bi lling Prov ider First  Name TWP:  changed t o length 3 5 from 25  - field =  nm104fst_n m
  1158                                      sbDtlRec .append(fo rmatOutput String(pay mentDataEx traction.g etBillingP roviderFir stName(),  OPTIONAL,  1, 60, nul l));
  1159  
  1160  
  1161                                      // #10 B illing Pro vider Midd le Name TW P: added t his elemen t
  1162                                      sbDtlRec .append(fo rmatOutput String(pay mentDataEx traction.g etBillingP roviderMid dleName(),  OPTIONAL,  1, 60, nu ll));
  1163  
  1164  
  1165                                      // #11 B illing Pro vider Name  Suffix
  1166                                      sbDtlRec .append(fo rmatOutput String(pay mentDataEx traction.g etBillingP roviderNam eSuffix(),  OPTIONAL,  1, 25, St ringFormat .RPADSPACE S));
  1167  
  1168   // END OF  BILLING PR OVIDER NAM E INFORMAT ION
  1169  
  1170  
  1171   // Start o f Service  Provider I nformation .
  1172  
  1173  
  1174   //#12 Serv ice Provid er Federal  Tax ID
  1175   // Expect  SP Fed Tax  ID (field  12) to be  blank if  the same a s the Bill ing Provid er Tax ID  field 5
  1176   // String  sID = paym entDataExt raction.ge tServicePr oviderFede ralTaxID() ;
  1177  
  1178                                      sbDtlRec .append(fo rmatOutput String(pay mentDataEx traction.g etServiceP roviderFed eralTaxID( ), false,  1, 50, Str ingFormat. RPADSPACES ));
  1179  
  1180  
  1181  
  1182   //#13 Serv ice Provid er Payer A ssigned Nu mber - def ault to ""  in code
  1183   // Request  - 8/22 -  default to  0.....
  1184                                      sbDtlRec .append(DE FAULT_NULL );
  1185                                      delimit( sbDtlRec);
  1186  
  1187  
  1188  
  1189                                      //#14 Se rvice Prov ider Natio nal Provid er ID
  1190                                      sbDtlRec .append(fo rmatOutput String(pay mentDataEx traction.g etServiceP roviderNat ionalProvi derID(), f alse, 1, 2 0, StringF ormat.RPAD SPACES));
  1191  
  1192  
  1193                                      // #15 S ervice Pro vider Last  Name (or  Org Name)
  1194                                      sbDtlRec .append(fo rmatOutput String(pay mentDataEx traction.g etServiceP roviderLas tName(), f alse, 1, 6 0, StringF ormat.RPAD SPACES));
  1195  
  1196                                      // #16 S ervice Pro vider Firs t Name
  1197                                      sbDtlRec .append(fo rmatOutput String(pay mentDataEx traction.g etServiceP roviderFir stName(),  false, 1,  35, String Format.RPA DSPACES));
  1198  
  1199  
  1200                                      // #17 S ervice Pro vider Midd le Name
  1201                                      sbDtlRec .append(fo rmatOutput String(pay mentDataEx traction.g etServiceP roviderMid dleName(),  OPTIONAL,  1, 25, St ringFormat .RPADSPACE S));
  1202  
  1203  
  1204                                      // #18 S ervice Pro vider Name  suffix
  1205                                      sbDtlRec .append(fo rmatOutput String(pay mentDataEx traction.g etServiceP roviderNam eSuffix(),  OPTIONAL,  1, 10, St ringFormat .RPADSPACE S));
  1206  
  1207   // END OF  SERVICE PR OVIDER SEC TION
  1208  
  1209  
  1210  
  1211                                      // #19 E mployer Id entificati on Number
  1212                                      sbDtlRec .append(DE FAULT_NULL );
  1213                                      delimit( sbDtlRec);
  1214  
  1215  
  1216  
  1217                                      // #20 E mployer Na me
  1218                                      sbDtlRec .append(DE FAULT_NULL );
  1219                                      delimit( sbDtlRec);
  1220  
  1221  
  1222  
  1223   // START O F PERSON I NFO
  1224                         PersonInfo  person =  getPersonN ame(this.s bcrId);
  1225  
  1226                         //TWP Seem s Like the  old code  made the a ssumption  that the s ubscriber  and patien t were the  same
  1227                         //am I int erpreting  this corre ctly?
  1228                         if (person  != null)  {
  1229  
  1230  
  1231   // CHECK M AX FIELD L ENGTH FOR  EACH OF TH ESE FIELDS
  1232   // #21 Sub scriber Id
  1233                             sbDtlR ec.append( formatOutp utString(p erson.getP ersonId(),   OPTIONAL , 2, 80, S tringForma t.RPADSPAC ES));
  1234  
  1235  
  1236   // #22 Sub scriber La st Name
  1237                             sbDtlR ec.append( formatOutp utString(p erson.getL astName(),   OPTIONAL , 1, 60, S tringForma t.RPADSPAC ES));
  1238  
  1239  
  1240   // #23 Sub scriber Fi rst Name
  1241                             sbDtlR ec.append( formatOutp utString(p erson.getF irstName() ,  OPTIONA L, 1, 35,  StringForm at.RPADSPA CES));
  1242  
  1243  
  1244   // #24 Sub scriber Mi ddle Name
  1245                             sbDtlR ec.append( formatOutp utString(p erson.getM iddleName( ), OPTIONA L, 1, 25,  StringForm at.RPADSPA CES));
  1246  
  1247  
  1248   // #25 Sub scriber Na me Suffix
  1249                             sbDtlR ec.append( formatOutp utString(p erson.getN ameSuffix( ), OPTIONA L, 1, 10,  StringForm at.RPADSPA CES));
  1250  
  1251  
  1252   // END SUB SCRIBER IN FO.
  1253  
  1254                                               // #26 Pat ient ID -  TWP looks  like we di d not send  this in t he past
  1255                                               sbDtlRec.a ppend(DEFA ULT_NULL);
  1256                                               delimit(sb DtlRec);
  1257  
  1258  
  1259  
  1260   // #27 Pat ient Last  Name
  1261                             sbDtlR ec.append( formatOutp utString(p erson.getL astName(),  OPTIONAL,  1, 60, St ringFormat .RPADSPACE S));
  1262  
  1263  
  1264   // #28 Pat ient First  Name
  1265                             sbDtlR ec.append( formatOutp utString(p erson.getF irstName() , OPTIONAL , 1, 35, S tringForma t.RPADSPAC ES));
  1266  
  1267  
  1268   // #29 Pat ient Middl e Name
  1269                             sbDtlR ec.append( formatOutp utString(p erson.getM iddleName( ), OPTIONA L, 1, 25,  StringForm at.RPADSPA CES));
  1270  
  1271  
  1272  
  1273   // #30 Pat ient Name  Suffix
  1274                             sbDtlR ec.append( formatOutp utString(p erson.getN ameSuffix( ), OPTIONA L, 1, 10,  StringForm at.RPADSPA CES));
  1275  
  1276  
  1277  
  1278                                 }  else {
  1279                                      //IL Sel ects the i nsured or  subscriber  - MI sele cts the Me mber ident ification  number
  1280                                      String v Ql = "AND  NM101ENTY_ ID_CD = 'I L' AND NM1 08ID_CD_QU AL = 'MI'  ";
  1281                                      EntityNa me entityN ameS = get EntityName ("2010BA",  vQl);
  1282                                      sbDtlRec .append(fo rmatOutput String(ent ityNameS.g etNm109idC d(),
  1283                                               OPTIONAL,  2, 80, Str ingFormat. RPADSPACES )); //Subs criber Id
  1284                                      sbDtlRec .append(fo rmatOutput String(
  1285                                               entityName S.getNm103 lastNm(),  OPTIONAL,  1, 60,
  1286                                               StringForm at.RPADSPA CES)); //S ubscriber  Last Name
  1287                                      sbDtlRec .append(fo rmatOutput String(
  1288                                               entityName S.getNm104 fstNm(), O PTIONAL, 1 , 35,
  1289                                               StringForm at.RPADSPA CES)); //S ubscriber  First Name
  1290                                      sbDtlRec .append(fo rmatOutput String("",  OPTIONAL,  1, 25,
  1291                                               StringForm at.RPADSPA CES)); //S ubscriber  Middle Nam e
  1292                                      sbDtlRec .append(fo rmatOutput String("",  OPTIONAL,  1, 10,
  1293                                               StringForm at.RPADSPA CES)); //S ubscriber  Name Suffi x
  1294                                      sbDtlRec .append(fo rmatOutput String("",  OPTIONAL,  2, 80,
  1295                                               StringForm at.RPADSPA CES)); //P atient ID  - TWP look s like we  did not se nd this in  the past
  1296                                      sbDtlRec .append(fo rmatOutput String(
  1297                                               entityName S.getNm103 lastNm(),  OPTIONAL,  1, 60,
  1298                                               StringForm at.RPADSPA CES)); //P atient Las t Name
  1299                                      sbDtlRec .append(fo rmatOutput String(
  1300                                               entityName S.getNm104 fstNm(), O PTIONAL, 1 , 35,
  1301                                               StringForm at.RPADSPA CES)); //P atient Fir st Name
  1302                                      sbDtlRec .append(fo rmatOutput String("",  OPTIONAL,  1, 25,
  1303                                               StringForm at.RPADSPA CES)); //P atient Mid dle Name
  1304                                      sbDtlRec .append(fo rmatOutput String("",  OPTIONAL,  1, 10,
  1305                                               StringForm at.RPADSPA CES)); //P atient Nam e Suffix
  1306                                 }
  1307  
  1308  
  1309  
  1310   // END PER SON INFO
  1311  
  1312   // DEMOGRA PHIC INFO
  1313                                 De mographicI nfo demogr aphicInfo  = getDemog raphicInfo ();
  1314  
  1315                                 if  (demograp hicInfo !=  null) {
  1316  
  1317  
  1318   // #31 Pat ient Date  of Birth
  1319                             sbDtlR ec.append( formatOutp utString(d emographic Info.getDm g02brthDt( ), REQUIRE D, 8, 8, S tringForma t.RPADSPAC ES));
  1320  
  1321   // #32 Pat ient Gende r - B.B. -  why is th is logic h ere? It is  not in th e spec.... .if not nu ll and is  M or F, th en write M  or F else  write emp ty string
  1322  
  1323  
  1324                                 if  ((demogra phicInfo.g etDmg03gnd r() != nul l) && ("M" .equalsIgn oreCase(de mographicI nfo.getDmg 03gndr())  || "F".equ alsIgnoreC ase(demogr aphicInfo. getDmg03gn dr()))) {
  1325                                          sbDt lRec.appen d(formatOu tputString (demograph icInfo.get Dmg03gndr( ), OPTIONA L, 1, 1, S tringForma t.RPADSPAC ES));
  1326                                      } else {
  1327                                          sbDt lRec.appen d(formatOu tputString ("", OPTIO NAL, 1, 1,  StringFor mat.RPADSP ACES)); // Patient Ge nder
  1328                                      }
  1329                                 }  else {
  1330                                      sbDtlRec .append(fo rmatOutput String("",  REQUIRED,  8, 8, Str ingFormat. RPADSPACES )); //Pati ent Date o f Birth
  1331                                      sbDtlRec .append(fo rmatOutput String("",  OPTIONAL,  1, 1,  St ringFormat .RPADSPACE S)); //Pat ient Gende r
  1332                                 }
  1333  
  1334  
  1335   // END DEM OGRAPHIC I NFO
  1336  
  1337  
  1338                                      // 33  -  Emdeon Cl aim Number
  1339   // payment DataExtrac tion.setEm deonClaimN umber(this .sClaimKey );
  1340                                      sbDtlRec .append(fo rmatOutput String(pay mentDataEx traction.g etEmdeonCl aimNumber( ), OPTIONA L, 1, 50,  StringForm at.RPADSPA CES));
  1341  
  1342  
  1343                                                                         // new  method to  calculate  the Claim  Charge Am ount and C laim Payme nt Amount
  1344   // payment DataExtrac tion.setCl aimChargeP aymentAmou nts(this.s ClaimKey);
  1345  
  1346                                      // #34 C laim Charg e Amount -  DONE
  1347                                      sbDtlRec .append(pa ymentDataE xtraction. getClaimCh argeAmount Formatted( ) );
  1348                                      delimit( sbDtlRec);
  1349  
  1350  
  1351  
  1352                                      //#35 Cl aim Paymen t Amount -  DONE
  1353                                      // sbDtl Rec.append (formatOut putString( paymentDat aExtractio n.getClaim PaymentAmo untFormatt ed(), REQU IRED, 0, 1 8, StringF ormat.RPAD SPACES));
  1354                                      sbDtlRec .append(pa ymentDataE xtraction. getClaimPa ymentAmoun tFormatted () );
  1355                                      delimit( sbDtlRec);
  1356  
  1357  
  1358                                      // 36 -  Payment da te DONE
  1359   // payment DataExtrac tion.setCl aimAdjudic ationPayme ntDate(thi s.sClaimKe y);
  1360                                      sbDtlRec .append(fo rmatOutput String(pay mentDataEx traction.g etClaimAdj udicationP aymentDate (), OPTION AL, 8, 8,  StringForm at.RPADSPA CES));
  1361  
  1362  
  1363                                      // 37 -   Check EFT /Date - DO NE
  1364   // payment DataExtrac tion.setCh eckDateAnd Number(thi s.sClaimKe y);
  1365                                      sbDtlRec .append(fo rmatOutput String(pay mentDataEx traction.g etCheckDat e(), OPTIO NAL, 8, 8,  StringFor mat.RPADSP ACES));
  1366  
  1367  
  1368                                      // 38 Ch eck/EFT Nu mber - DON E
  1369                                      sbDtlRec .append(fo rmatOutput String(pay mentDataEx traction.g etCheckNum ber(), OPT IONAL, 1,  16,  Strin gFormat.RP ADSPACES)) ;
  1370  
  1371  
  1372                                      // NOTE:  uses orig inal code
  1373                                      // 39 -  Bill Type
  1374                                      sbDtlRec .append(fo rmatOutput String(cla im.getBill TypeCd(),  OPTIONAL,  1, 3, Stri ngFormat.R PADSPACES) );
  1375  
  1376  
  1377   // #40 - P ayer Claim  Identific ation Numb er - DONE
  1378                                      sbDtlRec .append(th is.sClaimK ey);
  1379                                      delimit( sbDtlRec);
  1380  
  1381  
  1382   // NOTE: u ses origin al code
  1383   // #41 - P atient Acc ount Numbe r - DONE
  1384                                      sbDtlRec .append(fo rmatOutput String(rep osClaim.ge tClm01ptAc ctNbr(), R EQUIRED, 1 , 50, Stri ngFormat.R PADSPACES) );
  1385  
  1386  
  1387  
  1388  
  1389                                      // #42 P harmacy Pr escription  Number
  1390   // payment DataExtrac tion.setPh armacyPres criptionNu mber(this. sClaimKey) ;
  1391                                      sbDtlRec .append(fo rmatOutput String(pay mentDataEx traction.g etPharmacy Prescripti onNumber() , OPTIONAL , 1, 50, S tringForma t.RPADSPAC ES)); //Ph armacy Pre scription  Number
  1392  
  1393  
  1394  
  1395                                      // #43 V oucher Ide ntifier
  1396                                      sbDtlRec .append(DE FAULT_NULL );
  1397                                      delimit( sbDtlRec);
  1398  
  1399                                      // #44 A pplication  of Locati on System  Identifier
  1400                                      sbDtlRec .append(DE FAULT_NULL );
  1401                                      delimit( sbDtlRec);
  1402  
  1403                                      // #45 G roup Numbe r
  1404                                      sbDtlRec .append(DE FAULT_NULL );
  1405  
  1406                                      delimit( sbDtlRec);
  1407  
  1408                                      sStartDa te = new S impleDateF ormat("yyy yMMdd").fo rmat(claim .getBeginS erviceDate ());
  1409                                      sEndDate  = new Sim pleDateFor mat("yyyyM Mdd").form at(claim.g etEndServi ceDate());
  1410  
  1411  
  1412                                      sbDtlRec .append(sS tartDate);
  1413                                      delimit( sbDtlRec);
  1414  
  1415                                      sbDtlRec .append(sE ndDate);
  1416  
  1417   }catch(Exc eption e)  {
  1418           er roredKeys. add(this.c laimKey);
  1419           LO GGER.error ("createPr imaryDetai lRec() - E rror getti ng claim i nfo on Cla im Key: {} ",  this.s ClaimKey);
  1420       LOGGER .error(e.g etMessage( ), e);
  1421       contin ue;
  1422   }
  1423  
  1424   /********* ********** ********** ********** ********** ******* EN D OF OUTPU T SECTION  ********** ********** ********** ********** ********** ********** ********** ******/
  1425                                      cumulati veDetailSi ze+=sbDtlR ec.length( );
  1426  
  1427                         this.vCsFi le.print(s bDtlRec);
  1428                         this.vCsFi le.print(C RLF);
  1429  
  1430  
  1431                                      this.vCs File.flush ();
  1432  
  1433   // clear p revious va lues in St ringBuffer  - DO NOT  EDIT THIS  LINE.
  1434                                      sbDtlRec .setLength (0);
  1435  
  1436  
  1437                //Create  claim sta tus lines  for this c laim
  1438                         writeStcCl aimRec(cla im, "A2",  "20", "",  this.vCsFi le);
  1439  
  1440                         writeDTLRe c(this.vCs File);
  1441  
  1442  
  1443   //TODO UNC OMMENT TO  UPDATE REC ORDS...... .
  1444  
  1445   updateWrit tenRecordJ DBC(sClaim Key);
  1446  
  1447   if(DEBUG)  {
  1448            S ystem.out. println("\ nCreatePri maryDetail Rec() - up dateWritte nRecordJDB C() done   - time is. ....");
  1449            g etNow();
  1450   }
  1451  
  1452  
  1453                                                                         // out put file h anding....
  1454                                                       ++ count;
  1455  
  1456  
  1457                                                       fi leSize = c sFile.leng th();
  1458  
  1459                                                       //  if the fi le size is  between m ax and cut off, go to  new file
  1460                                                       if ( fileSize  > CUT_OFF _FILE_SIZE  && (fileS ize < MAX_ FILE_SIZE)   ) {
  1461  
  1462                                                                // c reate new  output fil e and cont inue
  1463                                                                try  {
  1464  
  1465                                                                         // 7/1  write foo ter....
  1466                                                                         create TrlRec(thi s.vCsFile) ;
  1467  
  1468                                                                         // 7/1  reset cou nter
  1469                                                                         this.r owCount =  2;
  1470  
  1471                                                                         // flu sh it, clo se it, kil l it....
  1472                                                                         this.v CsFile.flu sh();
  1473                                                                         this.v CsFile.clo se();
  1474                                                                         this.v CsFile=nul l;
  1475  
  1476                                                                         // cre ate new ou tput file
  1477                                                                         this.c sFile = cr eateNewOut putFile(fi lePath);
  1478                                                                         // ass ign writer
  1479                                                                         this.v CsFile = n ew PrintWr iter(new F ileOutputS tream(csFi le));
  1480  
  1481                                                                         // 7/1  write new  header fi le
  1482                                                                         create HdrRec(thi s.vCsFile) ;
  1483                                                                } ca tch (FileN otFoundExc eption e)  {
  1484                                                                         System .out.print ln("create PrimaryDet ailRec() -  File Not  Found Exce ption: " +  e.getMess age());
  1485                                                                         e.prin tStackTrac e();
  1486                                                                LOGG ER.error(" createPrim aryDetailR ec() - Fil e Not Foun d Exceptio n:()" + e. getMessage ());
  1487                                                                LOGG ER.error(e .getMessag e(), e);
  1488                                                                } ca tch(Except ion x) {
  1489                                                                         System .out.print ln("create PrimaryDet ailRec() -  General E xception:  " + x.getM essage());
  1490                                                                         x.prin tStackTrac e();
  1491                                                                LOGG ER.error(" createPrim aryDetailR ec() - Gen eral Excep tion()" +  x.getMessa ge());
  1492                                                                LOGG ER.error(x .getMessag e(), x);
  1493                                                                }        // end  if
  1494  
  1495                                                       }        // e nd try
  1496  
  1497                                                       cl aimsRecord Count++;
  1498  
  1499   // write a ny records  that were  left hang ing after  the batch  update pro cess...
  1500   writeOrpha nedRecords ();
  1501  
  1502                             if(err oredKeys.s ize() > 0  ) {
  1503  
  1504                                      int y =  erroredKey s.size();
  1505                                      for(int  i = 0; i <  y; i++) {
  1506                                               Long x =   (Long) err oredKeys.g et(i);
  1507                                               updateErro redClaim(x .longValue ());
  1508                                      }
  1509                             }
  1510   }
  1511  
  1512   /**
  1513                             System .out.print ln("\n<<<< <<<<<<<<<< <<<<<<<<<< <<<<<<<<<< <<<<<<<<<< <<<<<<<<<< <<<<<<<<<< <<<<<");
  1514                             System .out.print ln("\ncrea tePrimaryD etailRec()  - Claims  processed:  " + count );
  1515                             System .out.print ln("create PrimaryDet ailRec() -  Errored c laims coun t " + erro redKeys.si ze());
  1516   **/
  1517   }       //  END creat ePrimaryDe tailRec()
  1518  
  1519  
  1520  
  1521       /**
  1522         * Wr ite traile r line - n o data req uired
  1523        * @pa ram vCsFil e
  1524        */
  1525       final  void creat eTrlRec(Pr intWriter  vCsFile) {
  1526           St ringBuffer  sbTrlRec  = new Stri ngBuffer() ;
  1527  
  1528  
  1529           sb TrlRec.app end("TRLR" ); //Recor d ID
  1530           de limit(sbTr lRec);
  1531  
  1532  
  1533   // this sh ould be ro w.count-2  at end - i nsert othe r rowCount s in other  lines and  test this  at the ve ry end of  code edits .
  1534           sb TrlRec.app end(String Utils.lPad Zeros(Inte ger.toStri ng(this.ro wCount-2),  10)); //R ecord Coun t  (Note f ormat outp ut will de limit the  string)
  1535  
  1536           vC sFile.prin t(sbTrlRec );
  1537           vC sFile.prin t(CRLF); / /Record Te rminator
  1538  
  1539           th is.trailer Size=sbTrl Rec.length ();
  1540  
  1541           sb TrlRec = n ull;
  1542  
  1543       }
  1544  
  1545       //TWP:  bug fix r ejected st atus had '  not _
  1546       boolea n isReject edClaim()  {
  1547           re turn this. statusCd.e qualsIgnor eCase("REJ ECTED") ||
  1548           th is.statusC d.equalsIg noreCase(" 277U_REJ_S ENT");
  1549       }
  1550  
  1551       boolea n isAccept edClaim()  {
  1552           re turn this. statusCd.e qualsIgnor eCase("BUI LT") ||
  1553           th is.statusC d.equalsIg noreCase(" 277U_ACCPT _SENT");
  1554       }
  1555  
  1556       @Suppr essWarning s("uncheck ed")
  1557       final  EntityName  getEntity Name(Strin g vLoopId,  String vQ ual) {
  1558           St ring qstr  = "select  e from eEn tityName e  " +
  1559                "where e .txnSet.id .fileNumbe r = :file  " +
  1560                "  and e .txnSet.id .st02txnCt lNbr = :ct lnbr " +
  1561                "  and e .loopId =   :loopid "  + vQual;
  1562           Qu ery q = em .createQue ry(qstr);
  1563           q. setParamet er("file",  this.file Nbr);
  1564           q. setParamet er("ctlnbr ", this.st 02CtlNbr);
  1565           q. setParamet er("loopid ", vLoopId );
  1566  
  1567           En tityName e n = null;
  1568           Li st<EntityN ame> entit yNames = q .getResult List();
  1569  
  1570           if  ((entityN ames.size( ) > 0) &&  (entityNam es.get(0)  != null))  {
  1571                en = ent ityNames.g et(0);
  1572           }  else {
  1573                LOGGER.w arn("Error  in gettin g EntityNa me for fil eNumber: { }, st02txn CtlNbr: {} , loopId:  {}, qal: { }",
  1574                    new  Object[] {  this.file Nbr, this. st02CtlNbr , vLoopId,  vQual });
  1575           }
  1576  
  1577           re turn en;
  1578       }
  1579  
  1580       @Suppr essWarning s("uncheck ed")
  1581       final  EntityName  getEntity Name(Strin g vQual) {
  1582           St ring qstr  = "select  e from eEn tityName e  " +
  1583                "where e .txnSet.id .fileNumbe r = :file  " +
  1584                "  and e .txnSet.id .st02txnCt lNbr = :ct lnbr " + v Qual;
  1585           Qu ery q = em .createQue ry(qstr);
  1586           q. setParamet er("file",  this.file Nbr);
  1587           q. setParamet er("ctlnbr ", this.st 02CtlNbr);
  1588  
  1589           En tityName e n = null;
  1590           Li st<EntityN ame> entit yNames = q .getResult List();
  1591  
  1592           if  ((entityN ames.size( ) > 0) &&  (entityNam es.get(0)  != null))  {
  1593                en = ent ityNames.g et(0);
  1594           }  else {
  1595                LOGGER.d ebug("Did  not get En tityName f or fileNum ber: {}, s t02txnCtlN br: {}, lo opId: {},  qal: {} no te:it may  not be req uired",
  1596                    new  Object[] {  this.file Nbr, this. st02CtlNbr , vQual }) ;
  1597           }
  1598  
  1599           re turn en;
  1600       }
  1601  
  1602  
  1603       @Suppr essWarning s("uncheck ed")
  1604       final  PersonInfo  getPerson Name(Strin g vSsn) {
  1605           Qu ery q = em .createQue ry(
  1606                    "sel ect p from  foPersonI nfo p wher e p.person Id = :id " );
  1607           q. setParamet er("id", v Ssn);
  1608  
  1609           Pe rsonInfo p i = null;
  1610           Li st<PersonI nfo> pis =  q.getResu ltList();
  1611  
  1612           if  ((pis.siz e() > 0) & & (pis.get (0) != nul l)) {
  1613                pi = (Pe rsonInfo)  pis.get(0) ;
  1614           }  else {
  1615                LOGGER.d ebug("Unab le to get  PersonInfo  for perso n Id: {}",  vSsn);
  1616           }
  1617  
  1618           re turn pi;
  1619       }
  1620  
  1621       @Suppr essWarning s("uncheck ed")
  1622       final  Demographi cInfo getD emographic Info() {
  1623           St ring qstr  = "select  d from eDe mographicI nfo d " +
  1624                "where d .txnSet.id .fileNumbe r = :file  " +
  1625                "  and d .txnSet.id .st02txnCt lNbr = :ct lnbr " +
  1626                "  and d .nm109sbsr Id = :sbcr id " +
  1627                "  and d .loopId in  ('2010BA' , '2010CA' )";
  1628           Qu ery q = em .createQue ry(qstr);
  1629           q. setParamet er("file",  this.file Nbr);
  1630           q. setParamet er("ctlnbr ", this.st 02CtlNbr);
  1631           q. setParamet er("sbcrid ", this.sb crId);
  1632  
  1633           De mographicI nfo di = n ull;
  1634           Li st dis = q .getResult List();
  1635  
  1636           if  ((dis.siz e() > 0) & & (dis.get (0) != nul l)) {
  1637                di = (De mographicI nfo) dis.g et(0);
  1638   // System. out.printl n("\ngetDe mographicI nfo() - FO UND Demogr aphic Info  for file:  " +  this .fileNbr);
  1639           }  else {
  1640  
  1641  
  1642  
  1643                LOGGER.d ebug("Unab le to get  Demographi c Info for  file: {},  st02txnCt lNbr: {},  nm109sbsrI d: {} ",
  1644                    new  Object[] {  this.file Nbr, this. st02CtlNbr , this.sbc rId });
  1645           }
  1646  
  1647           re turn di;
  1648       }
  1649  
  1650  
  1651  
  1652       final  StringBuff er fillErr orCodes(St ringBuffer  sbDtlRec,  String vE rrCd) {
  1653           if  (!(vErrCd .equals("" ))) {
  1654                String[]  tkns = vE rrCd.split (":");
  1655  
  1656                if (tkns [0] != nul l) {
  1657                    sbDt lRec.appen d(formatOu tputString (tkns[0],  OPTIONAL,  2, 3,
  1658                             String Format.RPA DSPACES));  //Claim S tatus Cate gory Code
  1659                } else {
  1660                    sbDt lRec.appen d(formatOu tputString ("", OPTIO NAL, 2, 3,
  1661                             String Format.RPA DSPACES));  //Claim S tatus Cate gory Code
  1662                }
  1663  
  1664                if (tkns [1] != nul l) {
  1665                    sbDt lRec.appen d(formatOu tputString (tkns[1],  OPTIONAL,  2, 3,
  1666                             String Format.RPA DSPACES));  //Claim S tatus Code
  1667                } else {
  1668                    sbDt lRec.appen d(formatOu tputString ("", OPTIO NAL, 2, 3,
  1669                             String Format.RPA DSPACES));  //Claim S tatus Code
  1670                }
  1671  
  1672                if (tkns .length >  2) {
  1673                    if ( tkns[2] !=  null) {
  1674                         sbDtlRec.a ppend(form atOutputSt ring(tkns[ 2], OPTION AL, 2, 3,
  1675                                 St ringFormat .RPADSPACE S)); //Ent ity Code X
  1676                    } el se {
  1677                         sbDtlRec.a ppend(form atOutputSt ring("", O PTIONAL, 2 , 3,
  1678                                 St ringFormat .RPADSPACE S)); //Ent ity Code X
  1679                    }
  1680                } else {
  1681                    sbDt lRec.appen d(formatOu tputString ("", OPTIO NAL, 2, 3,
  1682                             String Format.RPA DSPACES));  //Entity  Code X
  1683                }
  1684           }
  1685  
  1686           re turn sbDtl Rec;
  1687       }
  1688  
  1689  
  1690       privat e void del imit(Strin gBuffer sb ) {
  1691           sb .append(DE LIMITER);
  1692       }
  1693  
  1694  
  1695  
  1696       public  int getAv ailableRec ords() {
  1697  
  1698           
  1699           
  1700           En tityTransa ction txUp dateDataba se = em.ge tTransacti on();
  1701           Qu ery q;
  1702                List<?>  l;
  1703                Iterator <?> it;
  1704                int coun t = 0;
  1705  
  1706                String s qlGetStagi ngTableRec ordCount =  "SELECT c ount(*)    FROM fpps_ owner.clai ms c , e_r epos.claim  e " +
  1707                                      " WHERE  " +
  1708                                      " e.clai m_key = c. edi_claim_ key " +                                                                                     // par am b                                                                                                                // p aram e
  1709                                      " and c. claim_stat us_cd = 'C OMPLETE' a nd (sysdat e-c.date_m odified) < = " + this .iLookBack Days + "   and (sysda te-c.date_ modified)  >= " + thi s.iLookBac kEndDays +  " " +
  1710                                      " and no t exists ( SELECT 1 F ROM fpps_o wner.stg_2 77 s WHERE  s.claim_i ndex = c.c laim_index  and s.cla im_status_ cd = 'SENT ') ";
  1711  
  1712                                               try {
  1713  
  1714                                                     q =  this.em.cr eateNative Query(sqlG etStagingT ableRecord Count);
  1715                                                     l =  q.getResul tList();
  1716                                                     it =  l.iterato r();
  1717  
  1718  
  1719                                                     Obje ct row = ( BigDecimal ) it.next( );
  1720  
  1721                                                              if(row  != null)  {
  1722  
  1723                                                                         String  tmp = row .toString( );
  1724                                                                         count  = new Inte ger(tmp).i ntValue();
  1725                                                              }
  1726  
  1727                                          } ca tch(Except ion ex) {
  1728                                                       LO GGER.error ("getAvail ableRecord s() ERROR:  " + ex.ge tMessage() );
  1729                                      }
  1730  
  1731           re turn count ;
  1732       }
  1733  
  1734  
  1735  
  1736        @Supp ressWarnin gs({ "rawt ypes", "un checked" } )
  1737       /** Th is method  collects d etail reco rds for th e current  claim
  1738        * @au thor Bill  Blackmon
  1739        * @re turn List
  1740        */
  1741           pr ivate List  getDetail Records()  {
  1742  
  1743           Li st<DetailR ecord> det ailRecords  = new Arr ayList();
  1744  
  1745  
  1746                    // n ew code fo llows - al l of this  needs to b e refactor ed out to  PaymentDat aExtractio n when fin ished.....
  1747                    deta ilRecords  = paymentD ataExtract ion.getDet ailRecords (this.sCla imKey);
  1748  
  1749  
  1750           re turn detai lRecords;
  1751       }
  1752  
  1753       /**
  1754        * Thi s method p rints the  detail rec ord sectio n of the o utput file
  1755        * @au thor Bill  Blackmon
  1756        * @pa ram claim
  1757        * @pa ram vCsFil e
  1758        */
  1759      // @Sup pressWarni ngs({ "raw types", "u nchecked"  })
  1760   //      pr ivate void  writeDTLR ec(Claim c laim, Prin tWriter vC sFile) {
  1761  
  1762                    priv ate void w riteDTLRec (PrintWrit er vCsFile ) {
  1763           //  list of d etail reco rds
  1764           @S uppressWar nings("unc hecked")
  1765                    List <DetailRec ord> detai lsList = g etDetailRe cords();
  1766  
  1767           fo r(DetailRe cord dRec:  detailsLi st)
  1768           {
  1769   // System. out.printl n("IN DETA IL SECTION  - detail  rec id is:  " + dRec. toString() );
  1770                                      StringBu ffer sbDTL Rec = new  StringBuff er();
  1771  
  1772  
  1773  
  1774   // 1 Recor d ID
  1775                                      sbDTLRec .append("D TL");
  1776                                      delimit( sbDTLRec);
  1777  
  1778                                               // #2 reco rd number  - current  record
  1779                                               sbDTLRec.a ppend(form atOutputSt ring(Integ er.toStrin g(this.row Count), RE QUIRED, 1,  10, Strin gFormat.LP ADZERO));  //rowCount
  1780                                               this.rowCo unt++;
  1781  
  1782  
  1783                                               // 3
  1784                                               //Payer ID  (Emdeon A ssigned Nu mber) - Re quired, St ring
  1785                                               sbDTLRec.a ppend(PAYE R_ID);
  1786                                               delimit(sb DTLRec);
  1787  
  1788                                               // spec. # 4 Payer Cl aim Identi fication N umber - Re quired, St ring
  1789                                               sbDTLRec.a ppend(this .sClaimKey );
  1790                                               delimit(sb DTLRec);
  1791  
  1792                                               // #5 Line  Item Cont rol Number
  1793                                               sbDTLRec.a ppend(dRec .getLineIt emControlN umber());
  1794                                               delimit(sb DTLRec);
  1795  
  1796  
  1797                                               // # Servi ce Qualifi er ID
  1798                                               sbDTLRec.a ppend(dRec .getServic eQualifier ());
  1799                                               delimit(sb DTLRec);
  1800  
  1801                                               // #7 Serv ice Identi fication C ode -
  1802  
  1803                                               sbDTLRec.a ppend(dRec .getProcCo de());
  1804                                               delimit(sb DTLRec);
  1805   // System. out.printl n("detail  7 PROC COD E: = " + s bDTLRec.to String());
  1806  
  1807  
  1808                                               // DONE
  1809                                               // #8 Proc edure Modi fier 1
  1810                                               sbDTLRec.a ppend(dRec .getProced ureModifie r1());
  1811                                                        d elimit(sbD TLRec);
  1812  
  1813  
  1814                                                       //  DONE
  1815                                                       //  #9 Proced ure Modifi er 2
  1816                                                        s bDTLRec.ap pend(dRec. getProcedu reModifier 2());
  1817                                                        d elimit(sbD TLRec);
  1818  
  1819                                                       //  DONE
  1820                                                       //  #10  Proc edure Modi fier 3
  1821                                                        s bDTLRec.ap pend(dRec. getProcedu reModifier 3());
  1822                                                        d elimit(sbD TLRec);
  1823  
  1824                                                       //  DONE
  1825                                                       //  #11  Proc edure Modi fier 4
  1826                                                        s bDTLRec.ap pend(dRec. getProcedu reModifier 4());
  1827                                                        d elimit(sbD TLRec);
  1828  
  1829                                                       //  END OF PR OCEDURE/SE RVICE MODI FIERS
  1830  
  1831                                                       //  DONE
  1832                                                       //       #12  Line Item  Charge Amo unt
  1833                                                       sb DTLRec.app end(format OutputStri ng(dRec.ge tBilledAmo untFormatt ed(), OPTI ONAL, 1, 1 8, StringF ormat.LPAD ZERO));
  1834   // System. out.printl n("writeDT LRec() FIE LD 12 bill ed amount  claim # :  " + this.s ClaimKey +  " " + sbD TLRec.toSt ring());
  1835  
  1836  
  1837  
  1838   // should  be DEFAULT _ZERO if a mount is e mpty or nu ll
  1839                                                       //  #13 Paid  Amount
  1840                                                       sb DTLRec.app end(format OutputStri ng(dRec.ge tPaidAmoun tFormatted (), OPTION AL, 1, 18,  StringFor mat.LPADZE RO));
  1841   // System. out.printl n("writeDT LRec() FIE LD 13 paid  amount cl aim # : "  + this.sCl aimKey + "  " + sbDTL Rec.toStri ng());
  1842  
  1843  
  1844  
  1845                                                       //  DONE
  1846                                                       //  14 Revenu e Code
  1847                                                       sb DTLRec.app end(dRec.g etRevenueC ode());
  1848                                                       de limit(sbDT LRec);
  1849   // System. out.printl n("detail  out 14 REV ENUE CODE:  " + sbDTL Rec.toStri ng());
  1850  
  1851                                                       //  DONE
  1852                                                       //  15 Quanti ty(Units o f Service)  Optional,  Numeric,  min-max =  1 15 DEFAU LT VALUE I S 1
  1853                                                       sb DTLRec.app end(dRec.g etBilledUn its());
  1854                                                       de limit(sbDT LRec);
  1855                                                       //  System.ou t.println( "detail ou t: " + sbD TLRec.toSt ring());
  1856  
  1857                                                       //  DONE
  1858                                                       //  16 EMDEON  Claim Num ber OPTION AL AN 1 50  Emdeon ID  if an Emd eon Claim.
  1859                                                       sb DTLRec.app end(format OutputStri ng(dRec.ge tEmdeonCla imNumber() , OPTIONAL , 1, 50, S tringForma t.RPADSPAC ES));
  1860                                                       //  System.ou t.println( "detail ou t: " + sbD TLRec.toSt ring());
  1861  
  1862                                                       //  DONE
  1863                                                       //  17 Date o f Service  Start Requ ired Date
  1864                                                        s bDTLRec.ap pend(forma tOutputStr ing(dRec.g etServiceF romDateFor matted(),  OPTIONAL,  8, 8, Stri ngFormat.R PADSPACES) );
  1865                                                        / / System.o ut.println ("detail o ut: " + sb DTLRec.toS tring());
  1866  
  1867                                                       //  DONE
  1868                                                       //  18 Servic e to Date
  1869                                                        s bDTLRec.ap pend(dRec. getService ToDateForm atted());
  1870   // System. out.printl n("writeDT LRec - det ail out: "  + sbDTLRe c.toString ());
  1871  
  1872  
  1873  
  1874                                                       //  END OF TH E LINE.... ...
  1875                                                       sb DTLRec.app end(CRLF);  //Record  Teminator  new for 50 10
  1876                                                       //  System.ou t.println( "writeDTLR ec() - fin al String  is: " + sb DTLRec);
  1877  
  1878                                               vCsFile.pr int(sbDTLR ec); //TWP  Changed t o print ra ther than  println si nce I am e xplicitly  adding CRL F
  1879                                               vCsFile.fl ush();
  1880  
  1881  
  1882                                               sbDTLRec =  null;
  1883                                               this.bInCl aim=false;
  1884  
  1885                                               writeStcDe tailRec("A 2", "20",  "", vCsFil e, dRec);
  1886  
  1887           }        // E ND OF DETA IL LOOP
  1888  
  1889  
  1890  
  1891    }      //  end write DTLRec()
  1892  
  1893                         /**
  1894                          * This me thod is us ed to writ e the STC  for a deta il record.
  1895                          * @author  Bill Blac kmon
  1896                         * @param p ayerClaimI d
  1897                         * @param s tatusCateg oryCode
  1898                         * @param s tatusCode
  1899                         * @param e ntityCode
  1900                         * @param v CsFile
  1901                         */
  1902  
  1903                                      private  void write StcDetailR ec(String  statusCate goryCode,  String sta tusCode,
  1904                                               String ent ityCode, P rintWriter  vCsFile,  DetailReco rd dRec) {
  1905   // FIELD 1  - Record  ID
  1906                                      StringBu ffer sbSTC Rec = new  StringBuff er();
  1907                                      sbSTCRec .append("S TC"); //Re cord ID
  1908                                      delimit( sbSTCRec);
  1909  
  1910  
  1911                                      // sbSTC Rec.append (formatOut putString( Integer.to String(thi s.cnt), RE QUIRED, 1,  10, Strin gFormat.LP ADZERO));  //Record N umber - mu st be in s ync with o ther recor ds
  1912  
  1913   // FIELD 2       - Ro w Count
  1914                                      sbSTCRec .append(fo rmatOutput String(Int eger.toStr ing(this.r owCount),  REQUIRED,  1, 10, Str ingFormat. LPADZERO)) ; // rowCo unt
  1915                                      this.row Count++;
  1916  
  1917  
  1918   // FIELD 3       - Pa yer ID
  1919                                      sbSTCRec .append(PA YER_ID);
  1920                                      delimit( sbSTCRec);
  1921  
  1922   // FIELD 4  - Payer C laim Ident ification  Number
  1923                                      sbSTCRec .append(fo rmatOutput String(thi s.sClaimKe y, REQUIRE D, 1, 50,  StringForm at.RPADSPA CES));
  1924  
  1925  
  1926   // Field 5  - Line It em Control  Number
  1927                                               sbSTCRec.a ppend(dRec .getLineIt emControlN umber());
  1928                                               delimit(sb STCRec);
  1929                                               // System. out.printl n("writeSt cDetailRec () - after  lineItemC ontrolNumb er: " + sb STCRec);
  1930  
  1931   // Field 6  - Status  Informatio n Effectiv e Date - B .B. - inhe rited
  1932                                      Date tod ay = Calen dar.getIns tance().ge tTime();
  1933                                      String d ateFormat  = "yyyyMMd dHHmmss";
  1934                                      sbSTCRec .append(ne w SimpleDa teFormat(d ateFormat) .format(to day));
  1935                                      delimit( sbSTCRec);
  1936  
  1937  
  1938  
  1939  
  1940   // Field # 7 - Claim  Status Cat egory Code
  1941   // f1 or f 2 at this  level, det ermines if  there is  a paid amt  f1 else f 2
  1942   // F1 = PA ID, F2 = N O PAYMENTS , F0 MIXED  (claim le vel ONLY)  - paid and  unpaid in  detail re cords -
  1943   // NO MIXE D IN DETAI L RECORDS
  1944   // amount  of 69.3 fa ils for in put string ......
  1945  
  1946  
  1947   /**
  1948    The value  of 1 shou ld be used  only if N OT paid, s o only for  F0 or F2.   65 is on ly used fo r a paid ( F1).
  1949  
  1950   PAID AMT.  IS NEGATIV E........
  1951   1.      DT L-FL12 (Li ne Item Ch arge Amoun t) = 20.00  and DTL-F L13 (Line  Item Provi der Paymen t Amount)  = -10.00:
  1952   Currently  report as  F2/1, plea se change  to F1/65
  1953   2.      DT L-FL12 (Li ne Item Ch arge Amoun t) = -20.0 0 and DTL- FL13 (Line  Item Prov ider Payme nt Amount)  = -10.00.  use F1/65 .
  1954   Currently  report as  F2/1, plea se change  to F1/65
  1955  
  1956    */
  1957  
  1958   /**
  1959    * New log ic from Jo hn S., 6/2 6....
  1960   Regarding  the F0, F1 , F2 issue .  I belie ve the fol lowing  sh ould cover  the condi tions for  when to us e which va lue.
  1961   For the ST C record a ssociated  with the D TL lines,  if there i s a paymen t and it i s not equa l to 0.00,
  1962   then the C LAIM STATU S CAT CODE  = F1 and  CLAIM STAT US CODE =  65 If paym ent is bla nk, or 0.0 0, the CAT  CODE=F2 a nd STATUS  CODE=1
  1963  
  1964    */
  1965                             BigDec imal iPaid Amt = dRec .getPaidAm ount();
  1966  
  1967   // Field 7  - Claim S tatus CATE GORY Code
  1968  
  1969   // changed  7/3 to ha ndle null  paid amts.
  1970   // logic o k'ed by An ne 7/3
  1971                             if(iPa idAmt == n ull) {
  1972  
  1973   // System. out.printl n("writeSt cDetailRec () - NULL  PAID AMT.  for id: "  + this.cla imKey);
  1974                                      sbSTCRec .append("F 2");
  1975                                      this.sta tusCode="1 ";
  1976  
  1977                             } else  {
  1978  
  1979                                      int x =  iPaidAmt.i ntValue();
  1980  
  1981                                      if( (x >  0) || (x  < 0) )
  1982                                      {
  1983                                               sbSTCRec.a ppend("F1" );
  1984                                               this.statu sCode="65" ;
  1985                                      } else {         //  x - 0 pay ment
  1986                                               sbSTCRec.a ppend("F2" );
  1987                                               this.statu sCode="1";
  1988                                      }
  1989                             }
  1990  
  1991  
  1992   delimit(sb STCRec);
  1993  
  1994  
  1995   // System. out.printl n("writeSt cDetailRec () - NEW S TATUS CODE  IS: " + t his.status Code);
  1996  
  1997   // Field 8  - Claim S tatus Code
  1998                              sbSTC Rec.append (this.stat usCode);
  1999                              delim it(sbSTCRe c);
  2000   // end CLA IM STATUS  CATEGORY C ODE
  2001  
  2002   // Field 9  - Entity  Code - OPT IONAL - no  set to an y value in  existing  code....
  2003                         sbSTCRec.a ppend(enti tyCode);
  2004                         delimit(sb STCRec);
  2005  
  2006  
  2007  
  2008   // Field # 10 - Data  In Error ( 'for futur e use') -  set to emp ty string
  2009                             sbSTCR ec.append( DEFAULT_NU LL); //Dat a In Error  - we do n ot have th is from wh at I can t ell so lea ve it blan k - .B.B.  THIS CAME  WITH THE E XISTING CO DE - leavi ng as is
  2010                             delimi t(sbSTCRec );
  2011  
  2012   // Field 1 1 - Emdeon  Status Co de
  2013                             sbSTCR ec.append( DEFAULT_NU LL); // Em deon Statu s Code
  2014  
  2015                    sbST CRec.appen d(CRLF); / /Record Te minator ne w for 5010
  2016  
  2017                    vCsF ile.print( sbSTCRec);  //TWP Cha nged to pr int rather  than prin tln since  I am expli citly addi ng CRLF
  2018  
  2019                    vCsF ile.flush( );
  2020                    sbST CRec = nul l;
  2021       }   //  end write STCDetailR ec()
  2022  
  2023  
  2024  
  2025  
  2026  
  2027           /* *
  2028            *  NOTE - ch eck to see  where the  args pass ed in are  coming fro m and make  sure that  they are  correct if  they are  being set  at the Cla im level.
  2029            *
  2030        * Thi s method w as inherit ed from In itial Paym ent scheme ........ne eds examin ation and  refactorin g for Fee  purposes
  2031        * @pa ram claim
  2032        * @pa ram payerC laimId
  2033        * @pa ram status CategoryCo de
  2034        * @pa ram status Code
  2035        * @pa ram entity Code
  2036        * @pa ram vCsFil e
  2037        */
  2038  
  2039       privat e void wri teStcClaim Rec(Claim  claim, Str ing status CategoryCo de, String  statusCod e,
  2040                    Stri ng entityC ode, Print Writer vCs File) {
  2041  
  2042   // #1 Reco rd ID
  2043           St ringBuffer  sbSTCRec  = new Stri ngBuffer() ;
  2044           sb STCRec.app end("STC") ; //Record  ID
  2045           de limit(sbST CRec);
  2046  
  2047   // #2 Reco rd Number
  2048   //         sbSTCRec.a ppend(form atOutputSt ring(Integ er.toStrin g(this.cnt ),  REQUIR ED, 1, 10,  StringFor mat.LPADZE RO)); //Re cord Numbe r - must b e in sync  with other  records
  2049  
  2050  
  2051   // #2 Reco rd Number
  2052           sb STCRec.app end(format OutputStri ng(Integer .toString( this.rowCo unt),  REQ UIRED, 1,  10, String Format.LPA DZERO)); / / rowCount
  2053   // System. out.printl n("writeSt cClaimRec( ) - output  is: " + s bSTCRec.to String());
  2054           th is.rowCoun t++;
  2055  
  2056   // #3 Paye r ID
  2057           sb STCRec.app end(PAYER_ ID);
  2058           de limit(sbST CRec);
  2059  
  2060   // #4 Paye r Claim Id entificati on Number
  2061           sb STCRec.app end(format OutputStri ng(this.sC laimKey, R EQUIRED, 1 , 50, Stri ngFormat.R PADSPACES) );
  2062  
  2063           // TWP What d o we use f or an iden tification  number -  we have no t assigned  it yet
  2064           // for a clai m that has  only been  accepted  ???? we ha ve a GUID
  2065           // Should we  really be  running th is file af ter the FP PS PL/SQL  loading ru ns so we c an assign  it a claim  index?
  2066  
  2067  
  2068   // field #  5 - Line  Item Contr ol Number
  2069   // always  set to ""  for Claim  level reco rd - accor ding to Ma ry Simons  3/19/2013
  2070           sb STCRec.app end("");
  2071           de limit(sbST CRec);
  2072  
  2073   // field # 6 - Status  Informati on Effecti ve Date -  B.B. - inh erited
  2074           Da te today =  Calendar. getInstanc e().getTim e();
  2075           St ring dateF ormat = "y yyyMMddHHm mss";
  2076           sb STCRec.app end(new Si mpleDateFo rmat(dateF ormat).for mat(today) );
  2077           de limit(sbST CRec);
  2078  
  2079  
  2080  
  2081  
  2082   // Field # 7 - Claim  Status Cat egory Code
  2083   // F0 ('mi xed') can  only be on  CLM's STC  not DTL's  STC.
  2084   //  if cod e is F0 an d we are i n the deta il section , swap cod e to F1 un til detail  records a re found a nd read
  2085   //  rec co unt of 3,  2nd  claim  is the pr oblem.....
  2086   //  System .out.print ln("writeS tcClaimRec () - recor d count is : " + this .cnt);
  2087   /**
  2088    * f1 in d etail, f1  in claim
  2089    * f2 in d etail f2 i n claim
  2090    * f1 and  f2 in deta il, f0 in  claim leve l
  2091  
  2092    */
  2093  
  2094  
  2095   // System. out.printl n("writeSt cClaimRec( ) - claim  status cat egory code  at top is : " + this .claimStat usCategory Code);
  2096  
  2097  
  2098   if(this.cl aimStatusC ategoryCod e.equalsIg noreCase(" "))  {
  2099   //      Sy stem.out.p rintln("wr iteStcClai mRec() - c laimStatus CategoryCo de IS NULL ");
  2100   }
  2101  
  2102  
  2103   if ( (this .claimStat usCategory Code.equal sIgnoreCas e("F0")) & & (this.bI nClaim ==  false) ) {
  2104                    this .claimStat usCategory Code="F1";
  2105   // System. out.printl n("writeSt cClaimRec( ) - STATUS  CATEGORY  CODE CHANG ED to F1") ;
  2106   }
  2107  
  2108  
  2109   // Field # 7 Claim St atus Categ ory Code
  2110           sb STCRec.app end(this.c laimStatus CategoryCo de);
  2111  
  2112   // System. out.printl n("writeSt cClaimRec( ) - claimS tatusCateg oryCode is : " + this .claimStat usCategory Code);
  2113  
  2114           de limit(sbST CRec);
  2115  
  2116   // Field # 8 - Claim  Status Cod e
  2117           sb STCRec.app end(this.s tatusCode) ;
  2118           de limit(sbST CRec);
  2119   // System. out.printl n("STC OUT  after Fin alized Cod es Setting  is: " + s bSTCRec.to String());
  2120  
  2121  
  2122  
  2123   // Field # 9 - Entity  Code - OP TIONAL - n o set to a ny value i n existing  code....
  2124           sb STCRec.app end(entity Code);
  2125           de limit(sbST CRec);
  2126  
  2127  
  2128  
  2129   // Field # 10 - Data  In Error ( 'for futur e use') -  set to emp ty string
  2130           sb STCRec.app end(""); / /Data In E rror - we  do not hav e this fro m what I c an tell so  leave it  blank - .B .B. THIS C AME WITH T HE EXISTIN G CODE - l eaving as  is
  2131           de limit(sbST CRec);
  2132  
  2133   // Field # 11 Emdeon  Status Cod e - OPTION AL - see i f this exi sts elsewh ere?
  2134           sb STCRec.app end(""); / /Emdeon St atus Code  -  THIS CA ME WITH TH E EXISTING  CODE - le aving as i s
  2135  
  2136   // REMOVED  per Chad  Morrison 6 /25
  2137           //  delimit(s bSTCRec);
  2138  
  2139           sb STCRec.app end(CRLF);  //Record  Teminator  new for 50 10
  2140  
  2141           vC sFile.prin t(sbSTCRec ); //TWP C hanged to  print rath er than pr intln sinc e I am exp licitly ad ding CRLF
  2142           vC sFile.flus h();
  2143  
  2144           sb STCRec = n ull;
  2145       }
  2146  
  2147       privat e String f ormatOutpu tString(Ob ject dataT oFormat, b oolean req uired, int  minLength , int maxL ength, Str ingFormat  format) {
  2148           re turn forma tOutputStr ing(dataTo Format, re quired, mi nLength, m axLength,
  2149                format,  true);
  2150       }
  2151  
  2152       /**
  2153        * Thi s method s hould be c alled for  each field  which
  2154        * wil l make the  code abov e basicall y match th e spec.
  2155        * It  will forma t the fiel d to the s pecs given  and delim it
  2156        * eac h value re turned.
  2157        *
  2158        * @pa ram dataTo Format
  2159        * @pa ram minLen ght
  2160        * @pa ram maxLen gth
  2161        * @pa ram format
  2162        * @pa ram delimi t
  2163        * @re turn
  2164        */
  2165       privat e String f ormatOutpu tString(Ob ject dataT oFormat, b oolean req uired, int  minLength , int maxL ength, Str ingFormat  format, bo olean deli mit) {
  2166           // If we don' t have dat a for a re quired fie ld we just  balk righ t now - wh at do you  really wan t to happe n?
  2167           if  ((require d && (data ToFormat = = null)) | | (require d && (data ToFormat i nstanceof  String &&  (((String)  dataToFor mat).trim( ).length()  < 1)))) {
  2168                throw ne w RuntimeE xception(
  2169                    "for matOuputSt ring() run timeExcept ion.");
  2170           }
  2171  
  2172           // We are ass uming if w e send a v alue it mu st meet th e spec min Length and  maxLength
  2173           // But option al fields  may be lef t blank -  i.e. a bla nk field w ill appear  in the ou tput
  2174           // For exampl e see ;; i n the foll owing samp le line ->
  2175           //                                                                                                                 ;nonblan kfield;;no nblankfiel d;
  2176           St ring strin gToReturn  = "";
  2177  
  2178           if  ((dataToF ormat != n ull) &&
  2179                    !(da taToFormat  instanceo f String & &
  2180                    (((S tring) dat aToFormat) .trim().le ngth() < 1 ))) {
  2181                //If the  data need s to be fo rmatted a  specific w ay format  it
  2182                if (form at != null ) {
  2183                    stri ngToReturn  = this.fo rmatString (dataToFor mat, minLe ngth,
  2184                             maxLen gth, forma t);
  2185                } else {
  2186                    stri ngToReturn  = dataToF ormat.toSt ring();
  2187                }
  2188  
  2189                //Check  to see if  the value  complies w ith EMDEON S minimum  length req uirement
  2190                int stri ngLength =  stringToR eturn.leng th();
  2191  
  2192                if (stri ngLength <  minLength ) {
  2193                    thro w new Runt imeExcepti on(
  2194                         "Please sp ecify a fo rmatter fo r this dat a so it ca n be forma tted to me et the min imum lengh t requirem ent." +
  2195                         dataToForm at);
  2196                }
  2197  
  2198                //Check  to see if  the value  complies w ith EMDEON S max leng th require ment -
  2199                //If it  does not w e make tru ncate it -  this seem s dangerou s - TWP.
  2200                if (stri ngLength >  maxLength ) {
  2201                    stri ngToReturn  = truncat e(stringTo Return, da taToFormat ,
  2202                             maxLen gth);
  2203                }
  2204           }
  2205  
  2206           if  (delimit)  {
  2207                stringTo Return +=  DELIMITER;
  2208           }
  2209  
  2210           re turn strin gToReturn;
  2211       }
  2212  
  2213  
  2214       privat e String t runcate(St ring forma ttedString , Object d ataToForma t,
  2215           in t maxLengt h) {
  2216           in t beginInd ex = forma ttedString .length()  - maxLengt h;
  2217           St ring strin gToReturn  = formatte dString.su bstring(be ginIndex);
  2218  
  2219           LO GGER.warn( "Truncatin g data fro m " + form attedStrin g + " to "  +
  2220                stringTo Return);
  2221  
  2222           re turn strin gToReturn;
  2223       }
  2224  
  2225       /**
  2226        * Thr ows a runt ime except ion if it  can not fo rmat the d ata to the  specifica tion given .
  2227        * Wil l also thr ow an exce ption if n ull is pas sed in - i t expects  to format  a string.
  2228        *
  2229        * @pa ram string ToFormat s tring to b e formatte d
  2230        * @pa ram minLen gth                   minimum le ngth of st ringToForm at
  2231        * @pa ram maxLen gth          maximum  length of  stringToFo rmat
  2232        * @pa ram format                               fo rmat
  2233        * @re turn Strin g                             fo rmatted st ring
  2234        */
  2235       privat e String f ormatStrin g(Object s tringToFor mat, int m inLength,
  2236           in t maxLengt h, StringF ormat form at) {
  2237           St ring strin gToReturn  = null;
  2238  
  2239           if  ((stringT oFormat !=  null) &&  stringToFo rmat insta nceof BigD ecimal) {
  2240                stringTo Format = s tringToFor mat.toStri ng();
  2241           }
  2242  
  2243           if  ((stringT oFormat !=  null) &&
  2244                    (((S tring) str ingToForma t).length( ) < minLen gth)) {
  2245                if (Stri ngFormat.R PADSPACES  == format)  {
  2246                    stri ngToReturn  = StringU tils.padSt ring((Stri ng) string ToFormat,
  2247                             minLen gth, ' ',  false);
  2248                }
  2249  
  2250                if (Stri ngFormat.L PADZERO ==  format) {
  2251                    stri ngToReturn  = StringU tils.padSt ring((Stri ng) string ToFormat,
  2252                             minLen gth, '0',  true);
  2253                }
  2254           }  else {
  2255                if ((str ingToForma t != null)  &&
  2256                         (((String)  stringToF ormat).len gth() >= m inLength))  {
  2257                    stri ngToReturn  = (String ) stringTo Format;
  2258                }
  2259           }
  2260  
  2261           if  (StringFo rmat.LPADD ECZERO2PLA CES == for mat) {
  2262                stringTo Return = S tringUtils .lPadDecim alZeros2Pl aces((Stri ng) string ToFormat,
  2263                         maxLength) ;
  2264           }
  2265  
  2266           if  (stringTo Return ==  null) {
  2267                throw ne w RuntimeE xception(" Could not  format the  object -  " +
  2268                    stri ngToFormat  +
  2269                    " -  conversion  of this t ype of dat a is not y et support ed.");
  2270           }
  2271  
  2272           re turn strin gToReturn;
  2273       }
  2274  
  2275  
  2276       /**
  2277        *
  2278        * @re turn java. sql.Timest amp for us e in JDBC
  2279        * @au thor Bill  Blackmon
  2280        * @si nce 11/27/ 2013
  2281        */
  2282       privat e static j ava.sql.Ti mestamp ge tCurrentTi meStamp()  {
  2283           ja va.util.Da te today =  new java. util.Date( );
  2284           re turn new j ava.sql.Ti mestamp(to day.getTim e());
  2285       }
  2286  
  2287  
  2288  
  2289       /**
  2290        * @au thor Bill  Blackmon
  2291        * @si nce 12/21/ 2013
  2292        * @re turn java. sql.Timest amp
  2293        */
  2294       public  Timestamp  getRuntim eTimeStamp ()
  2295       {
  2296  
  2297            j ava.util.D ate date=  new java.u til.Date() ;
  2298  
  2299            r eturn new  java.sql.T imestamp(d ate.getTim e());
  2300  
  2301       }
  2302  
  2303  
  2304  
  2305       public  void clea nStagingTa ble() {
  2306  
  2307           En tityTransa ction txUp dateDataba se = em.ge tTransacti on();
  2308           Qu ery q;
  2309                List<?>  l;
  2310                Iterator <?> it;
  2311                int coun t = 0;
  2312  
  2313                String s qlCleanSta gingTable  = "delete  FROM fpps_ owner.STG_ 277 where  claim_stat us_cd = 'S ENT' ";
  2314  
  2315   // System. out.printl n("validat eEreposCla im() - sql  is: " + s qlGetEdiCl aims);
  2316  
  2317  
  2318           tr y {
  2319  
  2320                                                     q =  this.em.cr eateNative Query(sqlC leanStagin gTable);
  2321                                                     l =  q.getResul tList();
  2322                                                     it =  l.iterato r();
  2323  
  2324  
  2325                                                     Obje ct row = ( BigDecimal ) it.next( );
  2326  
  2327                                                              if(row  != null)  {
  2328  
  2329                                                                         String  tmp = row .toString( );
  2330                                                                         count  = new Inte ger(tmp).i ntValue();
  2331  
  2332   // System. out.printl n("validat eEreposCla im() - EDI  claims co unt is: "  + count);
  2333  
  2334                                                              }
  2335  
  2336                                               } catch(Ex ception ex ) {
  2337  
  2338                                               System.out .println(" getStaging TableRecor dCount() E RROR: " +  ex.getMess age());
  2339                                                       ex .printStac kTrace();
  2340                                                       LO GGER.error ("getStagi ngTableRec ordCount()  ERROR: "  + ex.getMe ssage());
  2341                                      }
  2342  
  2343  
  2344  
  2345  
  2346       }
  2347  
  2348  
  2349  
  2350       /**
  2351        * @au thor Bill  Blackmon
  2352        * @si nce 12/21/ 2013
  2353        * @re turn java. sql.Date
  2354        */
  2355       public  java.sql. Date getCu rSqlDate()
  2356       {
  2357           fi nal Calend ar cal = C alendar.ge tInstance( );
  2358           fi nal java.s ql.Date vS qlDate = n ew java.sq l.Date(cal .getTimeIn Millis());
  2359  
  2360           re turn vSqlD ate;
  2361       }
  2362  
  2363  
  2364  
  2365       public  String ge tNowMs() {
  2366  
  2367                  Date d Now = new  Date( );
  2368                  Simple DateFormat  ft =
  2369                  new Si mpleDateFo rmat ("yyy y:mm:dd:hh :mm:ss:ms" );
  2370  
  2371                  String  out = ft. format(dNo w);
  2372                  return  out;
  2373  
  2374       }
  2375  
  2376           pu blic Strin g getNow()  {
  2377  
  2378                  Date d Now = new  Date( );
  2379                  Simple DateFormat  ft =
  2380                  new Si mpleDateFo rmat ("hh: mm:ss:ms") ;
  2381  
  2382                  String  out = ft. format(dNo w);
  2383                  return  out;
  2384                  // Sys tem.out.pr intln(ft.f ormat(dNow ));
  2385           }
  2386  
  2387  
  2388       privat e enum Str ingFormat  {RPADSPACE S,
  2389           LP ADZERO,
  2390           LP ADDECZERO2 PLACES;
  2391       }
  2392  
  2393  
  2394   }