70. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 2/7/2017 12:14:08 PM Eastern Standard 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.

70.1 Files compared

# Location File Last Modified
1 cpss.zip\cpss\src\main\java\gov\va\cpss\service CbsService.java Wed Feb 1 21:07:26 2017 UTC
2 cpss.zip\cpss\src\main\java\gov\va\cpss\service CbsService.java Mon Feb 6 15:14:19 2017 UTC

70.2 Comparison summary

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

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

70.4 Active regular expressions

No regular expressions were active.

70.5 Comparison detail

  1   package go v.va.cpss. service;
  2  
  3   import jav a.sql.Time stamp;
  4   import jav a.util.Arr ayList;
  5   import jav a.util.Cal endar;
  6   import jav a.util.Col lections;
  7   import jav a.util.Com parator;
  8   import jav a.util.Dat e;
  9   import jav a.util.Lis t;
  10   import jav a.util.Map ;
  11   import jav a.util.Map .Entry;
  12   import jav a.util.str eam.Collec tors;
  13  
  14   import org .apache.lo g4j.Logger ;
  15   import org .springfra mework.ste reotype.Se rvice;
  16  
  17   import gov .va.cpss.c obol.Money ;
  18   import gov .va.cpss.d ao.CBSAcco untDAO;
  19   import gov .va.cpss.d ao.CBSSite PatientDAO ;
  20   import gov .va.cpss.d ao.CBSSite StmtDAO;
  21   import gov .va.cpss.d ao.CBSSite TransDAO;
  22   import gov .va.cpss.d ao.CBSStmt DAO;
  23   import gov .va.cpss.d ao.Process StatusDAO;
  24   import gov .va.cpss.m odel.Boole anChar;
  25   import gov .va.cpss.m odel.cbs.C BSSitePati ent;
  26   import gov .va.cpss.m odel.cbs.C BSSiteStmt ;
  27   import gov .va.cpss.m odel.cbs.C BSSiteTran s;
  28   import gov .va.cpss.m odel.cbs.C BSStmt;
  29   import gov .va.cpss.m odel.Proce ssStatus;
  30   import gov .va.cpss.m odel.fps.P SDetails;
  31   import gov .va.cpss.m odel.fps.P SPatient;
  32  
  33   /**
  34    * Service  class for  handling  activities  relating  to consoli dating a p atient
  35    * stateme nt.
  36    * 
  37    * @author   DN S      D N S
  38    */
  39   @Service
  40   public cla ss CbsServ ice {
  41  
  42           pr ivate stat ic final L ogger logg er = Logge r.getLogge r(CbsServi ce.class.g etCanonica lName());
  43  
  44           pr ivate stat ic final i nt MAX_COB OL_FIELD_L ENGTH = 9;
  45  
  46           pr ivate bool ean lateSt atementMes sage;
  47           
  48           pr ivate Proc essStatusD AO process StatusDAO;
  49  
  50           pr ivate CBSA ccountDAO  cbsAccount DAO;
  51  
  52           pr ivate CBSS tmtDAO cbs StmtDAO;
  53  
  54           pr ivate CBSS iteStmtDAO  cbsSiteSt mtDAO;
  55  
  56           pr ivate CBSS itePatient DAO cbsSit ePatientDA O;
  57  
  58           pr ivate CBSS iteTransDA O cbsSiteT ransDAO;
  59  
  60           pu blic CbsSe rvice() {
  61           }
  62  
  63           pu blic boole an getLate StatementM essage() {
  64                    retu rn lateSta tementMess age;
  65           }
  66  
  67           pu blic void  setLateSta tementMess age(boolea n lateStat ementMessa ge) {
  68                    this .lateState mentMessag e = lateSt atementMes sage;
  69           }
  70  
  71           pu blic Proce ssStatusDA O getProce ssStatusDA O() {
  72                    retu rn process StatusDAO;
  73           }
  74  
  75           pu blic void  setProcess StatusDAO( ProcessSta tusDAO pro cessStatus DAO) {
  76                    this .processSt atusDAO =  processSta tusDAO;
  77           }
  78  
  79           pu blic CBSAc countDAO g etCbsAccou ntDAO() {
  80                    retu rn cbsAcco untDAO;
  81           }
  82  
  83           pu blic void  setCbsAcco untDAO(CBS AccountDAO  cbsAccoun tDAO) {
  84                    this .cbsAccoun tDAO = cbs AccountDAO ;
  85           }
  86  
  87           pu blic CBSSt mtDAO getC bsStmtDAO( ) {
  88                    retu rn cbsStmt DAO;
  89           }
  90  
  91           pu blic void  setCbsStmt DAO(CBSStm tDAO cbsSt mtDAO) {
  92                    this .cbsStmtDA O = cbsStm tDAO;
  93           }
  94  
  95           pu blic CBSSi tePatientD AO getCbsS itePatient DAO() {
  96                    retu rn cbsSite PatientDAO ;
  97           }
  98  
  99           pu blic void  setCbsSite PatientDAO (CBSSitePa tientDAO c bsSitePati entDAO) {
  100                    this .cbsSitePa tientDAO =  cbsSitePa tientDAO;
  101           }
  102  
  103           pu blic CBSSi teStmtDAO  getCbsSite StmtDAO()  {
  104                    retu rn cbsSite StmtDAO;
  105           }
  106  
  107           pu blic void  setCbsSite StmtDAO(CB SSiteStmtD AO cbsSite StmtDAO) {
  108                    this .cbsSiteSt mtDAO = cb sSiteStmtD AO;
  109           }
  110  
  111           pu blic CBSSi teTransDAO  getCbsSit eTransDAO( ) {
  112                    retu rn cbsSite TransDAO;
  113           }
  114  
  115           pu blic void  setCbsSite TransDAO(C BSSiteTran sDAO cbsSi teTransDAO ) {
  116                    this .cbsSiteTr ansDAO = c bsSiteTran sDAO;
  117           }
  118           
  119           /* *
  120            *  Build a c onsolidate d statemen t for the  CBS Accoun t to list  of PSPatie nt records
  121            *  map.
  122            *  
  123            *  @param ba tchRunId
  124            *                  The  batch run  ID.
  125            *  @param pa tientMap
  126            *              The map  of records  to consol idate.
  127            *  @return A  consolida ted statem ent.
  128            * /
  129           pu blic CBSSt mt buildSt atementFor PatientMap (final lon g batchRun Id, Entry< Long, List <PSPatient >> patient Map) throw s RuntimeE xception {
  130  
  131                    // F irst, crea te an init ial statem ent for th e records  in the map .
  132                    CBSS tmt statem ent = crea teInitialS tatement(b atchRunId,  patientMa p.getKey() );
  133  
  134                    // T hen proces s the list  of PSPati ent record s.
  135                    if ( processPat ientList(s tatement,  patientMap .getValue( )) > 0) {
  136  
  137                             // Now  check if  this shoul d be a lat e statemen t or if a  new
  138                             // sta tement alr eady exist s for this  patient.
  139                             // If  an unrecov erable err or occurs  false will  be return ed.
  140                             if (!c heckForExi stingState ment(state ment)) {
  141  
  142                                      // An un recoverabl e error ha s occurred  indicatin g the data base
  143                                      // is co rrupted.
  144                                      throw ne w RuntimeE xception(" Unrecovera ble data e rror check ing for ex isting sta tement");
  145                             }
  146  
  147                    } el se {
  148  
  149                             // If  unexpected  data erro r occurs ( patient li st is empt y or no
  150                             // pat ients proc essed) the n log an e rror messa ge and
  151                             // ski p the stat ement.
  152                             logger .error("No  patients  processed  for CBS Ac count: " +  patientMa p.getKey() );
  153  
  154                             // Ret urn null w hich will  skip state ment.
  155                             statem ent = null ;
  156                    }
  157                    
  158                    // S et accntNu mDisp afte r site pat ients have  been proc essed and  statement  merged wit h existing  statement
  159                    setA cntNumDisp (statement );
  160  
  161                    retu rn stateme nt;
  162           }
  163  
  164           /* *
  165            *  Check and  handle ex isting sta tement.
  166            *  
  167            *  @param st atement
  168            *              The cons olidated s tatement.
  169            *  @return F lag indica ting if su ccessfully  checked o r if an un recoverabl e
  170            *          e rror occur red.
  171            * /
  172           pu blic boole an checkFo rExistingS tatement(C BSStmt sta tement) {
  173  
  174                    bool ean succes sful = fal se;
  175  
  176                    // C heck if th is should  be a late  statement  (a stateme nt for thi s month
  177                    // a lready) or  if a new  statement
  178                    // a lready exi sts that n eeds to be  merged.
  179                    fina l Date sta tementDate  = stateme nt.getSite StmtL().ge t(0).getSt atementDat e();
  180  
  181                    // U nrecoverab le error i f statemen t date hap pens to be  null.
  182                    if ( statementD ate != nul l) {
  183  
  184                             // Que ry for exi sting stat ement.
  185                             CBSStm t existing Statement  = getExist ingStateme ntForAccou nt(stateme nt.getAcco untId(), s tatementDa te);
  186  
  187                             // If  an existin g statemen t exists ( !null) the n process  accordingl y.
  188                             if (ex istingStat ement != n ull) {
  189  
  190                                      // Handl e existing  statement  different ly dependi ng on its
  191                                      // statu s.
  192                                      switch ( processSta tusDAO.get StatusType (existingS tatement.g etStatusId ()).getSta tus()) {
  193  
  194                                      case NEW :
  195                                               combineWit hExistingS tatement(s tatement,  existingSt atement);
  196                                               successful  = true;
  197                                               break;
  198                                      case ACK :
  199                                      case ERR OR:
  200                                      case SEN T:
  201                                               setAsLateS tatement(s tatement);
  202                                               successful  = true;
  203                                               break;
  204                                      case INI TIAL:
  205                                      case REP LACED:
  206                                      case UND EFINED:
  207                                      default:
  208                                               logger.err or("Existi ng stateme nt detecte d of inval id status  at time of  query");
  209                                               break;
  210                                      }
  211                             } else  {
  212  
  213                                      // There  is no exi sting stat ement foun d.
  214                                      successf ul = true;
  215                             }
  216                    } el se {
  217  
  218                             logger .error("Un able to ch eck for ex isting sta tement bec ause date  check was  unexpected ly null");
  219                    }
  220  
  221                    retu rn success ful;
  222           }
  223  
  224           /* *
  225            *  Create a  consolidat ed stateme nt object  for the sp ecified ac count numb er.
  226            *  
  227            *  @param ac countNumbe r
  228            *              The acco unt number  to associ ate with t he consoli dated
  229            *              statemen t.
  230            *  @return T he initial ized conso lidated st atement.
  231            * /
  232           pr ivate CBSS tmt create InitialSta tement(fin al long ba tchRunId,  final long  accountNu mber) {
  233  
  234                    // C reate a st atement fo r the acco unt.
  235                    CBSS tmt statem ent = new  CBSStmt(ba tchRunId,  accountNum ber,
  236                                      processS tatusDAO.g etStatusFr omEnum(Pro cessStatus .Status.IN ITIAL));
  237  
  238                    init ializeStat ement(stat ement);
  239  
  240                    retu rn stateme nt;
  241           }
  242  
  243           /* *
  244            *  Combine t he consoli dated stat ement with  the speci fied exist ing statem ent.
  245            *  
  246            *  @param st atement
  247            *              The cons olidated s tatement.
  248            *  @param ex istingStat ement
  249            *              The exis ting conso lidated st atement.
  250            * /
  251           pu blic void  combineWit hExistingS tatement(C BSStmt sta tement, fi nal CBSStm t existing Statement)  {
  252  
  253                    // S ave the re places id.
  254                    stat ement.setR eplacedStm tId(existi ngStatemen t.getId()) ;
  255  
  256                    // I nitialize  the runnin g totals w ith the va lues alrea dy in the
  257                    // s tatement.
  258                    doub le amountD ue = state ment.getAm ountDue(). getDouble( );
  259                    doub le previou sBalance =  statement .getPrevBa lance().ge tDouble();
  260                    doub le totalCh arges = st atement.ge tTotalChar ges().getD ouble();
  261                    doub le totalCr edits = st atement.ge tTotalCred its().getD ouble();
  262                    doub le newBala nce = stat ement.getN ewBalance( ).getDoubl e();
  263  
  264                    // A dd the exi sting stat ement valu es.
  265                    amou ntDue += e xistingSta tement.get AmountDue( ).getDoubl e();
  266                    prev iousBalanc e += exist ingStateme nt.getPrev Balance(). getDouble( );
  267                    tota lCharges + = existing Statement. getTotalCh arges().ge tDouble();
  268                    tota lCredits + = existing Statement. getTotalCr edits().ge tDouble();
  269                    newB alance +=  existingSt atement.ge tNewBalanc e().getDou ble();
  270  
  271                    // S ave the va lues.
  272                    setA mountDue(s tatement,  amountDue) ;
  273                    setP revBalance (statement , previous Balance);
  274                    setT otalCharge s(statemen t, totalCh arges);
  275                    setT otalCredit s(statemen t, totalCr edits);
  276                    setN ewBalance( statement,  newBalanc e);
  277  
  278                    // A ppend the  existing l ist of sit e statemen ts to the  new statem ent.
  279                    List <CBSSiteSt mt> siteSt atementL =  statement .getSiteSt mtL();
  280                    site StatementL .addAll(ex istingStat ement.getS iteStmtL() );
  281                    setP rimarySite Flags(stat ement, sit eStatement L);
  282                    stat ement.setS iteStmtL(s iteStateme ntL);
  283                    
  284                    // T ake the va lue of the  existing  statement  late state ment messa ge.
  285                    stat ement.setL ateStmtMsg (existingS tatement.g etLateStmt Msg());
  286           }
  287  
  288           /* *
  289            *  Set the l ate messag e in the s tatement.
  290            *  
  291            *  @param st atement
  292            *              The stat ement that  is late.
  293            * /
  294           pr ivate void  setAsLate Statement( CBSStmt st atement) {
  295                    stat ement.setL ateStmtMsg (lateState mentMessag e);
  296           }
  297  
  298           /* *
  299            *  Initializ e a consol idated sta tement val ues.
  300            *  
  301            *  @param st atement
  302            * /
  303           pr ivate void  initializ eStatement (CBSStmt s tatement)  {
  304  
  305                    fina l Timestam p currentT ime = new  Timestamp( Calendar.g etInstance ().getTime ().getTime ());
  306  
  307                    stat ement.setS iteStmtL(n ew ArrayLi st<>());
  308  
  309                    setA mountDue(s tatement,  0);
  310                    setP revBalance (statement , 0);
  311                    setT otalCharge s(statemen t, 0);
  312                    setT otalCredit s(statemen t, 0);
  313                    setN ewBalance( statement,  0);
  314  
  315                    stat ement.setC reatedDate (currentTi me);
  316                    stat ement.setM odifiedDat e(currentT ime);
  317  
  318                    stat ement.setL ateStmtMsg (false);
  319           }
  320  
  321           pu blic void  setAmountD ue(CBSStmt  statement , final do uble value ) {
  322                    stat ement.setA mountDue(n ew Money(v alue, MAX_ COBOL_FIEL D_LENGTH)) ;
  323           }
  324  
  325           pu blic void  setPrevBal ance(CBSSt mt stateme nt, final  double val ue) {
  326                    stat ement.setP revBalance (new Money (value, MA X_COBOL_FI ELD_LENGTH ));
  327           }
  328  
  329           pu blic void  setTotalCh arges(CBSS tmt statem ent, final  double va lue) {
  330                    stat ement.setT otalCharge s(new Mone y(value, M AX_COBOL_F IELD_LENGT H));
  331           }
  332  
  333           pu blic void  setTotalCr edits(CBSS tmt statem ent, final  double va lue) {
  334                    stat ement.setT otalCredit s(new Mone y(value, M AX_COBOL_F IELD_LENGT H));
  335           }
  336  
  337           pu blic void  setNewBala nce(CBSStm t statemen t, final d ouble valu e) {
  338                    stat ement.setN ewBalance( new Money( value, MAX _COBOL_FIE LD_LENGTH) );
  339           }
  340           
  341           pu blic void  setAcntNum Disp(CBSSt mt stateme nt) {
  342                    stat ement.setA cntNumDisp (CBSStmt.c reateAcntN umDisp(sta tement));
  343           }
  344  
  345           /* *
  346            *  Identify  the approp riate site  statement s for prim ary patien t data and
  347            *  primary p atient add ress.
  348            *  
  349            *  @param si teStatemen tL
  350            *              The list  of site s tatements  for which  to calcula te primary
  351            *              flags.
  352            * /
  353           pu blic void  setPrimary SiteFlags( CBSStmt st atement, L ist<CBSSit eStmt> sit eStatement L) {
  354  
  355                    // I f there is  only one  site state ment then  this is ea sy.
  356                    if ( siteStatem entL.size( ) == 1) {
  357  
  358                             siteSt atementL.g et(0).setI sPrimary(B ooleanChar .Y);
  359                             siteSt atementL.g et(0).setI sPrimaryAd dress(Bool eanChar.Y) ;
  360  
  361                             // Set  the state ment dates  to the da tes of the  primary s ite
  362                             // sta tement.
  363                             setSta tementDate s(statemen t, siteSta tementL.ge t(0));
  364  
  365                    } el se {
  366  
  367                             // If  there are  multiple s ite statem ents then  it is more
  368                             // com plicated.
  369  
  370                             // Fir st, initia lize all t he sites t o not prim ary.
  371                             // Whi le doing s o, count t he number  of AR flag s.
  372                             int ar FlagCount  = 0;
  373                             for (C BSSiteStmt  siteState ment : sit eStatement L) {
  374  
  375                                      siteStat ement.setI sPrimary(B ooleanChar .N);
  376                                      siteStat ement.setI sPrimaryAd dress(Bool eanChar.N) ;
  377  
  378                                      // Count  how many  sites have  the AR fl ag set.
  379                                      if (site Statement. getArAddre ssFlag().i sTrue()) {
  380                                               arFlagCoun t++;
  381                                      }
  382                             }
  383  
  384                             // Sor t statemen ts by most  recent la stBillPrep Date to id entify
  385                             // isP rimary
  386                             Collec tions.sort (siteState mentL, new  Comparato r<CBSSiteS tmt>() {
  387                                      public i nt compare (CBSSiteSt mt o1, CBS SiteStmt o 2) {
  388                                               if (o1.get LastBillPr epDate() = = null) {
  389                                                       //  If o1 nul l, then as sume older .
  390                                                       re turn 1;
  391                                               } else if  (o2.getLas tBillPrepD ate() == n ull) {
  392                                                       //  If o2 is  then assum e o1 is ne wer.
  393                                                       re turn -1;
  394                                               } else {
  395                                                       //  Desire mo st recent  date, so c ompare o2  to o1.
  396                                                       re turn o2.ge tLastBillP repDate(). compareTo( o1.getLast BillPrepDa te());
  397                                               }
  398                                      }
  399                             });
  400  
  401                             // The  most rece nt will be  sorted fi rst.
  402                             // It  will be us ed for Pat ient Detai ls.
  403                             // Set  the first  in the co llection t o isPrimar y for Pati ent Detail s.
  404                             siteSt atementL.g et(0).setI sPrimary(B ooleanChar .Y);
  405  
  406                             // Set  the state ment dates  to the da tes of the  primary s ite
  407                             // sta tement.
  408                             setSta tementDate s(statemen t, siteSta tementL.ge t(0));
  409  
  410                             // Use  different  logic to  identify t he primary  site stat ement to u se
  411                             // for  the Patie nt
  412                             // Add ress
  413  
  414                             if (ar FlagCount  == 1) {
  415  
  416                                      // If ex actly one  AR flag fo und then u se that si te stateme nt as
  417                                      // the P rimary Add ress.
  418                                      for (CBS SiteStmt s iteStateme nt : siteS tatementL)  {
  419                                               if (siteSt atement.ge tArAddress Flag().isT rue()) {
  420                                                       si teStatemen t.setIsPri maryAddres s(BooleanC har.Y);
  421                                                       br eak;
  422                                               }
  423                                      }
  424  
  425                             } else  {
  426  
  427                                      // If th ere is mor e than one  AR flag o r if there  are no AR  flags
  428                                      // then  use the fi rst in the  sorted co llection j ust like h ow
  429                                      // Patie nt
  430                                      // Detai ls is dete rmined.
  431                                      siteStat ementL.get (0).setIsP rimaryAddr ess(Boolea nChar.Y);
  432                             }
  433                    }
  434           }
  435  
  436           /* *
  437            *  Set the s tatement d ates using  the prima ry site st atement da te values.
  438            *  
  439            *  @param st atement
  440            *              The stat ement to u pdate.
  441            *  @param si teStatemen t
  442            *              The site  statement  as refere nce.
  443            * /
  444           pr ivate void  setStatem entDates(C BSStmt sta tement, fi nal CBSSit eStmt site Statement)  {
  445                    // S et the sta tement val ues to poi nt to the  primary da tes.
  446                    stat ement.setS tatementDa te(siteSta tement.get StatementD ate());
  447                    stat ement.setP rocessDate (siteState ment.getPr ocessDate( ));
  448           }
  449  
  450           /* *
  451            *  Process t he list of  raw PSPat ient recor ds and rol l processe d data int o
  452            *  the conso lidated st atement.
  453            *  
  454            *  @param st atement
  455            *              The cons olidated s tatement t o update.
  456            *  @param ps PatientL
  457            *              The list  of PSPati ent record s.
  458            *  @return N umber of p atients pr ocessed.
  459            * /
  460           pu blic int p rocessPati entList(CB SStmt stat ement, fin al List<PS Patient> p sPatientL)  {
  461  
  462                    int  processedC ount = 0;
  463  
  464                    if ( (psPatient L == null)  || psPati entL.isEmp ty()) {
  465  
  466                             // Une xpected er ror that s hould neve r happen.
  467                             logger .error("Pa tient list  was unexp ectedly em pty!");
  468  
  469                    } el se {
  470  
  471                             // Get  the site  statement  list.
  472                             List<C BSSiteStmt > siteStat ementL = s tatement.g etSiteStmt L();
  473  
  474                             // Ini tialize th e running  totals wit h the valu es already  in the
  475                             // sta tement.
  476                             double  amountDue  = stateme nt.getAmou ntDue().ge tDouble();
  477                             double  previousB alance = s tatement.g etPrevBala nce().getD ouble();
  478                             double  totalChar ges = stat ement.getT otalCharge s().getDou ble();
  479                             double  totalCred its = stat ement.getT otalCredit s().getDou ble();
  480                             double  newBalanc e = statem ent.getNew Balance(). getDouble( );
  481  
  482                             for (P SPatient p sPatient :  psPatient L) {
  483                                      logger.i nfo("Proce ssing Pati ent: " + p sPatient.g etIcnNumbe r());
  484  
  485                                      // Creat e CBSSiteS tmt associ ated with  the PSPati ent record .
  486                                      CBSSiteS tmt siteSt atement =  getSiteSta tementForP atient(psP atient);
  487  
  488                                      // Calcu late Total s for Cons olidated S tatement
  489                                      amountDu e += siteS tatement.g etAmountDu e().getDou ble();
  490                                      previous Balance +=  siteState ment.getPr evBalance( ).getDoubl e();
  491                                      totalCha rges += si teStatemen t.getTotal Charges(). getDouble( );
  492                                      totalCre dits += si teStatemen t.getTotal Credits(). getDouble( );
  493                                      newBalan ce += site Statement. getNewBala nce().getD ouble();
  494  
  495                                      // Appen d the site  statement  to the li st.
  496                                      siteStat ementL.add (siteState ment);
  497  
  498                                      // Incre ment the n umber of p atients pr ocessed.
  499                                      processe dCount++;
  500                             }
  501  
  502                             if (!s iteStateme ntL.isEmpt y()) {
  503                                      // Ident ify Primar y Site (Pa tient Deta ils) and P rimary Sit e
  504                                      // (Addr ess)
  505                                      setPrima rySiteFlag s(statemen t, siteSta tementL);
  506  
  507                                      // Set t he site st atement li st in the  Consolidat ed Stateme nt
  508                                      statemen t.setSiteS tmtL(siteS tatementL) ;
  509  
  510                                      // Set t he calcula ted totals .
  511                                      setAmoun tDue(state ment, amou ntDue);
  512                                      setPrevB alance(sta tement, pr eviousBala nce);
  513                                      setTotal Charges(st atement, t otalCharge s);
  514                                      setTotal Credits(st atement, t otalCredit s);
  515                                      setNewBa lance(stat ement, new Balance);
  516                             }
  517                    }
  518  
  519                    retu rn process edCount;
  520           }
  521  
  522           /* *
  523            *  Build a s ite statem ent associ ated with  the patien t record.
  524            *  
  525            *  @param ps Patient
  526            *              The pati ent record .
  527            *  @return A  site stat ement asso ciated wit h the spec ified pati ent record .
  528            * /
  529           pr ivate CBSS iteStmt ge tSiteState mentForPat ient(final  PSPatient  psPatient ) {
  530  
  531                    fina l Timestam p currentT ime = new  Timestamp( Calendar.g etInstance ().getTime ().getTime ());
  532  
  533                    CBSS iteStmt si teStatemen t = new CB SSiteStmt( );
  534                    site Statement. setStation Num(psPati ent.getPsS ite().getF acilityNum ());
  535                    site Statement. setStation PhoneNum(p sPatient.g etPsSite() .getFacili tyPhoneNum ());
  536                    site Statement. setProcess Date(psPat ient.getPs Site().get ProcessDat e());
  537                    site Statement. setStateme ntDate(psP atient.get PsSite().g etStatemen tDate());
  538                    site Statement. setAmountD ue(psPatie nt.getAmou ntDue());
  539                    site Statement. setPrevBal ance(psPat ient.getPr evBalance( ));
  540                    site Statement. setTotalCh arges(psPa tient.getT otalCharge s());
  541                    site Statement. setTotalCr edits(psPa tient.getT otalCredit s());
  542                    site Statement. setNewBala nce(psPati ent.getNew Balance()) ;
  543                    site Statement. setSpecial Notes(psPa tient.getS pecialNote s());
  544                    site Statement. setNoParaC des(psPati ent.getRig htsObligat ionParagra phCodes()) ;
  545                    site Statement. setLargeFo ntInd(psPa tient.getL argeFontIn d());
  546                    site Statement. setArAddre ssFlag(psP atient.get AddressFla g());
  547                    site Statement. setLastBil lPrepDate( psPatient. getLastBil lPrepDate( ));
  548                    site Statement. setIsPrima ry(Boolean Char.N);
  549                    site Statement. setIsPrima ryAddress( BooleanCha r.N);
  550                    site Statement. setCreated Date(curre ntTime);
  551                    site Statement. setModifie dDate(curr entTime);
  552  
  553                    CBSS itePatient  sitePatie nt = new C BSSitePati ent();
  554                    site Patient.se tIcn(psPat ient.getIc nNumber()) ;
  555                    site Patient.se tDfn(psPat ient.getDf nNumber()) ;
  556                    site Patient.se tOldAcntNu m(psPatien t.getPatie ntAccount( ));
  557                    site Patient.se tFirstName (psPatient .getPatien tFirstName ());
  558                    site Patient.se tLastName( psPatient. getPatient LastName() );
  559                    site Patient.se tMiddleNam e(psPatien t.getPatie ntMiddleNa me());
  560                    site Patient.se tAddress1( psPatient. getAddress 1());
  561                    site Patient.se tAddress2( psPatient. getAddress 2());
  562                    site Patient.se tAddress3( psPatient. getAddress 3());
  563                    site Patient.se tCity(psPa tient.getC ity());
  564                    site Patient.se tState(psP atient.get State());
  565                    site Patient.se tZipCode(p sPatient.g etZipCode( ));
  566                    site Patient.se tCountry(p sPatient.g etCountryN ame());
  567                    site Patient.se tCreatedDa te(current Time);
  568                    site Patient.se tModifiedD ate(curren tTime);
  569                    site Statement. setSitePat ient(siteP atient);
  570  
  571                    List <CBSSiteTr ans> siteT ransL = ne w ArrayLis t<>();
  572                    for  (PSDetails  details :  psPatient .getPsDeta ilsL()) {
  573  
  574                             CBSSit eTrans sit eTrans = n ew CBSSite Trans();
  575                             siteTr ans.setDat ePosted(de tails.getD atePosted( ));
  576                             siteTr ans.setTra nsDesc(det ails.getTr ansDesc()) ;
  577                             siteTr ans.setTra nsAmount(d etails.get TransAmoun t());
  578                             siteTr ans.setRef erenceNum( details.ge tReference Num());
  579                             siteTr ans.setOrd erNum(deta ils.getSeq Num());
  580                             siteTr ans.setCre atedDate(c urrentTime );
  581                             siteTr ans.setMod ifiedDate( currentTim e);
  582                             siteTr ansL.add(s iteTrans);
  583                    }
  584                    site Statement. setSiteTra nsL(siteTr ansL);
  585  
  586                    retu rn siteSta tement;
  587           }
  588  
  589           /* *
  590            *  Save an s tatement a nd update  the databa se auto ge nerated ID .
  591            *  
  592            *  @param st atement
  593            *              The cons olidated s tatement.
  594            *  @return T he updated  statement  populated  with the  auto gener ated ID.
  595            * /
  596           pu blic void  saveStatem ent(CBSStm t statemen t) {
  597  
  598                    stat ement.setI d(cbsStmtD AO.save(st atement));
  599           }
  600  
  601           /* *
  602            *  Save an s ite patien t and upda te the dat abase auto  generated  ID.
  603            *  
  604            *  @param si tePatient
  605            *              The site  patient.
  606            *  @return T he updated  site pati ent popula ted with t he auto ge nerated ID .
  607            * /
  608           pu blic void  savePatien t(CBSSiteP atient sit ePatient)  {
  609  
  610                    site Patient.se tId(cbsSit ePatientDA O.save(sit ePatient)) ;
  611           }
  612  
  613           /* *
  614            *  Save an s ite statem ent and up date the d atabase au to generat ed ID.
  615            *  
  616            *  @param si teStatemen t
  617            *              The site  statement .
  618            *  @return T he updated  site stat ement popu lated with  the auto  generated  ID.
  619            * /
  620           pu blic void  saveSiteSt atement(CB SSiteStmt  siteStatem ent) {
  621  
  622                    site Statement. setId(cbsS iteStmtDAO .save(site Statement) );
  623           }
  624  
  625           /* *
  626            *  Query the  database  for an exi sting stat ement for  this accou nt for the
  627            *  same mont h as the s pecified d ate.
  628            *  
  629            *  @param ac countNumbe r
  630            *              The acco unt number  for the s tatement.
  631            *  @param st atementDat e
  632            *              The date  for this  month.
  633            *  @return T he existin g statemen t or null  if does no t exist.
  634            * /
  635           pr ivate CBSS tmt getExi stingState mentForAcc ount(final  long acco untNumber,  final Dat e statemen tDate) {
  636  
  637                    CBSS tmt statem ent = cbsS tmtDAO.get ExistingSt atementByA ccountAndM onth(accou ntNumber,  statementD ate);
  638  
  639                    if ( statement  != null) {
  640  
  641                             // The n get all  CBSSiteStm t from dat abase.
  642                             List<C BSSiteStmt > siteStat ementL = c bsSiteStmt DAO.getAll ByCBSStmtI D(statemen t.getId(),  true);
  643  
  644                             // The n get all  CBSSiteTra ns from da tabase.
  645                             if ((s iteStateme ntL != nul l) && !sit eStatement L.isEmpty( )) {
  646  
  647                                      List<CBS SiteTrans>  siteTrans L = cbsSit eTransDAO. getAllByCB SSiteStmtI D(statemen t.getId()) ;
  648  
  649                                      // Sort  into a map  (CBSSiteS tmt.ID to  List<CBSSi teTrans>)  for
  650                                      // the
  651                                      // list  of CBSSite Trans.
  652                                      Map<Long , List<CBS SiteTrans> > transQue ryM = site TransL.str eam()
  653                                                       .c ollect(Col lectors.gr oupingBy(w  -> w.getS iteStmtId( )));
  654  
  655                                      // Set t he appropr iate trans  list in t he CBSSite Stmt.
  656                                      for (CBS SiteStmt s iteStmt :  siteStatem entL) {
  657                                              
  658                                               logger.deb ug("SITEST MT.ID: " +  siteStmt. getId());
  659                                              
  660                                               List<CBSSi teTrans> s iteTransMa pEntry = t ransQueryM .get(siteS tmt.getId( ));
  661                                               // If no l ist then a n unrecove rable data  error.
  662                                               if (siteTr ansMapEntr y != null)  {
  663  
  664                                                       si teStmt.set SiteTransL (siteTrans MapEntry);
  665                                               } else {
  666                                                       fi nal String  error = " Unrecovera ble data e rror, site  trans map  is null f or site";
  667                                                       lo gger.error (error);
  668                                                       th row new Ru ntimeExcep tion(error );
  669                                               }
  670                                      }
  671  
  672                                      // Add t he site st atement li st to the  statement.
  673                                      statemen t.setSiteS tmtL(siteS tatementL) ;
  674                             } else  {
  675                                      final St ring error  = "Unreco verable da ta error,  site state ment list  is null or  empty";
  676                                      logger.e rror(error );
  677                                      throw ne w RuntimeE xception(e rror);
  678                             }
  679                    }
  680  
  681                    retu rn stateme nt;
  682           }
  683  
  684           /* *
  685            *  Publish t he INITIAL  statement s to NEW s tatus.
  686            *  
  687            *  @return T he number  of stateme nts that w ere update d.
  688            * /
  689           pu blic int p ublishAllN ewStatemen ts() {
  690  
  691                    Inte ger initia lStatus =  processSta tusDAO.get StatusFrom Enum(Proce ssStatus.S tatus.INIT IAL);
  692                    Inte ger newSta tus = proc essStatusD AO.getStat usFromEnum (ProcessSt atus.Statu s.NEW);
  693  
  694                    if ( (initialSt atus != nu ll) && (ne wStatus !=  null)) {
  695  
  696                             return  cbsStmtDA O.updateAl lStatusFro mTo(initia lStatus, n ewStatus);
  697                    } el se {
  698  
  699                             logger .error("Un able to ob tain statu s mapping  for: " + P rocessStat us.Status. INITIAL +  " or "
  700                                               + ProcessS tatus.Stat us.NEW);
  701                    }
  702  
  703                    retu rn 0;
  704           }
  705  
  706           /* *
  707            *  Revert th e REPLACED  statement s to NEW s tatus that  are assoc iated with  INITIAL s tatements.
  708            *  
  709            *  @return T he number  of stateme nts that w ere update d.
  710            * /
  711           pu blic int r evertRepla cedStateme ntsAssocia tedWithIni tialStatem ents() {
  712                    
  713                    int  revertedCo unt = -1;
  714  
  715                    Inte ger initia lStatus =  processSta tusDAO.get StatusFrom Enum(Proce ssStatus.S tatus.INIT IAL);
  716                    Inte ger replac edStatus =  processSt atusDAO.ge tStatusFro mEnum(Proc essStatus. Status.REP LACED);
  717                    Inte ger newSta tus = proc essStatusD AO.getStat usFromEnum (ProcessSt atus.Statu s.NEW);
  718  
  719                    if ( (initialSt atus != nu ll) && (re placedStat us != null ) && (newS tatus != n ull)) {
  720  
  721                             revert edCount =  cbsStmtDAO .updateSta tusFromToF orInitial( replacedSt atus, newS tatus, ini tialStatus );
  722                    } el se {
  723  
  724                             logger .error("Un able to ob tain statu s mapping  for: " + P rocessStat us.Status. INITIAL +  " or " + P rocessStat us.Status. REPLACED +  " or "
  725                                               + ProcessS tatus.Stat us.NEW);
  726                    }
  727  
  728                    retu rn reverte dCount;
  729           }
  730  
  731           /* *
  732            *  Remove st atements t hat have I NITIAL sta tus.
  733            *  
  734            *  @return T he number  of stateme nts that w ere update d.
  735            * /
  736           pu blic int r emoveIniti alStatemen ts() {
  737                    
  738                    int  removedCou nt = -1;
  739  
  740                    Inte ger initia lStatus =  processSta tusDAO.get StatusFrom Enum(Proce ssStatus.S tatus.INIT IAL);
  741  
  742                    if ( initialSta tus != nul l) {
  743  
  744                             remove dCount = c bsStmtDAO. deleteBySt atusId(ini tialStatus );
  745                    } el se {
  746  
  747                             logger .error("Un able to ob tain statu s mapping  for: " + P rocessStat us.Status. INITIAL);
  748                    }
  749  
  750                    retu rn removed Count;
  751           }
  752  
  753           /* *
  754            *  Query the  number of  consolida ted statem ents in th e NEW stat e.
  755            *  
  756            *  @return T he number  of consoli dated stat ements in  the NEW st ate or nul l if
  757            *          e rror.
  758            * /
  759           pu blic Long  getCountOf Statements InState(fi nal Proces sStatus.St atus state ) {
  760  
  761                    Long  available Count = nu ll;
  762  
  763                    Inte ger status  = process StatusDAO. getStatusF romEnum(st ate);
  764  
  765                    if ( status !=  null) {
  766  
  767                             availa bleCount =  cbsStmtDA O.getState mentCountW ithStatus( status);
  768  
  769                             if (av ailableCou nt == null ) {
  770  
  771                                      logger.e rror("Inva lid count  when check ing for co unt of sta tements");
  772                             }
  773  
  774                    } el se {
  775  
  776                             logger .error("Un able to ob tain statu s mapping  for: " + s tate);
  777                    }
  778  
  779                    retu rn availab leCount;
  780           }
  781  
  782   }